GraphQL

Github GraphQL – List Commit History

Github GraphQL – List Commit History

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 a Commit 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 a Commit 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:

Featured image by Vito Goričan.

Leave a reply

Your email address will not be published. Required fields are marked *