Search code examples
rgithubgithub-api

R: How to download single file from specific branch of private GitHub repo?


How to download single file from specific branch of GitHub private repo using R?

It can be easily done for default branch, e.g.:

require(httr)

github_path = "https://api.github.com/repos/{user}/{repo}/contents/{path_to}/{file}"
github_pat = Sys.getenv("GITHUB_PAT"))

req <- content(GET(github_path,
                   add_headers(Authorization = paste("token", github_pat))), as = "parsed")

tmp <- tempfile()
r1 <- GET(req$download_url, write_disk(tmp))

...but I can't figure out how to do that for specific branch. Tried to include branch name in github_path but it didn't work (Error in handle_url(handle, url, ...)).

Since it is easy with classic curl, e.g.:

curl -s -O https://{PAT}@raw.githubusercontent.com/{user}/{repo}/{branch}/{path_to}/{file}

...I tried to do it like:

tmp <- tempfile()
curl::curl_download("https://{PAT}@raw.githubusercontent.com/{user}/{repo}/{branch}/{path_to}/{file}", tmp)

But it didn't work as well.

What am I missing? Thanks!


Solution

  • You can use curl in R like this to include the auth header and the path to the desired file:

    library(curl)
    h <- new_handle(verbose = TRUE)
    handle_setheaders(h,
      "Authorization" = "token ghp_XXXXXXX"
    )
    con <- curl("https://raw.githubusercontent.com/username/repo/branch/path/file.R", handle = h)
    readLines(con)