2

I'm writing a PHP script that lets users enter a GitHub owner & repo name, and then it downloads a zip file from that repo.

GitHub allows linking directly to the download of the latest release for a repo: /owner/name/releases/latest/download/name.zip (see https://docs.github.com/en/free-pro-team@latest/github/administering-a-repository/linking-to-releases). So if a repo has a release, that works fine.

However, for repos without a release, I want to download from the default branch instead. GitHub provides a link for this (green 'Code' button > 'Download ZIP'), but that URL includes the branch name: /owner/name/archive/[BRANCH].zip.

Is there a way to link directly to the download for the latest branch without knowing what the branch might be called? For example, something like this hypothetical URL: /owner/name/archive/latest.zip

BWPanda
  • 145
  • 7

2 Answers2

2

You would need to read the default branch of the repository first through GitHub API (See Get Repository)

Once you have the default branch, you can use it to complete your download URL

curl -L http://github.com/<user>/<repo>/archive/<branch>.zip --output <branch>.zip
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
2

Unless you need the default branch name for something, you can do this in one call.

https://api.github.com/repos/<user>/<repo>/zipball
Kerolos Zaki
  • 21
  • 1
  • 3