List of branches a commit appears on

徘徊边缘 提交于 2019-12-19 08:06:24

问题


Using the GitHub API (v3) I'd like to figure out which branches a commit appears on. I didn't find a way to directly query this, either through repo commits or the commit data objects. An alternate solution would be to list all the branches, and compare with their HEAD; I guess the comparison would fail if the commit is not on the given branch.

Is this supported via the current API, and I just missed it? If not, do you have a (better) workaround?


回答1:


That's not possible directly via the GitHub API.

Workaround 1:

  1. get a list of all branches
  2. for each branch, get a list of commits on that branch
  3. check if the commit is in the list of commits for each branch

Workaround 2 (I think this will work, but not 100% sure if I missed a case):

  1. get a list of all branches
  2. for each branch, compare the branch with the SHA:

    https://api.github.com/repos/:user/:repo/compare/:branch...:sha_of_commit

  3. If the value of the status attribute in the response is diverged or ahead, then the commit is not in the branch. If the value of the status attribute is behind or identical, then the commit is in the branch.




回答2:


I haven't checked if this is directly supported by the GitHub API, but this is trivial to do using plain Git:

git branch --all --contains <commit>

That will list all branches (local and remote) in a local repository that contain the given commit.




回答3:


GitLab API

Following Ivan Zuzak's solution number 2, to know if a commit is on a branch:

Use GitLab's repository compare API, and compare from the branch, to the commit

GET /projects/:id/repository/compare?from=<branch>&to=<sha_of_commit>

If the commits list is empty, then yes, the commit is on that branch.

In Python, using python-gitlab:

def is_commit_on_branch(project, commit, branch):
    c = project.repository_compare(branch, commit)
    return not c['commits']


来源:https://stackoverflow.com/questions/23899329/list-of-branches-a-commit-appears-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!