How to specify a git commit message template for a repository in a file at a relative path to the repository?

This blog tipped me off that if the path to the template file is not absolute, then the path is considered to be relative to the repository root.

git config commit.template /absolute/path/to/file

or

git config commit.template relative-path-from-repository-root

I used the prepare-commit-msg hook to solve this.

First create a file .git/commit-msg with the template of the commit message like

$ cat .git/commit-msg
My Commit Template

Next create a file .git/hooks/prepare-commit-msg with the contents

#!/bin/sh

firstLine=$(head -n1 $1)

if [ -z "$firstLine"  ] ;then
    commitTemplate=$(cat `git rev-parse --git-dir`/commit-msg)
    echo -e "$commitTemplate\n $(cat $1)" > $1
fi

Mark the newly-created file as executable:

chmod +x .git/hooks/prepare-commit-msg

This sets the commit message to the contents of the template.


You can always specify a template at commit-time with -t <file> or --template=<file>.

See: http://git-scm.com/docs/git-commit

Another option might be to use a prepare-commit-msg hook: https://stackoverflow.com/a/3525532/289099


1. Create a file with your custom template inside your project directory.

In this example in the .git/ folder of the project :

$ cat << EOF > .git/.commit-msg-template
> My custom template
> # Comment in my template
> EOF

2. Edit the config file in the .git/ folder of your project to add the path to your custom template.

  • With git command :

    $ git config commit.template .git/.commit-msg-template
    
  • Or by adding in the config file the following lines :

    [commit]
      template = .git/.commit-msg-template
    

Et voilà !