2022-01-16 08:24:05 +08:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2017-03-21 01:36:51 +08:00
|
|
|
import argparse
|
2019-04-20 20:46:49 +08:00
|
|
|
import re
|
2024-10-12 07:30:07 +08:00
|
|
|
from collections.abc import Sequence
|
2019-04-21 07:21:58 +08:00
|
|
|
from typing import AbstractSet
|
2017-03-21 01:36:51 +08:00
|
|
|
|
2018-02-20 04:56:14 +08:00
|
|
|
from pre_commit_hooks.util import CalledProcessError
|
2017-03-21 01:36:51 +08:00
|
|
|
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:
|
2018-02-20 04:56:14 +08:00
|
|
|
try:
|
2019-04-10 06:53:39 +08:00
|
|
|
ref_name = cmd_output('git', 'symbolic-ref', 'HEAD')
|
2018-02-20 04:56:14 +08:00
|
|
|
except CalledProcessError:
|
|
|
|
return False
|
2019-04-10 06:53:39 +08:00
|
|
|
chunks = ref_name.strip().split('/')
|
|
|
|
branch_name = '/'.join(chunks[2:])
|
2019-04-20 20:46:49 +08:00
|
|
|
return branch_name in protected or any(
|
|
|
|
re.match(p, branch_name) for p in patterns
|
|
|
|
)
|
2017-03-21 01:36:51 +08:00
|
|
|
|
|
|
|
|
2022-01-16 08:24:05 +08:00
|
|
|
def main(argv: Sequence[str] | None = None) -> int:
|
2017-03-21 01:36:51 +08:00
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument(
|
2018-06-10 02:16:14 +08:00
|
|
|
'-b', '--branch', action='append',
|
|
|
|
help='branch to disallow commits to, may be specified multiple times',
|
2017-07-16 03:56:51 +08:00
|
|
|
)
|
2019-04-20 20:46:49 +08:00
|
|
|
parser.add_argument(
|
|
|
|
'-p', '--pattern', action='append',
|
|
|
|
help=(
|
|
|
|
'regex pattern for branch name to disallow commits to, '
|
2019-04-21 06:07:14 +08:00
|
|
|
'may be specified multiple times'
|
2019-04-20 20:46:49 +08:00
|
|
|
),
|
|
|
|
)
|
2017-03-21 01:36:51 +08:00
|
|
|
args = parser.parse_args(argv)
|
|
|
|
|
2021-03-04 21:41:04 +08:00
|
|
|
protected = frozenset(args.branch or ('master', 'main'))
|
2019-04-21 06:07:14 +08:00
|
|
|
patterns = frozenset(args.pattern or ())
|
2019-04-20 20:46:49 +08:00
|
|
|
return int(is_on_branch(protected, patterns))
|
2017-03-21 01:36:51 +08:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2021-10-24 01:23:50 +08:00
|
|
|
raise SystemExit(main())
|