如何根据他们的名字颜色Git分支? [英] How can I color Git branches based on their names?

查看:116
本文介绍了如何根据他们的名字颜色Git分支?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的本地git仓库有一些分支,我保持一个特定的命名约定,帮助我区分最近使用和旧的分支,或者合并和不与主合并。



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



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

解决方案

git-branch 不允许你这样做




有一种方法在输出 git


否;

Git不提供一种方法来定制 git branch 输出中基于分支名称匹配的模式的颜色。



编写自定义脚本




到目前为止,我想出的最好的方法是运行


一种方法是写一个自定义的脚本。但是,请注意,


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...

解决方案

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):

这篇关于如何根据他们的名字颜色Git分支?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