如何以编程方式检测GitHub存储库中的非活动分支?

时间:2014-08-26 12:12:46

标签: git github git-branch github-api

我在GitHub存储库中有十几个存储库。存储库结构如下所示:

   + project1 
       +------- trunk
       +------- tags
       +------- branches
       + ------- releases
   + project2
       ....

我们的政策要求在30天不活动后删除任何有效分支。但是,没有自动检测这种非活动分支的方法。偶尔,我有一些不活跃的分支,可以存活30天。

是否有一个脚本列出分支,以及它们在所有GitHub存储库中的最后提交日期?

Edit1 - 还有一种方法可以通过API获取有多少组织及其所包含的项目?

2 个答案:

答案 0 :(得分:4)

GitHub Repository API 应该能够为您提供帮助。

列出分支

获取有关分支的详细信息

此调用方法公开分支的提示(即最新提交),您可以从中检索提交日期。在此基础上,您可以评估"活动"每个分支。

分支详细信息的示例输出

{
  "name": "coverity",
  "commit": {
    "sha": "f341f3a1276cbec3f6ee9d02264bd4453ca20835",
    "commit": {
      "author": {
        "name": "nulltoken",
        "email": "email@gmail.com",
        "date": "2014-05-03T21:28:26Z"
      },
      "committer": {
        "name": "nulltoken",
        "email": "email@gmail.com",
        "date": "2014-05-09T11:10:01Z"
      },
      "message": "Configure Coverity Scan hook for Travis",
      "tree": {
        "sha": "a5092e975145b96356df6b57cbf50e2d8c6140f8",
        "url": "https://api.github.com/repos/libgit2/libgit2sharp/git/trees/a5092e975145b96356df6b57cbf50e2d8c6140f8"
      },
      "url": "https://api.github.com/repos/libgit2/libgit2sharp/git/commits/f341f3a1276cbec3f6ee9d02264bd4453ca20835",
      "comment_count": 0
    },
    "url": "https://api.github.com/repos/libgit2/libgit2sharp/commits/f341f3a1276cbec3f6ee9d02264bd4453ca20835",

[...]

答案 1 :(得分:1)

如果您不介意,以下是python代码段,其中列出了裸存储库的非活动分支:

#!/bin/env python3
import pygit2, os, datetime

repo = pygit2.Repository(pygit2.discover_repository(os.getcwd()))
time_now = datetime.datetime.now()
for branch in (repo.lookup_branch(b) for b in repo.listall_branches()):
    last_commit = branch.get_object()
    commit_time = datetime.datetime.fromtimestamp(last_commit.commit_time)
    age = time_now - commit_time
    if age > datetime.timedelta(days=30):
        print("{} {} {}".format(last_commit.author.email, branch.branch_name, commit_time))

或者是删除超过100天的分支的Shell脚本版本:

git for-each-ref --sort=committerdate refs/ --format='%(committerdate:raw) %(refname:short)' | awk "\$1 < $(date -d "-100 day" "+%s") {print(\$3)}" | xargs git branch -D