Skip to content

Commit 0760bec

Browse files
committed
Show better error message when running inside .git
1 parent 0fd4a2e commit 0760bec

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

pre_commit/main.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,12 +122,20 @@ def _adjust_args_and_chdir(args):
122122
args.repo = os.path.abspath(args.repo)
123123

124124
try:
125-
os.chdir(git.get_root())
125+
toplevel = git.get_root()
126126
except CalledProcessError:
127127
raise FatalError(
128128
'git failed. Is it installed, and are you in a Git repository '
129129
'directory?',
130130
)
131+
else:
132+
if toplevel == '':
133+
raise FatalError(
134+
'git toplevel unexpectedly empty! make sure you are not '
135+
'inside the `.git` directory of your repository.',
136+
)
137+
else:
138+
os.chdir(toplevel)
131139

132140
args.config = os.path.relpath(args.config)
133141
if args.command in {'run', 'try-repo'}:

tests/main_test.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@ def test_adjust_args_and_chdir_not_in_git_dir(in_tmpdir):
3939
main._adjust_args_and_chdir(Args())
4040

4141

42+
def test_adjust_args_and_chdir_in_dot_git_dir(in_git_dir):
43+
with in_git_dir.join('.git').as_cwd(), pytest.raises(FatalError):
44+
main._adjust_args_and_chdir(Args())
45+
46+
4247
def test_adjust_args_and_chdir_noop(in_git_dir):
4348
args = Args(command='run', files=['f1', 'f2'])
4449
main._adjust_args_and_chdir(args)

0 commit comments

Comments
 (0)