11from __future__ import print_function
22
33import argparse
4+ import re
5+ from typing import AbstractSet
46from typing import Optional
57from typing import Sequence
6- from typing import Set
78
89from pre_commit_hooks .util import CalledProcessError
910from pre_commit_hooks .util import cmd_output
1011
1112
12- def is_on_branch (protected ): # type: (Set[str]) -> bool
13+ def is_on_branch (protected , patterns = frozenset ()):
14+ # type: (AbstractSet[str], AbstractSet[str]) -> bool
1315 try :
14- branch = cmd_output ('git' , 'symbolic-ref' , 'HEAD' )
16+ ref_name = cmd_output ('git' , 'symbolic-ref' , 'HEAD' )
1517 except CalledProcessError :
1618 return False
17- chunks = branch .strip ().split ('/' )
18- return '/' .join (chunks [2 :]) in protected
19+ chunks = ref_name .strip ().split ('/' )
20+ branch_name = '/' .join (chunks [2 :])
21+ return branch_name in protected or any (
22+ re .match (p , branch_name ) for p in patterns
23+ )
1924
2025
2126def main (argv = None ): # type: (Optional[Sequence[str]]) -> int
@@ -24,10 +29,18 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
2429 '-b' , '--branch' , action = 'append' ,
2530 help = 'branch to disallow commits to, may be specified multiple times' ,
2631 )
32+ parser .add_argument (
33+ '-p' , '--pattern' , action = 'append' ,
34+ help = (
35+ 'regex pattern for branch name to disallow commits to, '
36+ 'may be specified multiple times'
37+ ),
38+ )
2739 args = parser .parse_args (argv )
2840
29- protected = set (args .branch or ('master' ,))
30- return int (is_on_branch (protected ))
41+ protected = frozenset (args .branch or ('master' ,))
42+ patterns = frozenset (args .pattern or ())
43+ return int (is_on_branch (protected , patterns ))
3144
3245
3346if __name__ == '__main__' :
0 commit comments