问题
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...
回答1:
git-branch
doesn't let you do that
Is 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.
Write a custom script
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
Make an alias out of it
Put the script on your path and run
git config --global alias.colorbranch '!sh git-colorbranch.sh'
Test
Here is what I get in a toy repo (in GNU bash):
来源:https://stackoverflow.com/questions/31984968/how-can-i-color-git-branches-based-on-their-names