Skip to content

Support default version for env version source #1854

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions backend/src/hatchling/version/source/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,14 @@ def get_version_data(self) -> dict:
raise TypeError(message)

if variable not in os.environ:
message = f'environment variable `{variable}` is not set'
raise RuntimeError(message)
default = self.config.get('default')
if default is None:
message = f'environment variable `{variable}` is not set and the `default` option was not set'
raise RuntimeError(message)
if not isinstance(default, str):
message = 'option `default` must be a string'
raise TypeError(message)
return {'version': default}

return {'version': os.environ[variable]}

Expand Down
1 change: 1 addition & 0 deletions docs/plugins/version-source/env.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ source = "env"
| Option | Description |
| --- | --- |
| `variable` (required) | The name of the environment variable |
| `default` | The value to use for the version if the specified environment variable is not set. |
14 changes: 14 additions & 0 deletions tests/backend/version/source/test_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,22 @@ def test_variable_not_available(isolation):
source.get_version_data()


def test_variable_not_available_with_default(isolation):
source = EnvSource(str(isolation), {'variable': 'ENV_VERSION', 'default': '0.0.0'})

with EnvVars(exclude=['ENV_VERSION']):
assert source.get_version_data()['version'] == '0.0.0'


def test_variable_contains_version(isolation):
source = EnvSource(str(isolation), {'variable': 'ENV_VERSION'})

with EnvVars({'ENV_VERSION': '0.0.1'}):
assert source.get_version_data()['version'] == '0.0.1'


def test_variable_contains_version_with_default(isolation):
source = EnvSource(str(isolation), {'variable': 'ENV_VERSION', 'default': '0.0.0'})

with EnvVars({'ENV_VERSION': '0.0.1'}):
assert source.get_version_data()['version'] == '0.0.1'