From 0760bec3ffe1cbabdbead1909aac38aae14c7732 Mon Sep 17 00:00:00 2001 From: Anthony Sottile Date: Mon, 18 Nov 2019 14:57:41 -0800 Subject: [PATCH] Show better error message when running inside `.git` --- pre_commit/main.py | 10 +++++++++- tests/main_test.py | 5 +++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/pre_commit/main.py b/pre_commit/main.py index 59de5f24..772c69cb 100644 --- a/pre_commit/main.py +++ b/pre_commit/main.py @@ -122,12 +122,20 @@ def _adjust_args_and_chdir(args): args.repo = os.path.abspath(args.repo) try: - os.chdir(git.get_root()) + toplevel = git.get_root() except CalledProcessError: raise FatalError( 'git failed. Is it installed, and are you in a Git repository ' 'directory?', ) + else: + if toplevel == '': + raise FatalError( + 'git toplevel unexpectedly empty! make sure you are not ' + 'inside the `.git` directory of your repository.', + ) + else: + os.chdir(toplevel) args.config = os.path.relpath(args.config) if args.command in {'run', 'try-repo'}: diff --git a/tests/main_test.py b/tests/main_test.py index 364e0d39..b59d35ef 100644 --- a/tests/main_test.py +++ b/tests/main_test.py @@ -39,6 +39,11 @@ def test_adjust_args_and_chdir_not_in_git_dir(in_tmpdir): main._adjust_args_and_chdir(Args()) +def test_adjust_args_and_chdir_in_dot_git_dir(in_git_dir): + with in_git_dir.join('.git').as_cwd(), pytest.raises(FatalError): + main._adjust_args_and_chdir(Args()) + + def test_adjust_args_and_chdir_noop(in_git_dir): args = Args(command='run', files=['f1', 'f2']) main._adjust_args_and_chdir(args)