I have a number of branches in my local git repository and I keep a particular naming convention which helps me distinguish between recently used and old branches or between merged and not merged with master.
Is there a way to color branch names in the output of git branch
according to some regexp-based rules without using external scripts?
The best I've come up with so far is to run git branch
through an external script, and create an alias. However, this may not be very portable...
We use this sequence \[\e[32m\] to set the color of the text goes after that sequence, until another color is set. In this sequence, \[ and \] are used to mark the start and end of non-printing characters. Between them, \e denotes an ASCII escape character, and follows by [32m , which is the actual color code.
In order to change a branch name on Git, you have to use the “git branch” command followed by the “-m” option. Next, you just have to specify the name of the new branch. Note : before changing the branch name, make sure to switch to the branch that you want to rename.
Branch names must conform to a few simple rules. You can use the forward slash (/) to create a hierarchical name scheme. However, the name cannot end with a slash. The name cannot start with a minus sign (-).
git-branch
doesn't let you do thatIs there a way to color branch names in the output of
git branch
according to some regexp-based rules without using external scripts?
No; Git doesn't offer you a way of customising the colors in the output of git branch
based on patterns that the branch names match.
The best I've come up with so far is to run
git branch
through an external script, and create an alias.
One approach is indeed to write a custom script. However, note that git branch
is a porcelain Git command, and, as such, it shouldn't be used in scripts. Prefer the plumbing Git command git-for-each-ref
for that.
Here is an example of such a script; customize it to suit your needs.
#!/bin/sh
# git-colorbranch.sh
if [ $# -ne 0 ]; then
printf "usage: git colorbranch\n\n"
exit 1
fi
# color definitions
color_master="\033[32m"
color_feature="\033[31m"
# ...
color_reset="\033[m"
# pattern definitions
pattern_feature="^feature-"
# ...
git for-each-ref --format='%(refname:short)' refs/heads | \
while read ref; do
# if $ref the current branch, mark it with an asterisk
if [ "$ref" = "$(git symbolic-ref --short HEAD)" ]; then
printf "* "
else
printf " "
fi
# master branch
if [ "$ref" = "master" ]; then
printf "$color_master$ref$color_reset\n"
# feature branches
elif printf "$ref" | grep --quiet "$pattern_feature"; then
printf "$color_feature$ref$color_reset\n"
# ... other cases ...
else
printf "$ref\n"
fi
done
Put the script on your path and run
git config --global alias.colorbranch '!sh git-colorbranch.sh'
Here is what I get in a toy repo (in GNU bash):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With