From c03c3986cdf013e48d74bc1d26298465abbb1b4a Mon Sep 17 00:00:00 2001 From: Sorin Sbarnea Date: Mon, 4 Nov 2024 09:38:18 +0000 Subject: [PATCH] Allow display of custom message when no-commit-to-branch fails This change should make the failures of no-commit-to-branch easier for people that might encounter it as maintainers can provide information about allowed branch names. Current behavior just gives an opaque error that is not very useful for people that do not have a lot of knowledge about the project they are contributing to. --- README.md | 1 + pre_commit_hooks/no_commit_to_branch.py | 11 ++++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c0f678f..8317c3d 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,7 @@ Protect specific branches from direct checkins. branches. - `-p` / `--pattern` can be used to protect branches that match a supplied regex (e.g. `--pattern, release/.*`). May be specified multiple times. + - `-m` / `--message` can be used to customize the error message in case of failure. Note that `no-commit-to-branch` is configured by default to [`always_run`](https://pre-commit.com/#config-always_run). As a result, it will ignore any setting of [`files`](https://pre-commit.com/#config-files), diff --git a/pre_commit_hooks/no_commit_to_branch.py b/pre_commit_hooks/no_commit_to_branch.py index b0b8b23..166b480 100644 --- a/pre_commit_hooks/no_commit_to_branch.py +++ b/pre_commit_hooks/no_commit_to_branch.py @@ -37,11 +37,20 @@ def main(argv: Sequence[str] | None = None) -> int: 'may be specified multiple times' ), ) + parser.add_argument( + '-m', '--message', default='', + help=( + 'What message to display if the the check fails' + ), + ) args = parser.parse_args(argv) protected = frozenset(args.branch or ('master', 'main')) patterns = frozenset(args.pattern or ()) - return int(is_on_branch(protected, patterns)) + result = int(is_on_branch(protected, patterns)) + if result: + print(args.message) + return result if __name__ == '__main__':