如何根据名称为Git分支着色?

Mic*_*bus 8 git colors git-branch

我在我的本地git存储库中有许多分支,并且我保留了一个特定的命名约定,这有助于我区分最近使用的和旧的分支,或者在merge和不与master合并之间.

有没有办法git branch根据一些基于正则表达式的规则在输出中为分支名称着色而不使用外部脚本?

到目前为止,我提出的最好的方法是运行git branch外部脚本,并创建一个别名.但是,这可能不是很便携......

jub*_*0bs 5

git-branch 不允许你这样做

有没有办法git branch根据一些基于正则表达式的规则在输出中为分支名称着色而不使用外部脚本?

没有; Git没有为您提供一种git branch根据分支名称匹配的模式自定义输出中颜色的方法.

编写自定义脚本

到目前为止,我提出的最好的方法是运行git branch外部脚本,并创建一个别名.

一种方法确实是编写自定义脚本.但是,请注意这git branch是一个瓷器Git命令,因此,它不应该在脚本中使用.喜欢管道Git命令git-for-each-ref.

这是一个这样的脚本的例子; 定制它以满足您的需求.

#!/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
Run Code Online (Sandbox Code Playgroud)

用它做一个别名

将脚本放在路径上并运行

git config --global alias.colorbranch '!sh git-colorbranch.sh'
Run Code Online (Sandbox Code Playgroud)

测试

这是我在玩具回购中获得的(在GNU bash中):

在此输入图像描述