diff --git a/spk/build/_sources.py b/spk/build/_sources.py index 3dacf79ce0..4dcc94a114 100644 --- a/spk/build/_sources.py +++ b/spk/build/_sources.py @@ -6,7 +6,7 @@ from .. import api, storage from ._env import data_path -from ._binary import BuildError +from ._binary import BuildError, get_package_build_env _LOGGER = structlog.get_logger("spk.build") @@ -91,12 +91,18 @@ def collect_sources(spec: api.Spec, source_dir: str) -> None: """Collect the sources for a spec in the given directory.""" os.makedirs(source_dir) - for source in spec.sources: - - target_dir = source_dir - subdir = source.subdir - if subdir: - target_dir = os.path.join(source_dir, subdir.lstrip("/")) - os.makedirs(target_dir, exist_ok=True) - - source.collect(target_dir) + original_env = os.environ.copy() + os.environ.update(get_package_build_env(spec)) + try: + for source in spec.sources: + + target_dir = source_dir + subdir = source.subdir + if subdir: + target_dir = os.path.join(source_dir, subdir.lstrip("/")) + os.makedirs(target_dir, exist_ok=True) + + source.collect(target_dir) + finally: + os.environ.clear() + os.environ.update(original_env) diff --git a/spk/build/_sources_test.py b/spk/build/_sources_test.py index d779f92575..085b496289 100644 --- a/spk/build/_sources_test.py +++ b/spk/build/_sources_test.py @@ -1,5 +1,6 @@ import os import tarfile +from typing import Any import py.path @@ -39,3 +40,42 @@ def test_sources_subdir(tmpdir: py.path.local) -> None: assert not dest_dir.join("local/.git").exists(), "should exclude git repo" assert dest_dir.join("local/file.txt").isfile() assert dest_dir.join("local/source_file.txt").isfile() + + +def test_sources_environment(tmpdir: py.path.local, capfd: Any) -> None: + + spec = api.Spec.from_dict({"pkg": "sources-test/0.1.0/src"}) + expected = "\n".join( + [ + "SPK_PKG=sources-test/0.1.0/src", + "SPK_PKG_NAME=sources-test", + "SPK_PKG_VERSION=0.1.0", + "SPK_PKG_BUILD=src", + "SPK_PKG_VERSION_MAJOR=0", + "SPK_PKG_VERSION_MINOR=1", + "SPK_PKG_VERSION_PATCH=0", + "SPK_PKG_VERSION_BASE=0.1.0", + ] + ) + script_source = api.ScriptSource.from_dict( + { + "script": [ + "echo SPK_PKG=${SPK_PKG}", + "echo SPK_PKG_NAME=${SPK_PKG_NAME}", + "echo SPK_PKG_VERSION=${SPK_PKG_VERSION}", + "echo SPK_PKG_BUILD=${SPK_PKG_BUILD}", + "echo SPK_PKG_VERSION_MAJOR=${SPK_PKG_VERSION_MAJOR}", + "echo SPK_PKG_VERSION_MINOR=${SPK_PKG_VERSION_MINOR}", + "echo SPK_PKG_VERSION_PATCH=${SPK_PKG_VERSION_PATCH}", + "echo SPK_PKG_VERSION_BASE=${SPK_PKG_VERSION_BASE}", + ] + } + ) + dest_dir = tmpdir.join("dest") + spec.sources = [script_source] + collect_sources(spec, dest_dir.strpath) + + out, _ = capfd.readouterr() + assert ( + out.strip() == expected + ), "should have access to package variables in sources script"