Get last x commits from Github repo using Github Api V4

Viewed 3203

I'm trying to use the new Github GraphQL api (v4) and I don't seem to be able to figure out how to get the last x commits for master. I've used repository and ref but they still don't give me what I need.

The query below almost gives me what I need:

query{
  repository(owner: "typelevel", name: "cats") {
    refs(refPrefix:"refs/heads/", last: 5) {
      edges{
        node {
          associatedPullRequests(states: MERGED, last: 5) {
            edges{
              node {
                title
                baseRef {
                  name
                  prefix
                }
                baseRefName
                commits(last: 10) {
                  edges {
                    node {
                      commit {
                        abbreviatedOid
                        message

                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

but:

  1. doesn't seems to exactly match what is in the repo
  2. limited to PRs
  3. seems too unwieldy

I also tried using defaultBranchRef but that didn't work either:

query{
  repository(owner: "typelevel", name: "cats") {
    defaultBranchRef {
      name
      prefix
      associatedPullRequests(states: [MERGED], last: 5) {
        edges {
          node {
            title
          }
        }
      }
    }
  }
}

I've been testing the queries using the explorer app on the Github api page.

Any ideas?

3 Answers

Here's the shortest way that works on any default branch even if it's not named master

Last 10 commits

{
  repository(owner: "fregante", name: "webext-fun") {
    defaultBranchRef {
      target {
        ... on Commit {
          history(first: 10) {
            nodes {
              oid
            }
          }
        }
      }
    }
  }
}

Last 1 commit (HEAD)

{
  repository(owner: "fregante", name: "webext-fun") {
    defaultBranchRef {
      target {
        oid
      }
    }
  }
}
Related