We have a requirement to list commits by branch. However, we also need to support use cases where the branch is already deleted. To be able to list commit history from a deleted branch, we just need to remember the head commit of that deleted branch then list history from that commit.
List commits by ref (branch or tag name)
This is the easy one. We can simply fetch the repository then use the ref
property to connect to a branch or tag then from there, we can list the commit history. We store the repository NodeID
so we can just lookup the repository.
Here is the query structure:
- Lookup the repository by
NodeID
- Lookup a Git Object using the repository’s
ref
object - Resolve the
ref
into aCommit
object which I think represents the head commit of the branch or tag - List a paginated commit history starting from the commit above
query ListCommits($repoId: ID!, $ref: String!, $perPage: Int!, $cursor: String) {
node(id: $repoId) {
... on Repository {
id
ref(qualifiedName: $ref) {
name
target {
...on Commit {
oid
history(first: $perPage, after: $cursor) {
nodes {
oid
message
url
committedDate
}
pageInfo {
endCursor
hasNextPage
}
totalCount
}
}
}
}
}
}
}
List commits by a head commit ID
For deleted branches, we won’t be able to use ref
to list commit history for the branch. However, since we record the latest head commit in our end, we can still list the commit history by using the head commit ID. The query will look slightly different.
Query structure:
- Lookup for the repository
- Lookup a Git Object using the commit ID by using the
object
property of the repository - Resolve the
object
into aCommit
object - List commit history using above commit object
query ListCommitsByHeadCommitId($repoId: ID!, $commitId: GitObjectID!, $perPage: Int!, $cursor: String) {
node(id: $repoId) {
... on Repository {
id
object(oid: $commitId) {
... on Commit {
oid
history(first: $perPage, after: $cursor) {
nodes {
oid
message
url
committedDate
}
pageInfo {
endCursor
hasNextPage
}
totalCount
}
}
}
}
}
}
References:
- https://docs.github.com/en/graphql/reference/objects#repository
- https://docs.github.com/en/graphql/reference/interfaces#gitobject
- https://docs.github.com/en/graphql/reference/objects#ref
- https://docs.github.com/en/graphql/reference/objects#commit
Featured image by Vito Goričan.