summaryrefslogtreecommitdiffstats
path: root/pre_commit_hooks/no_commit_to_branch.py
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2022-01-30 11:02:58 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2022-01-30 11:02:58 +0000
commit307d578d739eb254ef3000fdde94271af9b8923e (patch)
treecf256ef8bea7b1cad51d3a662dd4d6885156e98b /pre_commit_hooks/no_commit_to_branch.py
parentInitial commit. (diff)
downloadpre-commit-hooks-307d578d739eb254ef3000fdde94271af9b8923e.tar.xz
pre-commit-hooks-307d578d739eb254ef3000fdde94271af9b8923e.zip
Adding upstream version 4.1.0.upstream/4.1.0
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'pre_commit_hooks/no_commit_to_branch.py')
-rw-r--r--pre_commit_hooks/no_commit_to_branch.py47
1 files changed, 47 insertions, 0 deletions
diff --git a/pre_commit_hooks/no_commit_to_branch.py b/pre_commit_hooks/no_commit_to_branch.py
new file mode 100644
index 0000000..db84850
--- /dev/null
+++ b/pre_commit_hooks/no_commit_to_branch.py
@@ -0,0 +1,47 @@
+import argparse
+import re
+from typing import AbstractSet
+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: AbstractSet[str],
+ patterns: AbstractSet[str] = frozenset(),
+) -> 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: Optional[Sequence[str]] = None) -> 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', 'main'))
+ patterns = frozenset(args.pattern or ())
+ return int(is_on_branch(protected, patterns))
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())