Skip to content

Commit

Permalink
Improve file detection outside git repositories (#1557)
Browse files Browse the repository at this point in the history
Address bug related to detection of lintable files when run outside
a git repository.

- extend list of exclusions with few common directiories
- allow linter to identify any file type, not only those with
  yaml/yml extension (matches behavior of git ls-files variant)
- improve logging messages

Closes: #1549
  • Loading branch information
ssbarnea committed May 19, 2021
1 parent 947f415 commit b27c0a2
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 23 deletions.
2 changes: 1 addition & 1 deletion src/ansiblelint/cli.py
Expand Up @@ -314,7 +314,7 @@ def merge_config(file_config: Dict[Any, Any], cli_config: Namespace) -> Namespac
)
# maps lists to their default config values
lists_map = {
'exclude_paths': [".cache"],
'exclude_paths': [".cache", ".git", ".hg", ".svn", ".tox"],
'rulesdir': [],
'skip_list': [],
'tags': [],
Expand Down
17 changes: 6 additions & 11 deletions src/ansiblelint/file_utils.py
Expand Up @@ -11,7 +11,9 @@
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Set, Union

# import wcmatch
import wcmatch.pathlib
from wcmatch.wcmatch import RECURSIVE, WcMatch

from ansiblelint.config import BASE_KINDS, options
from ansiblelint.constants import FileType
Expand Down Expand Up @@ -205,14 +207,13 @@ def discover_lintables(options: Namespace) -> Dict[str, Any]:
"""Find all files that we know how to lint."""
# git is preferred as it also considers .gitignore
git_command = ['git', 'ls-files', '-z']
_logger.info("Discovering files to lint: %s", ' '.join(git_command))

out = None

try:
out = subprocess.check_output(
git_command, stderr=subprocess.STDOUT, universal_newlines=True
).split("\x00")[:-1]
_logger.info("Discovered files to lint using: %s", ' '.join(git_command))
except subprocess.CalledProcessError as exc:
if not (exc.returncode == 128 and 'fatal: not a git repository' in exc.output):
_logger.warning(
Expand All @@ -224,15 +225,9 @@ def discover_lintables(options: Namespace) -> Dict[str, Any]:
_logger.warning("Failed to locate command: %s", exc)

if out is None:
# TODO(ssbarnea): avoid returning only yaml/yml files but be careful
# to avoid accidental return of too many files, especiall as some
# directories like .cache, .tox may bring undesireble noise.
out = [
os.path.join(root, name)
for root, dirs, files in os.walk('.')
for name in files
if name.endswith('.yaml') or name.endswith('.yml')
]
exclude_pattern = "|".join(options.exclude_paths)
_logger.info("Looking up for files, excluding %s ...", exclude_pattern)
out = WcMatch('.', exclude_pattern=exclude_pattern, flags=RECURSIVE).match()

return OrderedDict.fromkeys(sorted(out))

Expand Down
18 changes: 7 additions & 11 deletions test/TestUtils.py
Expand Up @@ -212,27 +212,23 @@ def test_expand_paths_vars(test_path, expected, monkeypatch):
@pytest.mark.parametrize(
('reset_env_var', 'message_prefix'),
(
# simulate absence of git command
('PATH', "Failed to locate command: "),
('GIT_DIR', "Discovering files to lint: "),
# simulate a missing git repo
('GIT_DIR', "Looking up for files"),
),
ids=('no-git-cli', 'outside-git-repo'),
)
def test_discover_lintables_git_verbose(
reset_env_var, message_prefix, monkeypatch, caplog
):
reset_env_var: str, message_prefix: str, monkeypatch, caplog
) -> None:
"""Ensure that autodiscovery lookup failures are logged."""
options = cli.get_config(['-v'])
initialize_logger(options.verbosity)
monkeypatch.setenv(reset_env_var, '')
file_utils.discover_lintables(options)

expected_info = (
"ansiblelint",
logging.INFO,
'Discovering files to lint: git ls-files -z',
)

assert expected_info in caplog.record_tuples
assert any(m[2].startswith("Looking up for files") for m in caplog.record_tuples)
assert any(m.startswith(message_prefix) for m in caplog.messages)


Expand Down Expand Up @@ -314,7 +310,7 @@ def test_cli_auto_detect(capfd):
out, err = capfd.readouterr()

# Confirmation that it runs in auto-detect mode
assert "Discovering files to lint: git ls-files -z" in err
assert "Discovered files to lint using: git ls-files -z" in err
# An expected rule match from our examples
assert (
"examples/playbooks/empty_playbook.yml:1: "
Expand Down

0 comments on commit b27c0a2

Please sign in to comment.