Skip to content

Commit

Permalink
fix: guess project root dir with git, config file and cwd (#1661)
Browse files Browse the repository at this point in the history
  • Loading branch information
xabinapal committed Jul 13, 2021
1 parent 4f1bb49 commit 97d74ee
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 21 deletions.
6 changes: 1 addition & 5 deletions src/ansiblelint/cli.py
Expand Up @@ -382,11 +382,7 @@ def get_config(arguments: List[str]) -> Namespace:
options.rulesdirs = get_rules_dirs(options.rulesdir, options.use_default_rules)

if options.project_dir == ".":
project_dir = os.path.dirname(
os.path.abspath(
options.config_file or f"{guess_project_dir()}/.ansible-lint"
)
)
project_dir = guess_project_dir(options.config_file)
options.project_dir = normpath(project_dir)
if not options.project_dir or not os.path.exists(options.project_dir):
raise RuntimeError(
Expand Down
54 changes: 38 additions & 16 deletions src/ansiblelint/file_utils.py
Expand Up @@ -2,6 +2,7 @@
import copy
import logging
import os
import pathlib
import subprocess
import sys
from argparse import Namespace
Expand Down Expand Up @@ -251,24 +252,45 @@ def discover_lintables(options: Namespace) -> Dict[str, Any]:
return OrderedDict.fromkeys(sorted(out))


def guess_project_dir() -> str:
"""Return detected project dir or user home directory."""
try:
result = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True,
check=False,
)
except FileNotFoundError:
# if git is absent we use home directory
return str(Path.home())
def guess_project_dir(config_file: str) -> str:
"""Return detected project dir or current working directory."""
path = None
if config_file is not None:
target = pathlib.Path(config_file)
if target.exists():
path = str(target.parent.absolute())

if path is None:
try:
result = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True,
check=False,
)

if result.returncode != 0:
return str(Path.home())
path = result.stdout.splitlines()[0]
except subprocess.CalledProcessError as exc:
if not (
exc.returncode == 128 and 'fatal: not a git repository' in exc.output
):
_logger.warning(
"Failed to guess project directory using git: %s",
exc.output.rstrip('\n'),
)
except FileNotFoundError as exc:
_logger.warning("Failed to locate command: %s", exc)

if path is None:
path = os.getcwd()

return result.stdout.splitlines()[0]
_logger.info(
"Guessed %s as project root directory",
path,
)

return path


def expand_dirs_in_lintables(lintables: Set[Lintable]) -> None:
Expand Down

0 comments on commit 97d74ee

Please sign in to comment.