Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: guess project root dir with git, config file and cwd #1661

Merged
merged 1 commit into from Jul 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's best not to put more than one command inside and try-block

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