From da81d972e94cc34bca8f41a5580f21e0994f0d99 Mon Sep 17 00:00:00 2001 From: Sorin Sbarnea Date: Thu, 18 Mar 2021 16:14:10 +0000 Subject: [PATCH] Avoid warnings when not running inside git repos Avoid confusing user with warning messages when linter is run outside git repos. This change will silently fallback to os.walk when run outside git repos. Fixes: #1410 --- src/ansiblelint/file_utils.py | 28 +++++++++++++++++++--------- test/TestUtils.py | 4 ++-- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/ansiblelint/file_utils.py b/src/ansiblelint/file_utils.py index ceaa18b88b..e5b023729f 100644 --- a/src/ansiblelint/file_utils.py +++ b/src/ansiblelint/file_utils.py @@ -212,10 +212,11 @@ def get_yaml_files(options: Namespace) -> Dict[str, Any]: git_command, stderr=subprocess.STDOUT, universal_newlines=True ).split("\x00")[:-1] except subprocess.CalledProcessError as exc: - _logger.warning( - "Failed to discover yaml files to lint using git: %s", - exc.output.rstrip('\n'), - ) + if not (exc.returncode == 128 and 'fatal: not a git repository' in exc.output): + _logger.warning( + "Failed to discover yaml files to lint using git: %s", + exc.output.rstrip('\n'), + ) except FileNotFoundError as exc: if options.verbosity: _logger.warning("Failed to locate command: %s", exc) @@ -253,10 +254,19 @@ def guess_project_dir() -> str: def expand_dirs_in_lintables(lintables: Set[Lintable]) -> None: """Return all recognized lintables within given directory.""" - all_files = get_yaml_files(options) + should_expand = False - for item in copy.copy(lintables): + for item in lintables: if item.path.is_dir(): - for filename in all_files: - if filename.startswith(str(item.path)): - lintables.add(Lintable(filename)) + should_expand = True + break + + if should_expand: + # this relies on git and we do not want to call unless needed + all_files = get_yaml_files(options) + + for item in copy.copy(lintables): + if item.path.is_dir(): + for filename in all_files: + if filename.startswith(str(item.path)): + lintables.add(Lintable(filename)) diff --git a/test/TestUtils.py b/test/TestUtils.py index 1ca3339369..38a780db96 100644 --- a/test/TestUtils.py +++ b/test/TestUtils.py @@ -213,9 +213,9 @@ def test_expand_paths_vars(test_path, expected, monkeypatch): ('reset_env_var', 'message_prefix'), ( ('PATH', "Failed to locate command: "), - ('GIT_DIR', "Failed to discover yaml files to lint using git: "), + ('GIT_DIR', "Discovering files to lint: "), ), - ids=('no Git installed', 'outside Git repository'), + ids=('no-git-cli', 'outside-git-repo'), ) def test_get_yaml_files_git_verbose(reset_env_var, message_prefix, monkeypatch, caplog): """Ensure that autodiscovery lookup failures are logged."""