diff --git a/backend/src/hatchling/version/source/env.py b/backend/src/hatchling/version/source/env.py index b46389437..4d80c6e13 100644 --- a/backend/src/hatchling/version/source/env.py +++ b/backend/src/hatchling/version/source/env.py @@ -19,6 +19,9 @@ def get_version_data(self) -> dict: raise TypeError(message) if variable not in os.environ: + default = self.config.get('default', '') + if default: + return {'version': default} message = f'environment variable `{variable}` is not set' raise RuntimeError(message) 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'