Skip to content

Instantly share code, notes, and snippets.

@cjtexas
Created February 12, 2018 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjtexas/6cd6ccff56bc2705324ab4371c93bf83 to your computer and use it in GitHub Desktop.
Save cjtexas/6cd6ccff56bc2705324ab4371c93bf83 to your computer and use it in GitHub Desktop.
source all r files in a gist
library(getPass)
library(httr)
library(rvest)
#' source_gist_all
#'
#' Standalone replacement for \code{devtools::source_gist} which
#' sources all the R files in a github gist with
#' authentication and error handling.
#' I didn't replicate any of the individual file-level
#' features of \code{devtools::source_gist} like hash matching
#' because those don't apply as much when sourcing multiple files.
#'
#' @param id character gist id or url
#' @param user character github username
#' @param pass character github password
#'
#' @import getPass httr rvest
#' @export
#'
source_gist_all <- function(id="7b07ee41e42791c7d61b145487d62037", user=NULL, pass=NULL) {
if (!grepl("github.com", id)) {
id <- paste0("https://gist.github.com/", id)
}
if (is.null(user)) {
user <- getPass::getPass("github user: ")
}
if (is.null(pass)) {
pass <- getPass::getPass("github pass: ")
}
res <- httr::GET(id, httr::authenticate(user, pass))
doc <- xml2::read_html(res)
nodes <- rvest::html_nodes(doc, css = "a")
links <- rvest::html_attr(nodes , "href")
matches <- grepl("\\.(r|R)$", links)
r_files <- as.character(links[matches])
for (i in 1:length(r_files)) {
url <- paste0("https://gist.github.com", r_files[i])
res <- httr::GET(url, httr::authenticate(user, pass))
if (httr::http_error(res)) {
stop("Authenticated Request Failed... \nCheck Your Credentials")
}
text <- httr::content(res)
fun_text <- tryCatch(parse(text = text), error = function(e) e)
if ("expression" %in% class(fun_text)) {
message(paste("sourcing file:", basename(as.character(r_files[i]))))
eval(fun_text, envir = parent.frame())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment