8000 Avoid direct use of os.environ by ssbarnea · Pull Request #71 · ansible/ansible-compat · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Avoid direct use of os.environ #71

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

Merged
merged 1 commit into from
Sep 5, 2021
Merged
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
8000
Diff view
43 changes: 23 additions & 20 deletions src/ansible_compat/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def __init__(
min_required_version: Optional[str] = None,
require_module: bool = False,
max_retries: int = 0,
environ: Optional[Dict[str, str]] = None,
) -> None:
"""Initialize Ansible runtime environment.

Expand All @@ -70,10 +71,13 @@ def __init__(
also perform Python imports from Ansible.
:param max_retries: Number of times it should retry network operations.
Default is 0, no retries.
:param environ: Environment dictionary to use, if undefined
``os.environ`` will be copied and used.
"""
self.project_dir = project_dir or os.getcwd()
self.isolated = isolated
self.max_retries = max_retries
self.environ = environ or os.environ.copy()
if isolated:
self.cache_dir = get_cache_dir(self.project_dir)
self.config = AnsibleConfig()
Expand Down Expand Up @@ -125,6 +129,7 @@ def exec(
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=self.environ,
)
if result.returncode == 0:
break
Expand Down Expand Up @@ -391,11 +396,11 @@ def _prepare_ansible_paths(self) -> None:
path_list.insert(0, path)

if library_paths != self.config.DEFAULT_MODULE_PATH:
_update_env('ANSIBLE_LIBRARY', library_paths)
self._update_env('ANSIBLE_LIBRARY', library_paths)
if collections_path != self.config.collections_paths:
_update_env(ansible_collections_path(), collections_path)
self._update_env(ansible_collections_path(), collections_path)
if roles_path != self.config.default_roles_path:
_update_env('ANSIBLE_ROLES_PATH', roles_path)
self._update_env('ANSIBLE_ROLES_PATH', roles_path)

def _install_galaxy_role(
self, project_dir: str, role_name_check: int = 0, ignore_errors: bool = False
Expand Down Expand Up @@ -461,6 +466,21 @@ def _install_galaxy_role(
link_path,
)

def _update_env(self, varname: str, value: List[str], default: str = "") -> None:
"""Update colon based environment variable if needed.

New values are prepended to make sure they take precedence.
"""
if not value:
return
orig_value = self.environ.get(varname, default)
if orig_value:
value = [*value, *orig_value.split(':')]
value_str = ":".join(value)
if value_str != self.environ.get(varname, ""):
self.environ[varname] = value_str
_logger.info("Set %s=%s", varname, value_str)


def _get_role_fqrn(galaxy_infos: Dict[str, Any], project_dir: str) -> str:
"""Compute role fqrn."""
Expand All @@ -476,23 +496,6 @@ def _get_role_fqrn(galaxy_infos: Dict[str, Any], project_dir: str) -> str:
return f"{role_namespace}{role_name}"


def _update_env(varname: str, value: List[str], default: str = "") -> None:
"""Update colon based environment variable if needed.

New values are added by inserting them to assure they take precedence
over the existing ones.
"""
if value:
orig_value = os.environ.get(varname, default=default)
if orig_value:
# Prepend original or default variable content to custom content.
value = [*value, *orig_value.split(':')]
value_str = ":".join(value)
if value_str != os.environ.get(varname, ""):
os.environ[varname] = value_str
_logger.info("Added %s=%s", varname, value_str)


def _get_galaxy_role_ns(galaxy_infos: Dict[str, Any]) -> str:
"""Compute role namespace from meta/main.yml, including trailing dot."""
role_namespace = galaxy_infos.get('namespace', "")
Expand Down
37 changes: 22 additions & 15 deletions test/test_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
AnsibleCompatError,
InvalidPrerequisiteError,
)
from ansible_compat.runtime import CompletedProcess, Runtime, _update_env
from ansible_compat.runtime import CompletedProcess, Runtime


def test_runtime_version(runtime: Runtime) -> None:
Expand Down Expand Up @@ -256,27 +256,30 @@ def test__update_env_no_old_value_no_default_no_value(monkeypatch: MonkeyPatch)
"""Make sure empty value does not touch environment."""
monkeypatch.delenv("DUMMY_VAR", raising=False)

_update_env("DUMMY_VAR", [])
runtime = Runtime()
runtime._update_env("DUMMY_VAR", [])

assert "DUMMY_VAR" not in os.environ
assert "DUMMY_VAR" not in runtime.environ


def test__update_env_no_old_value_no_value(monkeypatch: MonkeyPatch) -> None:
"""Make sure empty value does not touch environment."""
monkeypatch.delenv("DUMMY_VAR", raising=False)

_update_env("DUMMY_VAR", [], "a:b")
runtime = Runtime()
runtime._update_env("DUMMY_VAR", [], "a:b")

assert "DUMMY_VAR" not in os.environ
assert "DUMMY_VAR" not in runtime.environ


def test__update_env_no_default_no_value(monkeypatch: MonkeyPatch) -> None:
"""Make sure empty value does not touch environment."""
monkeypatch.setenv("DUMMY_VAR", "a:b")

_update_env("DUMMY_VAR", [])
runtime = Runtime()
runtime._update_env("DUMMY_VAR", [])

assert os.environ["DUMMY_VAR"] == "a:b"
assert runtime.environ["DUMMY_VAR"] == "a:b"


@pytest.mark.parametrize(
Expand All @@ -293,9 +296,10 @@ def test__update_env_no_old_value_no_default(
"""Values are concatenated using : as the separator."""
monkeypatch.delenv("DUMMY_VAR", raising=False)

_update_env("DUMMY_VAR", value)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", value)

assert os.environ["DUMMY_VAR"] == result
assert runtime.environ["DUMMY_VAR"] == result


@pytest.mark.parametrize(
Expand All @@ -311,9 +315,10 @@ def test__update_env_no_old_value(
"""Values are appended to default value."""
monkeypatch.delenv("DUMMY_VAR", raising=False)

_update_env("DUMMY_VAR", value, default)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", value, default)

assert os.environ["DUMMY_VAR"] == result
assert runtime.environ["DUMMY_VAR"] == result


@pytest.mark.parametrize(
Expand All @@ -329,9 +334,10 @@ def test__update_env_no_default(
"""Values are appended to preexisting value."""
monkeypatch.setenv("DUMMY_VAR", old_value)

_update_env("DUMMY_VAR", value)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", value)

assert os.environ["DUMMY_VAR"] == result
assert runtime.environ["DUMMY_VAR"] == result


@pytest.mark.parametrize(
Expand All @@ -353,9 +359,10 @@ def test__update_env(
"""Defaults are ignored when preexisting value is present."""
monkeypatch.setenv("DUMMY_VAR", old_value)

_update_env("DUMMY_VAR", value)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", value)

assert os.environ["DUMMY_VAR"] == result
assert runtime.environ["DUMMY_VAR"] == result


def test_require_collection_wrong_version(runtime: Runtime) -> None:
Expand Down
0