Skip to content

Commit

Permalink
Improve how we determine runtime verbosity
Browse files Browse the repository at this point in the history
- Assure `-q` reduced computed verbosity
- Use logger instead of print in pre-run phase
- `-q` and `-v` cancel each other, which is a natural expectation

Default verbosity of 0 matches the logging.NOSET level but adding -q
or -qq can reduce logging to WARN or ERROR levels only.

The only visible behavior change is that now the pre-run messages are
no longer displayed unless verbosity is >=1, which most people use
anyway. Previously adding `-q` did not had any effect in reducing
logging verbosity.
  • Loading branch information
ssbarnea committed Mar 11, 2021
1 parent 1be1871 commit bbc922f
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 26 deletions.
10 changes: 8 additions & 2 deletions src/ansiblelint/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,13 @@

def initialize_logger(level: int = 0) -> None:
"""Set up the global logging level based on the verbosity number."""
VERBOSITY_MAP = {0: logging.NOTSET, 1: logging.INFO, 2: logging.DEBUG}
VERBOSITY_MAP = {
-2: logging.ERROR,
-1: logging.WARNING,
0: logging.NOTSET,
1: logging.INFO,
2: logging.DEBUG,
}

handler = logging.StreamHandler()
formatter = logging.Formatter('%(levelname)-8s %(message)s')
Expand All @@ -83,7 +89,7 @@ def initialize_options(arguments: List[str]):
)
)
if err:
print(err, file=sys.stderr)
_logger.error(err)
sys.exit(ANSIBLE_MISSING_RC)
sys.exit(0)

Expand Down
34 changes: 17 additions & 17 deletions src/ansiblelint/_prerun.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import os
import pathlib
import re
Expand All @@ -24,6 +25,8 @@
)
from ansiblelint.loaders import yaml_from_file

_logger = logging.getLogger(__name__)


def check_ansible_presence(exit_on_error: bool = False) -> Tuple[str, str]:
"""Assures we stop execution if Ansible is missing or outdated.
Expand Down Expand Up @@ -85,7 +88,7 @@ def _get_ver_err() -> Tuple[str, str]:

ver, err = _get_ver_err()
if exit_on_error and err:
print(err, file=sys.stderr)
_logger.error(err)
sys.exit(ANSIBLE_MISSING_RC)
return ver, err

Expand All @@ -104,7 +107,7 @@ def prepare_environment() -> None:
"requirements.yml",
]

print("Running %s" % " ".join(cmd), file=sys.stderr)
_logger.info("Running %s", " ".join(cmd))
run = subprocess.run(
cmd,
universal_newlines=True,
Expand All @@ -113,7 +116,7 @@ def prepare_environment() -> None:
stderr=subprocess.STDOUT,
)
if run.returncode != 0:
print(run.stdout, file=sys.stderr)
_logger.error(run.stdout)
sys.exit(run.returncode)

# Run galaxy collection install works on v2 requirements.yml
Expand All @@ -129,7 +132,7 @@ def prepare_environment() -> None:
"requirements.yml",
]

print("Running %s" % " ".join(cmd), file=sys.stderr)
_logger.info("Running %s", " ".join(cmd))
run = subprocess.run(
cmd,
universal_newlines=True,
Expand All @@ -138,7 +141,7 @@ def prepare_environment() -> None:
stderr=subprocess.STDOUT,
)
if run.returncode != 0:
print(run.stdout, file=sys.stderr)
_logger.error(run.stdout, file=sys.stderr)
sys.exit(run.returncode)

_install_galaxy_role()
Expand All @@ -162,9 +165,9 @@ def _install_galaxy_role() -> None:
role_name = re.sub(r'^{0}'.format(re.escape('ansible-role-')), '', role_name)
fqrn = f"{role_namespace}.{role_name}"
if not re.match(r"[a-z0-9][a-z0-9_]+\.[a-z][a-z0-9_]+$", fqrn):
print(
f"""\
Computed fully qualified role name of {fqrn} is not valid.
_logger.error(
"""\
Computed fully qualified role name of %s is not valid.
Please edit meta/main.yml and assure we can correctly determine full role name:
galaxy_info:
Expand All @@ -174,7 +177,7 @@ def _install_galaxy_role() -> None:
Namespace: https://galaxy.ansible.com/docs/contributing/namespaces.html#galaxy-namespace-limitations
Role: https://galaxy.ansible.com/docs/contributing/creating_role.html#role-names
""",
file=sys.stderr,
fqrn,
)
sys.exit(INVALID_PREREQUISITES_RC)
p = pathlib.Path(f"{options.project_dir}/.cache/roles")
Expand All @@ -184,9 +187,9 @@ def _install_galaxy_role() -> None:
# it appears that is_dir() reports true instead, so we rely on exits().
if not link_path.exists():
link_path.symlink_to(pathlib.Path("../..", target_is_directory=True))
print(
f"Using {link_path} symlink to current repository in order to enable Ansible to find the role using its expected full name.",
file=sys.stderr,
_logger.info(
"Using %s symlink to current repository in order to enable Ansible to find the role using its expected full name.",
link_path,
)


Expand Down Expand Up @@ -223,10 +226,7 @@ def _make_module_stub(module_name: str) -> None:
collection=collection,
)
elif "." in module_name:
print(
"Config error: %s is not a valid module name." % module_name,
file=sys.stderr,
)
_logger.error("Config error: %s is not a valid module name.", module_name)
sys.exit(INVALID_CONFIG_RC)
else:
os.makedirs(f"{options.project_dir}/.cache/modules", exist_ok=True)
Expand Down Expand Up @@ -257,7 +257,7 @@ def _update_env(varname: str, value: List[str], default: str = "") -> None:
value_str = ":".join(value)
if value_str != os.environ.get(varname, ""):
os.environ[varname] = value_str
print("Added %s=%s" % (varname, value_str), file=sys.stderr)
_logger.info("Added %s=%s", varname, value_str)


