pre-commit-hooks/pre_commit_hooks/no_commit_to_branch.py

49 lines
1.3 KiB
Python
Raw Permalink Normal View History

from __future__ import annotations
import argparse
import re
from collections.abc import Sequence
2019-04-21 07:21:58 +08:00
from typing import AbstractSet
from pre_commit_hooks.util import CalledProcessError
from pre_commit_hooks.util import cmd_output
2020-02-06 03:10:42 +08:00
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: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
'-b', '--branch', action='append',
help='branch to disallow commits to, may be specified multiple times',
2017-07-16 03:56:51 +08:00
)
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())