mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2025-08-15 10:41:58 +08:00
Amend approach for no-commit-to-branch to use regex matching based on
feedback. Adds --pattern optional argument which can be used alongside --branch to block commits to a branch which matches a supplied regex expression
This commit is contained in:
@ -1,7 +1,7 @@
|
||||
from __future__ import print_function
|
||||
|
||||
import argparse
|
||||
import fnmatch
|
||||
import re
|
||||
from typing import Optional
|
||||
from typing import Sequence
|
||||
from typing import Set
|
||||
@ -10,14 +10,17 @@ from pre_commit_hooks.util import CalledProcessError
|
||||
from pre_commit_hooks.util import cmd_output
|
||||
|
||||
|
||||
def is_on_branch(protected): # type: (Set[str]) -> bool
|
||||
def is_on_branch(protected, patterns=set()):
|
||||
# type: (Set[str], Set[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 any(fnmatch.fnmatch(branch_name, s) for s in protected)
|
||||
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
|
||||
@ -26,10 +29,18 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
|
||||
'-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 = set(args.branch or ('master',))
|
||||
return int(is_on_branch(protected))
|
||||
patterns = set(args.pattern or ())
|
||||
return int(is_on_branch(protected, patterns))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
Reference in New Issue
Block a user