Skip to content

Commit bbc922f

Browse files
committed
Improve how we determine runtime verbosity
- 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.
1 parent 1be1871 commit bbc922f

File tree

5 files changed

+35
-26
lines changed

5 files changed

+35
-26
lines changed

src/ansiblelint/__main__.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,13 @@
5656

5757
def initialize_logger(level: int = 0) -> None:
5858
"""Set up the global logging level based on the verbosity number."""
59-
VERBOSITY_MAP = {0: logging.NOTSET, 1: logging.INFO, 2: logging.DEBUG}
59+
VERBOSITY_MAP = {
60+
-2: logging.ERROR,
61+
-1: logging.WARNING,
62+
0: logging.NOTSET,
63+
1: logging.INFO,
64+
2: logging.DEBUG,
65+
}
6066

6167
handler = logging.StreamHandler()
6268
formatter = logging.Formatter('%(levelname)-8s %(message)s')
@@ -83,7 +89,7 @@ def initialize_options(arguments: List[str]):
8389
)
8490
)
8591
if err:
86-
print(err, file=sys.stderr)
92+
_logger.error(err)
8793
sys.exit(ANSIBLE_MISSING_RC)
8894
sys.exit(0)
8995

src/ansiblelint/_prerun.py

+17-17
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
import os
23
import pathlib
34
import re
@@ -24,6 +25,8 @@
2425
)
2526
from ansiblelint.loaders import yaml_from_file
2627

28+
_logger = logging.getLogger(__name__)
29+
2730

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

8689
ver, err = _get_ver_err()
8790
if exit_on_error and err:
88-
print(err, file=sys.stderr)
91+
_logger.error(err)
8992
sys.exit(ANSIBLE_MISSING_RC)
9093
return ver, err
9194

@@ -104,7 +107,7 @@ def prepare_environment() -> None:
104107
"requirements.yml",
105108
]
106109

107-
print("Running %s" % " ".join(cmd), file=sys.stderr)
110+
_logger.info("Running %s", " ".join(cmd))
108111
run = subprocess.run(
109112
cmd,
110113
universal_newlines=True,
@@ -113,7 +116,7 @@ def prepare_environment() -> None:
113116
stderr=subprocess.STDOUT,
114117
)
115118
if run.returncode != 0:
116-
print(run.stdout, file=sys.stderr)
119+
_logger.error(run.stdout)
117120
sys.exit(run.returncode)
118121

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

132-
print("Running %s" % " ".join(cmd), file=sys.stderr)
135+
_logger.info("Running %s", " ".join(cmd))
133136
run = subprocess.run(
134137
cmd,
135138
universal_newlines=True,
@@ -138,7 +141,7 @@ def prepare_environment() -> None:
138141
stderr=subprocess.STDOUT,
139142
)
140143
if run.returncode != 0:
141-
print(run.stdout, file=sys.stderr)
144+
_logger.error(run.stdout, file=sys.stderr)
142145
sys.exit(run.returncode)
143146

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

192195

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

262262

263263
def _perform_mockings() -> None:

src/ansiblelint/cli.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -156,9 +156,9 @@ def get_cli_parser() -> argparse.ArgumentParser:
156156
parser.add_argument(
157157
'-q',
158158
dest='quiet',
159-
default=False,
160-
action='store_true',
161-
help="quieter, although not silent output",
159+
default=0,
160+
action='count',
161+
help="quieter, reduce verbosity, can be specified twice.",
162162
)
163163
parser.add_argument(
164164
'-p',
@@ -379,6 +379,9 @@ def get_config(arguments: List[str]) -> Namespace:
379379
)
380380
options.project_dir = normpath(project_dir)
381381

382+
# print(666, options.quiet, options.verbosity)
383+
# Compute final verbosity level by subtracting -q counter.
384+
options.verbosity -= options.quiet
382385
return config
383386

384387

test/TestCliRolePaths.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def test_run_role_name_with_prefix(self):
105105
cwd = self.local_test_dir
106106
role_path = 'roles/ansible-role-foo'
107107

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

120-
result = run_ansible_lint(role_path, cwd=cwd)
120+
result = run_ansible_lint("-v", role_path, cwd=cwd)
121121
assert len(result.stdout) == 0
122122
assert (
123123
"Added ANSIBLE_ROLES_PATH=~/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles:roles"

test/test_prerun.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def test_prerun_reqs_v1() -> None:
1515
os.path.dirname(os.path.realpath(__file__)), "..", "examples", "reqs_v1"
1616
)
1717
)
18-
result = run_ansible_lint(".", cwd=cwd)
18+
result = run_ansible_lint("-v", ".", cwd=cwd)
1919
assert "Running ansible-galaxy role install" in result.stderr, result.stderr
2020
assert (
2121
"Running ansible-galaxy collection install" not in result.stderr
@@ -31,7 +31,7 @@ def test_prerun_reqs_v2() -> None:
3131
os.path.dirname(os.path.realpath(__file__)), "..", "examples", "reqs_v2"
3232
)
3333
)
34-
result = run_ansible_lint(".", cwd=cwd)
34+
result = run_ansible_lint("-v", ".", cwd=cwd)
3535
assert "Running ansible-galaxy role install" in result.stderr, result.stderr
3636
assert "Running ansible-galaxy collection install" in result.stderr, result.stderr
3737
assert result.returncode == 0, result

0 commit comments

Comments
 (0)