Verify that a commit message contains some string with pre-commit

Viewed 29

I would like to ensure if my commit message contains a given string using pre-commit. I tried using a pygrep based hook, but it does not handle the multiline as expected.

For example, my commit message is:

My commit message

Changelog: trial

I want to validate that the commit message contains "Changelog:".

Does anyone have an idea?

1 Answers

with pygrep this is fairly easy -- but you'll need to invert the usual behaviour of pygrep (which is to error when present)

repos:
-   repo: local
    hooks:
    -   id: needs-changelog
        name: commit message needs "Changelog:"
        language: pygrep
        entry: '^Changelog:'
        args: [--multiline, --negate]
        stages: [commit-msg]

this also utilizes --multiline such that the regex can match anywhere in the message. --negate flips the usual pygrep behaviour

$ git commit -m "foo"
commit message needs "Changelog:"........................................Failed
- hook id: needs-changelog
- exit code: 1

.git/COMMIT_EDITMSG

$ git commit -m $'foo\nChangelog: whatever'
commit message needs "Changelog:"........................................Passed
[main (root-commit) 5d10868] foo Changelog: whatever
 1 file changed, 9 insertions(+)
 create mode 100644 .pre-commit-config.yaml


disclaimer: I created pre-commit

Related