Skip to content

Commit 9383354

Browse files
authored
Merge pull request #266 from pre-commit/fix_no_commit_to_branch
Fix no-commit-to-branch when not on a branch
2 parents 2f1e5e2 + 93f319c commit 9383354

File tree

2 files changed

+20
-13
lines changed

2 files changed

+20
-13
lines changed
Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,30 @@
11
from __future__ import print_function
22

33
import argparse
4-
import sys
54

5+
from pre_commit_hooks.util import CalledProcessError
66
from pre_commit_hooks.util import cmd_output
77

88

99
def is_on_branch(protected):
10-
branch = cmd_output('git', 'symbolic-ref', 'HEAD')
10+
try:
11+
branch = cmd_output('git', 'symbolic-ref', 'HEAD')
12+
except CalledProcessError:
13+
return False
1114
chunks = branch.strip().split('/')
1215
return '/'.join(chunks[2:]) == protected
1316

1417

15-
def main(argv=[]):
18+
def main(argv=None):
1619
parser = argparse.ArgumentParser()
1720
parser.add_argument(
18-
'-b', '--branch', default='master', help='branch to disallow commits to',
21+
'-b', '--branch', default='master',
22+
help='branch to disallow commits to',
1923
)
2024
args = parser.parse_args(argv)
2125

2226
return int(is_on_branch(args.branch))
2327

2428

2529
if __name__ == '__main__':
26-
sys.exit(main(sys.argv))
30+
exit(main())

tests/check_no_commit_to_branch_test.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,19 +29,22 @@ def test_master_branch(temp_git_dir):
2929
assert is_on_branch('master') is True
3030

3131

32-
def test_main_b_call(temp_git_dir):
33-
with temp_git_dir.as_cwd():
34-
cmd_output('git', 'checkout', '-b', 'other')
35-
assert main(['-b', 'other']) == 1
36-
37-
3832
def test_main_branch_call(temp_git_dir):
3933
with temp_git_dir.as_cwd():
4034
cmd_output('git', 'checkout', '-b', 'other')
41-
assert main(['--branch', 'other']) == 1
35+
assert main(('--branch', 'other')) == 1
4236

4337

4438
def test_main_default_call(temp_git_dir):
4539
with temp_git_dir.as_cwd():
4640
cmd_output('git', 'checkout', '-b', 'anotherbranch')
47-
assert main() == 0
41+
assert main(()) == 0
42+
43+
44+
def test_not_on_a_branch(temp_git_dir):
45+
with temp_git_dir.as_cwd():
46+
cmd_output('git', 'commit', '--no-gpg-sign', '--allow-empty', '-m1')
47+
head = cmd_output('git', 'rev-parse', 'HEAD').strip()
48+
cmd_output('git', 'checkout', head)
49+
# we're not on a branch!
50+
assert main(()) == 0

0 commit comments

Comments
 (0)