如何使用Github API获取原始的fork仓库?

9

我想知道如何从我的派生存储库中获取原始存储库。

我正在使用https://api.github.com/users/:user/repos?type=forks来获取派生存储库的列表。它返回了各种分支的链接,但我找不到如何获取原始存储库。

有什么想法吗?

注意:还有一些循环遍历https://api.github.com/users/:user/events的东西。

2个回答

7
你可以使用你提到的端点加载分叉存储库列表:
curl https://api.github.com/users/:user/repos?type=forks

这将会返回类似以下的JSON数据流(省略了无关信息):

[
  {
    "id": 24328834,
    "name": "repo_name",
    "full_name": ":user/repo_name",
    "owner": {
    }
    ...
    "url": "https://api.github.com/repos/:user/repo_name",
    ...
  }
  {
    "id": 24328835,
    "name": "repo_name_2",
    "full_name": ":user/repo_name_2",
    "owner": {
      ...
    }
    ...
    "url": "https://api.github.com/repos/:user/repo_name_2"
    ...
  }
]

根据@jasonrudolph的建议编辑

接着,从返回的列表中取出 name 元素键下的 repo_name 并使用它构建仓库 URL,或者只需引用 url 元素以发出以下 GET 请求:

curl https://api.github.com/repos/:user/repo_name

这将为您提供所请求的用户存储库信息(请注意,这是最简单的查询URL),您可以从中检索以下内容:
  • 包含存储库的父JSON元素,其中发行的存储库被分叉,包括其ID /名称/ URL等信息...
  • 包含原始存储库信息的源JSON元素,以防发行的存储库是另一个存储库的分支。
类似以下内容(此处父项仅是源代码,即存储库是从原始存储库分叉出来的):
{
  "id": 24328834,
  "name": "repo_name",
  "full_name": "user/repo_name",
  "owner": {
    ...
  },
  ...
  "parent": {
    "id": 354448,
    "name": "repo_name",
    "full_name": "real_owner_name/repo_name",
    "owner": {
      ...
    }
  }
  "source": {
    "id": 354448,
    "name": "repo_name",
    "full_name": "real_owner_name/repo_name",
    "owner": {
      ...
    }
  }
}

1
不必从响应中提取“name”属性并使用它手动构建URL,您可以直接使用“url”属性(例如,https://gist.github.com/jasonrudolph/4aa694db242c1cfbf2a5#file-response-json-L116)。 - jasonrudolph
4
要获取原始代码库,请使用source属性(而非parent属性)。parent属性包含该分支的直接父分支。请注意,该代码库可能是一个分支的分支。在这种情况下,parent不是原始代码库。例如,对于一个是分支的分支的repo,请注意parent属性(http://git.io/vehth)和source属性(http://git.io/vehqJ)之间的区别。 - jasonrudolph
1
@jasonrudolph 感谢您的笔记,我已经编辑了相关问题 :) - tmarwen

0
这实际上使用GraphQL API要简单得多。例如,这是如何查询您自己的存储库列表并显示它们的名称、是否为派生存储库以及其父存储库的URL。您可以将其原样粘贴到GraphQL Explorer中。
query {
  viewer {
    repositories(first:10) {
      nodes {
        name,
        isFork,
        parent {
          url
        }
      }
    }
  }
}

输出

{
  "data": {
    "viewer": {
      "repositories": {
        "nodes": [
          {
            "name": "cucumber",
            "isFork": true,
            "parent": {
              "url": "https://github.com/cucumber/cucumber-ruby"
            }
          },
          ...
        ]
      }
    }
  }
}
parent.url 是从原始仓库克隆的分支的URL。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接