mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-04 19:26:52 +00:00
feat: [no_commit_to_branch] Add user friendly error message
This commit is contained in:
parent
848f775476
commit
c1efc9943f
2 changed files with 51 additions and 21 deletions
|
|
@ -9,29 +9,37 @@ 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:
|
||||
def get_current_branch() -> str | None:
|
||||
try:
|
||||
ref_name = cmd_output('git', 'symbolic-ref', 'HEAD')
|
||||
except CalledProcessError:
|
||||
return False
|
||||
return None
|
||||
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
|
||||
return '/'.join(chunks[2:])
|
||||
|
||||
|
||||
def is_on_branch(
|
||||
current_branch: str,
|
||||
protected: AbstractSet[str],
|
||||
patterns: AbstractSet[str] = frozenset(),
|
||||
) -> bool:
|
||||
return current_branch in protected or any(
|
||||
re.match(p, current_branch) for p in patterns
|
||||
)
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
'-b', '--branch', action='append',
|
||||
'-b',
|
||||
'--branch',
|
||||
action='append',
|
||||
help='branch to disallow commits to, may be specified multiple times',
|
||||
)
|
||||
parser.add_argument(
|
||||
'-p', '--pattern', action='append',
|
||||
'-p',
|
||||
'--pattern',
|
||||
action='append',
|
||||
help=(
|
||||
'regex pattern for branch name to disallow commits to, '
|
||||
'may be specified multiple times'
|
||||
|
|
@ -41,7 +49,20 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||
|
||||
protected = frozenset(args.branch or ('master', 'main'))
|
||||
patterns = frozenset(args.pattern or ())
|
||||
return int(is_on_branch(protected, patterns))
|
||||
current_branch = get_current_branch()
|
||||
|
||||
if current_branch is None:
|
||||
return 0
|
||||
|
||||
on_branch = is_on_branch(current_branch, protected, patterns)
|
||||
|
||||
if on_branch:
|
||||
print(
|
||||
f'You are currently on {current_branch} branch, for which '
|
||||
f'pre-commit script does not permit this action.',
|
||||
)
|
||||
|
||||
return int(on_branch)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue