I should like to add my team name in the commit message automatically, that I have registered in the global config with the following command:
git config --global user.team "Seawolves"
There are many teams working in same project and we share a template file that is specified in gitconfig file.
[commit]
template = /mnt/share/gitmessage
Here is how part of my ~/.gitconfig look like:
cat ~/.gitconfig
[user]
name = Rajesh Khanna
email = rajesh.khanna@somthing.com
team = Seawolves
What is the best way to get the team name from ~/.gitconfig and git into the commit message? Should I use a prepare-commit-msg hook? Or is it an easier way to get the message in like its done automatically for email and name?
Or do I need to fetch it using the command: git config user.team
and just echo it into the message similar to what I found here: https://gist.github.com/bartoszmajsak/1396344/97081e76ab275f5fe526347908503febd1340495
The best way to handle this is indeed to use the prepare-commit-msg
hook. When you create one, you should take note of the arguments passed to it, and, unless you want to make your life needlessly difficult, avoid modifying it when you're using git commit --amend
(such as when the second argument is commit
).
Note that the hook needs to modify the file that's the first argument in place, which is different from what many people expect. As such, you will often want to use something like the -i
argument to Perl, Ruby, or sed
, or a scriptable line editor like ed -s
or ex -s
with the w
command.
If you're trying to add a trailer, then git interpret-trailers
may be helpful to add the entry you desire based on the config, and you can customize it to not add an entry if one is already present. It can't use user.team
, but it can use other configuration options to set the trailer.
An example where you're trying to simply replace a %(team)
token from the template with the value of user.team
looks like this:
#!/bin/sh
file="$1"
from="$2"
[ "$from" = commit ] && exit 0
TEAM=$(git config user.team) perl -i -e 's/\%\(team\)/$ENV{TEAM}/g' "$file"
This pulls the configuration value into a TEAM
environment variable which is passed to Perl, and then the %(team)
is replaced by the value of that environment variable. You can do this with sed
as well, but you must ensure your user.team
value doesn't contain a slash (or whatever other delimiter you use):
sed -i -e "s/%(team)/$(git config user.team)/g"
Note that this construction is for GNU sed; BSD sed, like on macOS, required an additional argument when -i
is used. Since this is not portable, you should avoid this syntax and use Perl or Ruby instead unless you are certain it will only ever be used on a single OS.