Github List Files Recursively with GraphQL

At this point GraphQL doesn’t seem to provide the right constructs to list files folders of unconstrained depth. Instead, users will make multiple calls into the API. So let’s get started:

{
  "owner": "gliptak",
  "name": "aws-cdk-python",
  "rev": ""
}
query DefaultBranch($owner: String!, $name: String!) {
  repository(owner: $owner, name: $name) {
    name
    defaultBranchRef {
      name
    }
  }
}

returns

{
  "data": {
    "repository": {
      "name": "aws-cdk-python",
      "defaultBranchRef": {
        "name": "master"
      }
    }
  }
}

Subtitute the default branch from above into the query variables with : appended (master: for our example or other syntax HEAD:) and run:

query RepoFiles($owner: String!, $name: String!, $rev: String!) {
  repository(owner: $owner, name: $name) {
    object(expression: $rev) {
      id
      ... on Tree {
        entries {
          name
          oid
          type
        }
      }
    }
  }
}

rev above points to a directory Tree to list entries for returning (slightly abbreviated):

{
  "data": {
    "repository": {
      "object": {
        "entries": [
          {
            "name": ".env",
            "oid": "9a10a235bf64f16f2684148e33c7aaf5eaa88721",
            "type": "blob"
          },
          {
            "name": ".github",
            "oid": "17ddafeaf72048e2dcb4a3ccb05ffbc12459cabd",
            "type": "tree"
          },
          ...
        ]
      }
    }
  }
}

From above oid/path(including branch prefix) can be used to list entries of trees and to display content of blobs as below:

query RepoFiles($owner: String!, $name: String!, $rev: String!) {
  repository(owner: $owner, name: $name) {
    object(expression: $rev) {
      ... on Blob {
        text
      }
    }
  }
}
{
  "data": {
    "repository": {
      "object": {
        "text": "USER_ID=1001\nGROUP_ID=1001\n"
      }
    }
  }
}

API transaction limits might apply so multiple queries could be performed in a single call.

comments powered by Disqus

Related