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

Git

Git Problem Overview


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.

Git Solutions


Solution 1 - Git

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

Solution 2 - Git

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.

Solution 3 - Git

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

Solution 4 - Git

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrrevoView Question on Stackoverflow
Solution 1 - GitDave NeeleyView Answer on Stackoverflow
Solution 2 - GitrrevoView Answer on Stackoverflow
Solution 3 - GitpattivacekView Answer on Stackoverflow
Solution 4 - GitCoYoT3View Answer on Stackoverflow