Reputation: 2351
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?
Upvotes: 8
Views: 2658
Reputation: 1225
In case anyone using the PyGitHub (https://pygithub.readthedocs.io/en/latest/introduction.html) library for API calls -
First get the list of all branches and then
g = Github(<accesskey>)
repo = g.get_repo(<repository>)
is_commit_in_branch = repo.compare('stable-2.11', <commit_id>).status
# If it returns behind or identical, then the commit is in the branch.
Upvotes: 1
Reputation: 1263
There is no direct endpoint to list the branches by a commit ID. But you can use a combination of other endpoints to solve this.
Condition 1 Use branches-where-head endpoint to get the name of the branches where the given commit ID is the head.
Condition 2 If condition 1 returns empty, get pull info object using the commit ID and extract the branch information using pulls info endpoint. Tip: The return object contains properties - base.ref and head.ref which has the branch name. If base.ref is the name of the master branch, use head.ref which should give you the name of the branches that contains the commit ID.
Upvotes: 0
Reputation: 137398
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']
Upvotes: -2
Reputation: 18762
That's not possible directly via the GitHub API.
for each branch, compare the branch with the SHA:
https://api.github.com/repos/:user/:repo/compare/:branch...:sha_of_commit
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.
Upvotes: 25
Reputation:
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.
Upvotes: 1