mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-03-30 18:26:53 +00:00
New hook for enforcing branch name
Use a regex to validate the naming convention the branch should follow. If it's not correct, it fails.
This commit is contained in:
parent
ee30c6ada9
commit
86d5ab84cb
4 changed files with 58 additions and 0 deletions
38
pre_commit_hooks/enforce_branch_name.py
Normal file
38
pre_commit_hooks/enforce_branch_name.py
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
from typing import AbstractSet
|
||||
from typing import Sequence
|
||||
|
||||
from pre_commit_hooks.util import CalledProcessError
|
||||
from pre_commit_hooks.util import cmd_output
|
||||
|
||||
OK = 0
|
||||
ERROR = 1
|
||||
|
||||
|
||||
def branch_follows_pattern(patterns: AbstractSet[str]) -> 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 any(re.match(p, branch_name) for p in patterns)
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"-p",
|
||||
"--pattern",
|
||||
action="append",
|
||||
help=("regex pattern that the name of the branch must comply with"),
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
return OK if branch_follows_pattern(frozenset(args.pattern)) else ERROR
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Loading…
Add table
Add a link
Reference in a new issue