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

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

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


当前回答

Gitv2.19引入了branch.sort配置选项(参见branch.sor)。

因此git分支将默认按提交日期(降序)排序

# gitconfig
[branch]
    sort = -committerdate     # Descending

脚本:

git config --global branch.sort -committerdate

So,

git branch

输出:

* dev
  master
  _

And

git branch -v

输出:

* dev    0afecf5 Merge branch 'oc' into dev
  master 652428a Merge branch 'dev'
  _      7159cf9 Merge branch 'bashrc' into dev

其他回答

下面是另一个脚本,它执行所有其他脚本所做的操作。实际上,它为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}"
}

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

gitbranch--sort=-committerdate|head-5

我作为脚本的最佳结果:

git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname:short)|%(committerdate:iso)|%(authorname)' |
    sed 's/refs\/heads\///g' |
    grep -v BACKUP  | 
    while IFS='|' read branch date author
    do 
        printf '%-15s %-30s %s\n' "$branch" "$date" "$author"
    done

Git分支名称列表,按最近提交排序…

根据Jakub的回答和Joe的提示,下面将去掉“refs/heads/”,因此输出仅显示分支名称:


命令:

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

结果:

这是我想要的变体:

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

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