Search code examples
gitgithub-cli

List files in repo using `gh` from GitHub CLI?


Is there a gh command to list files in a directory without having a working copy clone?

I have found a git command that will do it, but I think this is working only on the local working copy.

git ls-tree --name-only HEAD
git ls-tree --name-only -r HEAD

Solution

  • gh api is a gh command that can help you call the github apis. You can use the -q option to use jq to sort

    For example, here's one way to get a list of contents in one command, based on the trees api:

    gh api '/repos/{owner}/{repo}/git/trees/{branch}?recursive=true' -q '.tree[]|.path'
    

    Here, owner is your github user (or organization) name, repo is the repo name, branch is the branch name. Then .tree[]|.path turns the raw json output into a list of just paths in your repo.

    recursive option will save you from having to recurse the directory structure yourself, but has a size limit

    Note: The limit for the tree array is 100,000 entries with a maximum size of 7 MB when using the recursive parameter.

    If you're concerned about that limit, you'll have to do your own recursion.

    There is also a contents api (with the same 100k limit) as well as one for tarballs or zipfiles if you're interested in the contents of those files and not just their names.

    I encourage you to explore the github apis in depth - github has some really interesting APIs and did a very good job implementing them.