Files
pre-commit-hooks/pre_commit_hooks/no_commit_to_branch.py
Marc Jay a7af812449 Make optional argument use an immutable set for the default value
in no-commit-to-branch. Make other sets immutable to satisfy type-checking
and be consistent
2019-04-20 23:07:14 +01:00

48 lines
1.3 KiB
Python

from __future__ import print_function
import argparse
import re
from typing import FrozenSet
from typing import Optional
from typing import Sequence
from pre_commit_hooks.util import CalledProcessError
from pre_commit_hooks.util import cmd_output
def is_on_branch(protected, patterns=frozenset()):
# type: (FrozenSet[str], FrozenSet[str]) -> bool
try:
ref_name = cmd_output('git', 'symbolic-ref', 'HEAD')
except CalledProcessError:
return False
chunks = ref_name.strip().split('/')
branch_name = '/'.join(chunks[2:])
return branch_name in protected or any(
re.match(p, branch_name) for p in patterns
)
def main(argv=None): # type: (Optional[Sequence[str]]) -> int
parser = argparse.ArgumentParser()
parser.add_argument(
'-b', '--branch', action='append',
help='branch to disallow commits to, may be specified multiple times',
)
parser.add_argument(
'-p', '--pattern', action='append',
help=(
'regex pattern for branch name to disallow commits to, '
'may be specified multiple times'
),
)
args = parser.parse_args(argv)
protected = frozenset(args.branch or ('master',))
patterns = frozenset(args.pattern or ())
return int(is_on_branch(protected, patterns))
if __name__ == '__main__':
exit(main())