67

Is there a way to specify a git commit.template that is relative to a repository?

For configuration an example is

$ git config commit.template $HOME/.gitmessage.txt

But I would like to specify a template file relative to the .git folder of the repository.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
rrevo
  • 1,647
  • 1
  • 16
  • 22
  • 1
    Note: for those that want relative to home, `git config commit.template ~/.gitmessage.txt` is documented to work on `man` as of 1.9, and would be preferable to using `$HOME`, as you could use the same file even if you change username. – Ciro Santilli OurBigBook.com Jul 08 '16 at 08:13

4 Answers4

95

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
Dave Neeley
  • 3,526
  • 1
  • 24
  • 42
22

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.

Kyle Falconer
  • 8,302
  • 6
  • 48
  • 68
rrevo
  • 1,647
  • 1
  • 16
  • 22
8

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

Community
  • 1
  • 1
pattivacek
  • 5,617
  • 5
  • 48
  • 62
3

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à !

CoYoT3
  • 66
  • 6