diff --git a/backend/src/hatchling/version/source/env.py b/backend/src/hatchling/version/source/env.py index b46389437..97191b7bf 100644 --- a/backend/src/hatchling/version/source/env.py +++ b/backend/src/hatchling/version/source/env.py @@ -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]} diff --git a/docs/plugins/version-source/env.md b/docs/plugins/version-source/env.md index 125b23104..ac0486ede 100644 --- a/docs/plugins/version-source/env.md +++ b/docs/plugins/version-source/env.md @@ -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. | diff --git a/tests/backend/version/source/test_env.py b/tests/backend/version/source/test_env.py index 3e8d74847..a840b634c 100644 --- a/tests/backend/version/source/test_env.py +++ b/tests/backend/version/source/test_env.py @@ -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'