我想获得Git存储库中所有分支的列表,其中“最新”分支位于顶部,“最新的”分支是最近提交的分支(因此,更可能是我想关注的分支)。

有没有一种方法可以使用Git(a)按最新提交对分支列表进行排序,或者(b)以某种机器可读格式将分支列表与每个分支的最后提交日期一起获取?

最坏的情况是,我总是可以运行gitbranch获取所有分支的列表,解析其输出,然后运行git-log-n 1 branchname--format=format:%ci获取每个分支的提交日期。但这将在Windows环境下运行,在那里启动一个新进程相对昂贵,因此如果有很多分支,每个分支启动一次Git可执行文件可能会很慢。有没有一种方法可以用一个命令完成所有这些?


当前回答

根据提交人日期,只获取排名前五的分支名称:

gitbranch--sort=-committerdate|head-5

其他回答

下面是另一个脚本,它执行所有其他脚本所做的操作。实际上,它为shell提供了一个函数。

它的贡献是从Git配置中提取一些颜色(或使用默认值)。

# Git Branch by Date
# Usage: gbd [ -r ]
gbd() {
    local reset_color=`tput sgr0`
    local subject_color=`tput setaf 4 ; tput bold`
    local author_color=`tput setaf 6`

    local target=refs/heads
    local branch_color=`git config --get-color color.branch.local white`

    if [ "$1" = -r ]
    then
        target=refs/remotes/origin
        branch_color=`git config --get-color color.branch.remote red`
    fi

    git for-each-ref --sort=committerdate $target --format="${branch_color}%(refname:short)${reset_color} ${subject_color}%(subject)${reset_color} ${author_color}- %(authorname) (%(committerdate:relative))${reset_color}"
}

我发现以下命令对我的目的很有用。

git branch --sort=-committerdate | head -n 10

这将列出最新的10个分支。它很短,也可以在没有别名的情况下使用。

我喜欢使用相对日期,并将分支名称缩短如下:

git for-each-ref --sort='-authordate:iso8601' --format=' %(authordate:relative)%09%(refname:short)' refs/heads

这为您提供了输出:

21 minutes ago  nathan/a_recent_branch
6 hours ago     master
27 hours ago    nathan/some_other_branch
29 hours ago    branch_c
6 days ago      branch_d

我建议制作一个Bash文件来添加所有您喜爱的别名,然后将脚本分享给您的团队。下面是一个示例,只添加以下内容:

#!/bin/sh

git config --global alias.branches "!echo ' ------------------------------------------------------------' && git for-each-ref --sort='-authordate:iso8601' --format=' %(authordate:relative)%09%(refname:short)' refs/heads && echo ' ------------------------------------------------------------'"

然后,您可以这样做,以获得一个格式和排序良好的本地分支列表:

git branches

更新:如果要着色,请执行以下操作:

#!/bin/sh
#
(echo ' ------------------------------------------------------------‌​' && git for-each-ref --sort='-authordate:iso8601' --format=' %(authordate:relative)%09%(refname:short)' refs/heads && echo ' ------------------------------------------------------------‌​') | grep --color -E "$(git rev-parse --abbrev-ref HEAD)$|$"

下面是一个简单的命令,列出了具有最新提交的所有分支:

git branch -v

要按最近提交排序,请使用

git branch -v --sort=committerdate

资料来源:http://git-scm.com/book/en/Git-Branching-Branch-Management

这是我想要的变体:

git for-each-ref --sort=-committerdate --format='%(committerdate)%09%(refname:short)' refs/heads/ | tail -r

该tail-r反转列表,因此最近的commitedate是最后一个。