Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
ofek committed Aug 17, 2024
1 parent 48351d9 commit 66f3bc3
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 42 deletions.
4 changes: 1 addition & 3 deletions backend/src/hatchling/cli/version/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ def version_impl(
*,
called_by_app: bool, # noqa: ARG001
desired_version: str,
force: bool = False,
) -> None:
import os

Expand Down Expand Up @@ -38,7 +37,7 @@ def version_impl(
app.display(original_version)
return

updated_version = metadata.hatch.version.scheme.update(desired_version, original_version, version_data, force=force)
updated_version = metadata.hatch.version.scheme.update(desired_version, original_version, version_data)
source.set_version(updated_version, version_data)

app.display_info(f'Old: {original_version}')
Expand All @@ -49,5 +48,4 @@ def version_command(subparsers: argparse._SubParsersAction, defaults: Any) -> No
parser = subparsers.add_parser('version')
parser.add_argument('desired_version', default='', nargs='?', **defaults)
parser.add_argument('--app', dest='called_by_app', action='store_true', help=argparse.SUPPRESS)
parser.add_argument('--force', dest='force', action='store_true', help=argparse.SUPPRESS)
parser.set_defaults(func=version_impl)
4 changes: 4 additions & 0 deletions backend/src/hatchling/utils/constants.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
DEFAULT_BUILD_SCRIPT = 'hatch_build.py'
DEFAULT_CONFIG_FILE = 'hatch.toml'


class VersionEnvVars:
VALIDATE_BUMP = 'HATCH_VERSION_VALIDATE_BUMP'
32 changes: 29 additions & 3 deletions backend/src/hatchling/version/scheme/plugin/interface.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

import os
from abc import ABC, abstractmethod
from functools import cached_property


class VersionSchemeInterface(ABC): # no cov
Expand Down Expand Up @@ -51,9 +53,33 @@ def config(self) -> dict:
"""
return self.__config

@cached_property
def validate_bump(self) -> bool:
"""
This is the value of the `validate-bump` option, with the `HATCH_VERSION_VALIDATE_BUMP`
environment variable taking precedence. Validation is enabled by default.
```toml config-example
[tool.hatch.version]
validate-bump = true
```
"""
from hatchling.utils.constants import VersionEnvVars

if VersionEnvVars.VALIDATE_BUMP in os.environ:
return os.environ[VersionEnvVars.VALIDATE_BUMP] not in {'false', '0'}

validate_bump = self.config.get('validate-bump', True)
if not isinstance(validate_bump, bool):
message = 'option `validate-bump` must be a boolean'
raise TypeError(message)

return validate_bump

@abstractmethod
def update(self, desired_version: str, original_version: str, version_data: dict, *, force: bool = False) -> str:
def update(self, desired_version: str, original_version: str, version_data: dict) -> str:
"""
This should return a normalized form of the desired version and verify that it
is higher than the original version.
This should return a normalized form of the desired version. If the
[validate_bump](reference.md#hatchling.version.scheme.plugin.interface.VersionSchemeInterface.validate_bump)
property is `True`, this method should also verify that the version is higher than the original version.
"""
8 changes: 1 addition & 7 deletions backend/src/hatchling/version/scheme/standard.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ def update(
desired_version: str,
original_version: str,
version_data: dict, # noqa: ARG002
*,
force: bool = False,
) -> str:
from packaging.version import Version

Expand Down Expand Up @@ -59,11 +57,7 @@ def update(
raise ValueError(message)

next_version = Version(version)
if next_version <= original and not force and self.config.get('validate-bump', True):
# `hatch version --force` takes precedence and allows a
# downgrade. There is no --no-force option. If --force
# is not given, then consult the `validate-bump`
# configuration option.
if self.validate_bump and next_version <= original:
message = f'Version `{version}` is not higher than the original version `{original_version}`'
raise ValueError(message)

Expand Down
1 change: 1 addition & 0 deletions docs/plugins/version-scheme/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@
- PLUGIN_NAME
- root
- config
- validate_bump
- update
28 changes: 5 additions & 23 deletions src/hatch/cli/version/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,10 @@
'--force',
'-f',
is_flag=True,
default=False,
show_default=True,
help='Allow an explicit downgrading version to be given',
)
@click.pass_obj
def version(app: Application, desired_version: str | None, *, force: bool):
def version(app: Application, *, desired_version: str | None, force: bool):
"""View or set a project's version."""
if app.project.root is None:
if app.project.chosen_name is None:
Expand All @@ -34,6 +32,7 @@ def version(app: Application, desired_version: str | None, *, force: bool):
app.display(app.project.metadata.config['project']['version'])
return

from hatch.config.constants import VersionEnvVars
from hatch.project.constants import BUILD_BACKEND

with app.project.location.as_cwd():
Expand All @@ -48,35 +47,18 @@ def version(app: Application, desired_version: str | None, *, force: bool):
project_metadata = app.project.build_frontend.get_core_metadata()

app.display(project_metadata['version'])
elif 'version' not in app.project.metadata.dynamic:
source = app.project.metadata.hatch.version.source

version_data = source.get_version_data()
original_version = version_data['version']

if not desired_version:
app.display(original_version)
return

updated_version = app.project.metadata.hatch.version.scheme.update(
desired_version, original_version, version_data
)
source.set_version(updated_version, version_data)

app.display_info(f'Old: {original_version}')
app.display_info(f'New: {updated_version}')
else:
from hatch.utils.runner import ExecutionContext

app.ensure_environment_plugin_dependencies()
app.project.prepare_build_environment()

context = ExecutionContext(app.project.build_env)
command = ['python', '-u', '-m', 'hatchling', 'version']
if desired_version:
if force:
command.append('--force')
command.append(desired_version)
if force:
context.env_vars[VersionEnvVars.VALIDATE_BUMP] = 'false'

context = ExecutionContext(app.project.build_env)
context.add_shell_command(command)
app.execute_context(context)
4 changes: 4 additions & 0 deletions src/hatch/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,7 @@ class PythonEnvVars:
CUSTOM_SOURCE_PREFIX = 'HATCH_PYTHON_CUSTOM_SOURCE_'
CUSTOM_PATH_PREFIX = 'HATCH_PYTHON_CUSTOM_PATH_'
CUSTOM_VERSION_PREFIX = 'HATCH_PYTHON_CUSTOM_VERSION_'


class VersionEnvVars:
VALIDATE_BUMP = 'HATCH_VERSION_VALIDATE_BUMP'
16 changes: 10 additions & 6 deletions tests/backend/version/scheme/test_standard.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import pytest
from packaging.version import _parse_letter_version # noqa: PLC2701

from hatch.utils.structures import EnvVars
from hatchling.utils.constants import VersionEnvVars
from hatchling.version.scheme.standard import StandardScheme


Expand All @@ -11,23 +13,25 @@ def test_not_higher(isolation):
scheme.update('1.0.0', '1.0', {})


def test_not_higher_with_force(isolation):
scheme = StandardScheme(str(isolation), {})
assert scheme.update('1.9.0', '2.0.0', {}, force=True) == '1.9.0'


def test_specific(isolation):
scheme = StandardScheme(str(isolation), {})

assert scheme.update('9000.0.0-rc.1', '1.0', {}) == '9000.0.0rc1'


def test_specific_not_higher_allowed(isolation):
def test_specific_not_higher_allowed_config(isolation):
scheme = StandardScheme(str(isolation), {'validate-bump': False})

assert scheme.update('0.24.4', '1.0.0.dev0', {}) == '0.24.4'


def test_specific_not_higher_allowed_env_var(isolation):
scheme = StandardScheme(str(isolation), {})

with EnvVars({VersionEnvVars.VALIDATE_BUMP: 'false'}):
assert scheme.update('0.24.4', '1.0.0.dev0', {}) == '0.24.4'


def test_release(isolation):
scheme = StandardScheme(str(isolation), {})

Expand Down

0 comments on commit 66f3bc3

Please sign in to comment.