【问题标题】:What is the simplest way to display all branches that have not been committed to for more than 6 months?显示所有超过 6 个月未提交的分支的最简单方法是什么?
【发布时间】:2020-10-15 18:32:13
【问题描述】:

公司的一个仓库中似乎存在 1836 个分支,我的任务是首先显示然后删除所有 6 个月未提交的分支。

我找到了this SO question 并尝试运行(同时使用 --until 和 --before 以及“月”):

#!/bin/bash
branches_to_delete_count=0
for k in $(git branch -a | sed /\*/d); do
  if [ -n "$(git log -1 --before='6 month ago' -s $k)" ]; then
    echo "NOT REALLY DELETING, git branch -D $k"
  fi
  ((branches_to_delete_count=branches_to_delete_count+1))
done
echo "Found $branches_to_delete_count branches to delete!"

但无济于事,我每次删除相同数量的分支,即 1836。

我做错了什么?如何列出所有超过 6 个月未提交的分支?

【问题讨论】:

标签: bash git shell


【解决方案1】:

我们还没有直接得到6个月前最后一次提交的分支名称,所以我们结合git命令和制作shell脚本

这里我们传递了两个 git 命令

  • 首先是git branch | sed s/^..// 这里获取分支并删除两个空格
  • 第二个是git log -1 --before='6 month ago' <branch-name>

在终端中传递以下命令 在终端中复制并粘贴分支名称

for branch in `git branch | sed s/^..//` ; do log=`git log -1 --before='6 month ago' $branch`; if [ ${#log} -gt 0 ] ; then echo $branch; fi; done

这是 shell 脚本以及与上面相同的 git 命令

test.sh保存shell脚本,改变模式chmod +x test.sh然后运行bash test.sh

month=6 #check how many year ago
for branch in `git branch | sed s/^..//`  #get branch one by one 
do
  log=`git log -1 --before='%s month ago'$month $branch` #getting log of the branch last commit base on month
  if [ ${#log} -gt 0 ] #check if  log has output then it has branch commit before specify month ago 
  then 
      echo $branch  # print branch name which is in our project
  fi
done

让我知道它是否有效

【讨论】:

  • 此代码与 OP 有相同的错误:它将列出所有分支。
【解决方案2】:

所有分支出现的原因:git log branch 不只查看分支的head,它查看它的整个历史

git log -1 --before='6 month ago' branch 将:

  • 展开branch的历史记录
  • 只保留超过 6 个月的提交
  • 保留这些提交中的第一个

由于(在您公司的存储库中)所有分支的提交历史至少有 6 个月,git log -1 --before='6 month ago' branch 将始终显示一行。


您可以将提交范围限制为“仅包含头部提交的范围”:

git log -1 --before='6 month ago' branch^..branch

或使用@phd 在他的评论中建议的git for-each-ref

git for-each-ref --format="%(refname) %(creatordate)" --sort='-creatordate' refs/heads/

并保留具有足够旧日期的分支。

【讨论】:

    猜你喜欢
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多