Search code examples
gitsquash

Git commit template does not show up when I squash N-commits


I have setup path to the template file on my config file, and it works fine when I do basic commit (git add -A . && git commit):

[commit]
        template = .git-commit-template.txt

Instead when I try to squash N-commits, and also add their messages, my commit template does not show up.

=> Is there any way add git template message during squashing last N commits?


The way I squash my last 2 commits with the help of this answer: https://stackoverflow.com/a/5201642/2402577

If you want to start editing the new commit message with a concatenation of the existing commit messages:
git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})"

#!/bin/bash

git reset --soft HEAD~2
git commit --edit -m"$(git log --format=%B --reverse HEAD..HEAD@{1})" # template message does not show up

As alternative when I do following I get the same result:

git reset --hard HEAD~2 && git merge --squash HEAD@{1} && git commit


Solution

  • The -m argument you have in your sample command overrides your template.

    You might want to write a small script that:

    • reads your template;
    • runs the desired git log command;
    • inserts the git log output at some defined template location (perhaps using a syntax of your own invention in the template);
    • writes the resulting file somewhere, as a temporary file;
    • invokes git commit --edit -F /path/to/temporary/file rather than git commit --edit -m ...;
    • removes the temporary file when git commit itself returns;
    • exits with the exit status of the git commit command.

    Note, however, that git merge --squash obeys the merge.log configuration knob, which might be close to what you want. You can run git -c merge.log=20 merge --squash .... The drawback is that this is the %s format, not the %B format: you get only the subject lines.