Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including the current branch name in the commit template

Tags:

I have a commit template set up for git, and I would like to include the name of the current branch in it. I usually set up the branch to be the bug id, and it would help me with filling in boilerplate such as:

Bug : $BUG 

How can I perform such a substitution with the git comment template?

like image 836
Robert Munteanu Avatar asked Nov 03 '10 12:11

Robert Munteanu


People also ask

What is a commit template?

Commit Templates are predefined collections of metadata that you use regularly to commit, saving you time and eliminating the need to pick metadata each time you pull together. For example- If you frequently pull the two picklist fields Standard Case Reason field and the Custom Case Sub Reason field.

How do I add a commit to a message template?

Set a template: Open Settings > Tools > Commit Message Template and enter the desired template or set the path to a template file.

How do you find the branch of a commit?

It is based on "Find merge commit which include a specific commit". Find when a commit was merged into one or more branches. Find the merge commit that brought COMMIT into the specified BRANCH(es). Specifically, look for the oldest commit on the first-parent history of BRANCH that contains the COMMIT as an ancestor.

How do I add a description to a git branch?

To describe a branch, use git branch --edit-description , edit the opened file, save and exit.


1 Answers

I'd probably just use the prepare-commit-msg hook to add that to the file. From the (linked) manpage:

This hook is invoked by git commit right after preparing the default log message, and before the editor is started.

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 ... [message, template, merge, squash, or commit] ...

If the exit status is non-zero, git commit will abort.

The purpose of the hook is to edit the message file in place ...

You can get the current branch with git symbolic-ref HEAD.

You could just bypass templates altogether, and have the hook prepend/insert/append the branch name. Simplest case, appending, the script is just a shebang line, then git symbolic-ref HEAD >> "$1". Use your favorite method if you want to embed it - most readable to move the original aside, write, and append, but the method linked in the comments certainly works too.

If you'd prefer to use a template with placeholders, you could just do something like sed -i "s/Bug : \$BUG/BUG : $(git symbolic-ref HEAD)/" "$1". I'm sure you can imagine a lot of other variations.

You might want to suppress this behavior for some of the types of commits (that second argument) or even only turn it on if the second argument is "template", if you're using the boilerplate substitution approach.

like image 183
Cascabel Avatar answered Sep 23 '22 22:09

Cascabel