rauthenticationgithubdevtools

Sourcing R files in a private github folder


I wish to source some R script in a private github folder and make it available in some environment through R.

When using a public github folder, both of these commands do the job: get_URL and source_url (from devtools).

However, things get complicated when the folder is private and authentication is needed.

Is there a way to accomplish this and put login details within these functions that would pass the username & password automatically if some github autenthication is needed to go forward?

Thanks is advance,

Tamas


Solution

  • TL;DR: It's possible, see the below code.


    For anyone's future use, here's a method to source a R script from a private Github repo, using httr, and optionally, devtools.

    I searched around enough to find various pieces to the solution, and just stitched them all together. So credit goes to multiple other threads and websites.

    Some sources are here, here and here.

    See below code:

    library(httr)
    
    # Source R script from Github
    script <-
      GET(
        url = "https://api.github.com/repos/{user_name}/{repo_name}/contents/{script_name}.R",
        authenticate({github_email}, {github_personal_access_token}),     # Instead of PAT, could use password
        accept("application/vnd.github.v3.raw")
      ) %>%
      content(as = "text")
    
    # Evaluate and parse to global environment
    eval(parse(text = script))
    

    This may only work for a private repo that you own. I'm not sure if it will work for a private repo that was shared with you.

    See this link to create a Github Personal Access Token (PAT). You can also save this as an environment variable within R, if desired. devtools::github_pat() can be useful here.

    Both your email and PAT (or password) need to be in quotations.