使用下面的GitHub API,可以在存储库中获取提交的元数据,从最新的到最旧的排序
https://api.github.com/repos/git/git/commits是否有一种方法可以获得类似的元数据,但以相反的时间顺序提交,也就是说,从存储库中最古老的提交开始?
注意:我想获得这样的元数据,而不必下载完整的存储库。
谢谢
发布于 2020-09-15 01:01:09
使用GraphQL API解决方案是可能的。这个方法与在回购中获得第一次提交本质上是一样的
获取最后一次提交并返回totalCount和endCursor:
{
repository(name: "linux", owner: "torvalds") {
ref(qualifiedName: "master") {
target {
... on Commit {
history(first: 1) {
nodes {
message
committedDate
authoredDate
oid
author {
email
name
}
}
totalCount
pageInfo {
endCursor
}
}
}
}
}
}
}它返回与游标和pageInfo对象类似的内容:
"totalCount": 950329,
"pageInfo": {
"endCursor": "b961f8dc8976c091180839f4483d67b7c2ca2578 0"
}我没有任何关于游标字符串格式b961f8dc8976c091180839f4483d67b7c2ca2578 0的源代码,但是我已经用超过1000次提交的其他存储库进行了测试,并且它似乎总是格式化如下:
<static hash> <incremented_number>为了迭代从第一次提交到最新版本,您需要从第1页开始从totalCount - 1 - <number_perpage>*<page>开始:
例如,为了从linux存储库获得前20次提交:
{
repository(name: "linux", owner: "torvalds") {
ref(qualifiedName: "master") {
target {
... on Commit {
history(first: 20, after: "fc4f28bb3daf3265d6bc5f73b497306985bb23ab 950308") {
nodes {
message
committedDate
authoredDate
oid
author {
email
name
}
}
totalCount
pageInfo {
endCursor
}
}
}
}
}
}
}请注意,这个repo中的提交总数随着时间的推移而改变,因此在运行查询之前,您需要获得总计数值。
下面是一个python示例,迭代Linux存储库的前300个提交(从最老的)开始:
import requests
token = "YOUR_ACCESS_TOKEN"
name = "linux"
owner = "torvalds"
branch = "master"
iteration = 3
per_page = 100
commits = []
query = """
query ($name: String!, $owner: String!, $branch: String!){
repository(name: $name, owner: $owner) {
ref(qualifiedName: $branch) {
target {
... on Commit {
history(first: %s, after: %s) {
nodes {
message
committedDate
authoredDate
oid
author {
email
name
}
}
totalCount
pageInfo {
endCursor
}
}
}
}
}
}
}
"""
def getHistory(cursor):
r = requests.post("https://api.github.com/graphql",
headers = {
"Authorization": f"Bearer {token}"
},
json = {
"query": query % (per_page, cursor),
"variables": {
"name": name,
"owner": owner,
"branch": branch
}
})
return r.json()["data"]["repository"]["ref"]["target"]["history"]
#in the first request, cursor is null
history = getHistory("null")
totalCount = history["totalCount"]
if (totalCount > 1):
cursor = history["pageInfo"]["endCursor"].split(" ")
for i in range(1, iteration + 1):
cursor[1] = str(totalCount - 1 - i*per_page)
history = getHistory(f"\"{' '.join(cursor)}\"")
commits += history["nodes"][::-1]
else:
commits = history["nodes"]
print(commits)https://stackoverflow.com/questions/48948949
复制相似问题