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

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

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


当前回答

我能够参考前面的例子来创建最适合我的东西。

git for each ref--sort=-提交日期refs/heads--format='%(authordate:短)%(颜色:红色)%(对象名称:短)%(%(颜色:绿色)%(提交日期:相对)%(颜色重置))'

正如下面评论中所建议的,您还可以包括远程分支和作者的姓名。

git for each ref--sort=-committedate refs/heads refs/remotes--format='%(authordate:短)%(颜色:红色)%(对象名称:短)%(%(颜色:绿色)%(提交日期:相对)%(颜色重置))%(作者姓名)'

下面是作为shell别名的两个命令,您可以轻松地将它们添加到shell概要文件中。

# show a list of local git branches sorted by the commit date
alias git.branches='git for-each-ref --sort=-committerdate refs/heads --format="%(authordate:short) %(color:red)%(objectname:short) %(color:yellow)%(refname:short)%(color:reset) (%(color:green)%(committerdate:relative)%(color:reset))"'

# show a list of local and remote git branches sorted by the commit date
alias git.branches.remote='git for-each-ref --sort=-committerdate refs/heads refs/remotes --format="%(authordate:short) %(color:red)%(objectname:short) %(color:yellow)%(refname:short)%(color:reset) (%(color:green)%(committerdate:relative)%(color:reset)) %(authorname)"'

其他回答

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

git branch -v

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

git branch -v --sort=committerdate

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

我知道已经有很多答案了,但下面是我的两分钱,作为一个简单的别名(我喜欢在底部显示我最近的分支):

[alias]
        br = !git branch --sort=committerdate --color=always | tail -n15
[color "branch"]
        current = yellow
        local = cyan
        remote = red

这将为您提供最新15个分支的漂亮概览,颜色为,突出显示当前分支(并带有星号)。

以下是最佳代码,它结合了其他两个答案:

git for-each-ref --sort=-committerdate refs/heads/ --format='%(committerdate:short) %(authorname) %(refname:short)'

git for each ref--sort=committedate-refs/heads/--format='%(HEAD)%(颜色:黄色)%(refname:short)%(color:reset)-%(颜色:红色)%(objectname:short)%

仅供参考,如果您想获得最近签出的分支列表(而不是最近提交的分支),可以使用Git的reflog:

$ git reflog | egrep -io "moving from ([^[:space:]]+)" | awk '{ print $3 }' | head -n5
master
stable
master
some-cool-feature
feature/improve-everything

另请参阅:如何获取最近签出的Git分支列表?