Search code examples
gitgit-commitgithookspre-commit-hook

How to get arguments from githook?


From the githook's doc says:

Hooks can get their arguments via the environment, command-line arguments, and stdin. See the documentation for each hook below for details.

But what are the mentioned arguments?

If I do commit with this command:

git commit -m "my commit" --trailer "Helped-by: Nganu <[email protected]>"

How to get trailer value in pre-commit or prepare-commit-msg hook?

I don't see any documentation about getting arguments in pre-commit or prepare-commit-msg hooks. And I tried using $0 like bash argument, but it failed.


Solution

  • For prepare-commit-msg,

    It takes one to three parameters. The first is the name of the file that contains the commit log message. The second is the source of the commit message, and can be: message (if a -m or -F option was given); template (if a -t option was given or the configuration option commit.template is set); merge (if the commit is a merge or a .git/MERGE_MSG file exists); squash (if a .git/SQUASH_MSG file exists); or commit, followed by a commit object name (if a -c, -C or --amend option was given).

    We can get the file that contains the commit message log from the first parameter, and then parse it to get the trailers.

    #!/bin/bash
    
    msg_file=$1
    echo msg_file:${msg_file}
    
    # parse msg_file to get trailers
    trailer=$(git interpret-trailers --parse ${msg_file} | grep '^Helped-by:')
    echo Trailer: ${trailer}