def _perform_mockings() -> None:
Expand Down
9 changes: 6 additions & 3 deletions src/ansiblelint/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,9 @@ def get_cli_parser() -> argparse.ArgumentParser:
parser.add_argument(
'-q',
dest='quiet',
default=False,
action='store_true',
help="quieter, although not silent output",
default=0,
action='count',
help="quieter, reduce verbosity, can be specified twice.",
)
parser.add_argument(
'-p',
Expand Down Expand Up @@ -379,6 +379,9 @@ def get_config(arguments: List[str]) -> Namespace:
)
options.project_dir = normpath(project_dir)

# print(666, options.quiet, options.verbosity)
# Compute final verbosity level by subtracting -q counter.
options.verbosity -= options.quiet
return config


Expand Down
4 changes: 2 additions & 2 deletions test/TestCliRolePaths.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def test_run_role_name_with_prefix(self):
cwd = self.local_test_dir
role_path = 'roles/ansible-role-foo'

result = run_ansible_lint(role_path, cwd=cwd)
result = run_ansible_lint("-v", role_path, cwd=cwd)
assert len(result.stdout) == 0
assert (
"Added ANSIBLE_ROLES_PATH=~/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles:roles"
Expand All @@ -117,7 +117,7 @@ def test_run_role_name_from_meta(self):
cwd = self.local_test_dir
role_path = 'roles/valid-due-to-meta'

result = run_ansible_lint(role_path, cwd=cwd)
result = run_ansible_lint("-v", role_path, cwd=cwd)
assert len(result.stdout) == 0
assert (
"Added ANSIBLE_ROLES_PATH=~/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles:roles"
Expand Down
4 changes: 2 additions & 2 deletions test/test_prerun.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def test_prerun_reqs_v1() -> None:
os.path.dirname(os.path.realpath(__file__)), "..", "examples", "reqs_v1"
)
)
result = run_ansible_lint(".", cwd=cwd)
result = run_ansible_lint("-v", ".", cwd=cwd)
assert "Running ansible-galaxy role install" in result.stderr, result.stderr
assert (
"Running ansible-galaxy collection install" not in result.stderr
Expand All @@ -31,7 +31,7 @@ def test_prerun_reqs_v2() -> None:
os.path.dirname(os.path.realpath(__file__)), "..", "examples", "reqs_v2"
)
)
result = run_ansible_lint(".", cwd=cwd)
result = run_ansible_lint("-v", ".", cwd=cwd)
assert "Running ansible-galaxy role install" in result.stderr, result.stderr
assert "Running ansible-galaxy collection install" in result.stderr, result.stderr
assert result.returncode == 0, result

0 comments on commit bbc922f

Please sign in to comment.