Last active
August 18, 2017 17:35
-
-
Save russellpierce/b63dac5585c4fc8a0f2ff5c6b4851f93 to your computer and use it in GitHub Desktop.
Guarantee that the required version (or higher) of a package is installed and load it; otherwise get from github
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Require and install package version | |
#' | |
#' Guarantee that the required version (or higher) is installed. | |
#' This function will install from github in the desired version isn't found on CRAN or the current machine version is insufficient. | |
#' | |
#' @param packageName A quoted string, e.g. 'lubridate' | |
#' @param githubLoc e.g., 'hadley/lubridate' | |
#' @param requiredVersion e.g. '1.4' | |
#' | |
#' @return boolean ; TRUE if successful, FALSE otherwise | |
#' @export | |
#' | |
#' @examples | |
require_package_version_github <- function(packageName, githubLoc, requiredVersion) { | |
library(devtools) | |
installedVersion <- tryCatch(packageVersion(packageName),error = function(e) {NULL}) | |
if (length(installedVersion)==0) { | |
install.packages(packageName) | |
library_result <- tryCatch(library(packageName, character.only = TRUE), error = function(e) {FALSE}) | |
if (identical(library_result, FALSE)) { | |
requireInstall <- TRUE | |
} else { | |
requireInstall <- FALSE # we are going to install right now and drop into a recursive process | |
require_package_version_github(packageName, githubLoc, requiredVersion) | |
} | |
} else if (is.null(installedVersion) | is.na(installedVersion) | evaluate::is.error(installedVersion)) { | |
requireInstall <- TRUE | |
} else { | |
requireInstall <- compareVersion( as.character(installedVersion),requiredVersion) == -1 | |
} | |
if (requireInstall) { | |
tryCatch(install_github(githubLoc), error=function(e) {warning(paste0("Unable to download from ", githubLoc)); return(FALSE)}) | |
installedVersion <- tryCatch(packageVersion(packageName),error = function(e) {warning(paste0("Unable to load ", packageName));return(FALSE)}) | |
#make sure the version we got from github meets our requirements | |
if (compareVersion( as.character(installedVersion),requiredVersion) == -1) { | |
warning("Version of ",packageName," on github doesn't meet the ",requiredVersion," requirement or the install failed") | |
return(FALSE) | |
} | |
} | |
packageLoaded <- require(packageName, character.only=TRUE) | |
return(packageLoaded) | |
} | |
NULL |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment