Skip to content
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

Allow more control over verbosity when calling ansible-galaxy #278

Merged
merged 5 commits into from
Jan 3, 2024
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
Diff view
34 changes: 30 additions & 4 deletions src/ansible_compat/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ def __init__(
require_module: bool = False,
max_retries: int = 0,
environ: dict[str, str] | None = None,
verbosity: int = 0,
) -> None:
"""Initialize Ansible runtime environment.

Expand All @@ -186,12 +187,17 @@ def __init__(
Default is 0, no retries.
:param environ: Environment dictionary to use, if undefined
``os.environ`` will be copied and used.
:param verbosity: Verbosity level to use.
"""
self.project_dir = project_dir or Path.cwd()
self.isolated = isolated
self.max_retries = max_retries
self.environ = environ or os.environ.copy()
self.plugins = Plugins(runtime=self)
self.verbosity = verbosity

self.initialize_logger(level=self.verbosity)

# Reduce noise from paramiko, unless user already defined PYTHONWARNINGS
# paramiko/transport.py:236: CryptographyDeprecationWarning: Blowfish has been deprecated
# https://github.com/paramiko/paramiko/issues/2038
Expand Down Expand Up @@ -235,6 +241,21 @@ def warning(
# Monkey patch ansible warning in order to use warnings module.
Display.warning = warning

def initialize_logger(self, level: int = 0) -> None:
"""Set up the global logging level based on the verbosity number."""
verbosity_map = {
-2: logging.CRITICAL,
-1: logging.ERROR,
0: logging.WARNING,
1: logging.INFO,
2: logging.DEBUG,
}
# Unknown logging level is treated as DEBUG
logging_level = verbosity_map.get(level, logging.DEBUG)
_logger.setLevel(logging_level)
# Use module-level _logger instance to validate it
_logger.debug("Logging initialized to level %s", logging_level)

def _add_sys_path_to_collection_paths(self) -> None:
"""Add the sys.path to the collection paths."""
if self.config.collections_scan_sys_path:
Expand Down Expand Up @@ -505,9 +526,11 @@ def install_requirements( # noqa: C901
"ansible-galaxy",
"role",
"install",
"-vr",
"-r",
f"{requirement}",
]
if self.verbosity > 0:
cmd.extend(["-" + ("v" * self.verbosity)])
if self.cache_dir:
cmd.extend(["--roles-path", f"{self.cache_dir}/roles"])

Expand All @@ -519,8 +542,9 @@ def install_requirements( # noqa: C901
_logger.info("Running %s", " ".join(cmd))

result = self.run(cmd, retry=retry)
_logger.debug(result.stdout)
if result.returncode != 0:
_logger.error(result.stdout)
_logger.error(result.stderr)
raise AnsibleCommandError(result)

# Run galaxy collection install works on v2 requirements.yml
Expand All @@ -529,8 +553,10 @@ def install_requirements( # noqa: C901
"ansible-galaxy",
"collection",
"install",
"-v",
]
if self.verbosity > 0:
cmd.extend(["-" + ("v" * self.verbosity)])

for collection in reqs_yaml["collections"]:
if isinstance(collection, dict) and collection.get("type", "") == "git":
_logger.info(
Expand Down Expand Up @@ -558,8 +584,8 @@ def install_requirements( # noqa: C901
retry=retry,
env={**os.environ, "ANSIBLE_COLLECTIONS_PATH": ":".join(cpaths)},
)
_logger.debug(result.stdout)
if result.returncode != 0:
_logger.error(result.stdout)
_logger.error(result.stderr)
raise AnsibleCommandError(result)

Expand Down
14 changes: 7 additions & 7 deletions test/test_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,10 +240,11 @@ def cwd(path: Path) -> Iterator[None]:
os.chdir(old_pwd)


def test_prerun_reqs_v1(caplog: pytest.LogCaptureFixture, runtime: Runtime) -> None:
def test_prerun_reqs_v1(caplog: pytest.LogCaptureFixture) -> None:
"""Checks that the linter can auto-install requirements v1 when found."""
runtime = Runtime(verbosity=1)
path = Path(__file__).parent.parent / "examples" / "reqs_v1"
with cwd(path), caplog.at_level(logging.INFO):
with cwd(path):
runtime.prepare_environment()
assert any(
msg.startswith("Running ansible-galaxy role install") for msg in caplog.messages
Expand All @@ -254,12 +255,12 @@ def test_prerun_reqs_v1(caplog: pytest.LogCaptureFixture, runtime: Runtime) -> N
)


def test_prerun_reqs_v2(caplog: pytest.LogCaptureFixture, runtime: Runtime) -> None:
def test_prerun_reqs_v2(caplog: pytest.LogCaptureFixture) -> None:
"""Checks that the linter can auto-install requirements v2 when found."""
runtime = Runtime(verbosity=1)
path = (Path(__file__).parent.parent / "examples" / "reqs_v2").resolve()
with cwd(path):
with caplog.at_level(logging.INFO):
runtime.prepare_environment()
runtime.prepare_environment()
assert any(
msg.startswith("Running ansible-galaxy role install")
for msg in caplog.messages
Expand Down Expand Up @@ -526,11 +527,10 @@ def test_install_galaxy_role(runtime_tmp: Runtime) -> None:


def test_install_galaxy_role_unlink(
runtime_tmp: Runtime,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test ability to unlink incorrect symlinked roles."""
caplog.set_level(logging.INFO)
runtime_tmp = Runtime(verbosity=1)
runtime_tmp.prepare_environment()
pathlib.Path(f"{runtime_tmp.cache_dir}/roles").mkdir(parents=True, exist_ok=True)
pathlib.Path(f"{runtime_tmp.cache_dir}/roles/acme.get_rich").symlink_to("/dev/null")
Expand Down