Leedehai
Leedehai

Reputation: 3960

How to write a python pre-push to check the commit message?

I know I can use commit-msg hook to check the message (I did it) but I wish to check the message again prior to push with different criteria.

The example given under .git/hooks was written in shell script, but I wish to write a python script the string operations I have in mind are more complex.

I know I can change the first line to #!/usr/bin/env python. My problem is, I don't know how to get the lastest commit's message string. I experimented with git rev-list (on that example's line 44) but it doesn't give me the message string and it needs the commit hash id. Note that the message string might be multiline (because the first line is restricted to be 50 characters at most).

EIDT: other questions asked how to write a pre-push script in Python, but they didn't involve checking the message string.

Upvotes: 5

Views: 2517

Answers (1)

phd
phd

Reputation: 94736

pre-push hook is passed a list of local/remote refs and commit IDs (sha1), so you have to read them line by line, split and get the local commit ID. See how it can be done in a shell script.

Having a commit ID you can extract full commit message with the command

git show --format='%B' -s $SHA1

In Python it is something like:

for line in sys.stdin:
    local_ref, local_sha1, remote_ref, remote_sha1 = line.strip().split()
    message = subprocess.check_output(
        ['git', 'show', '--format=%B', '-s', local_sha1])
    if not check(message):
        sys.exit(1)

Upvotes: 4

Related Questions