Skip to content

Instantly share code, notes, and snippets.

@jamiefolson
Created November 9, 2014 21:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiefolson/034d2a91349822f5c3ae to your computer and use it in GitHub Desktop.
Save jamiefolson/034d2a91349822f5c3ae to your computer and use it in GitHub Desktop.
Get (recursive) package dependencies
library(stringr)
package_names_from_description <- function(pkg, imports=TRUE){
# include imports as well as depends
deps <- c("Depends",if(imports)"Imports")
pkg_descr <- packageDescription(pkg,fields=deps)
pkg_list <- unlist(pkg_descr)
pkg_list <- pkg_list[!is.na(pkg_list)]
if (length(pkg_list)==0)return(character(0))
pkg_full_names <- unlist(str_split(as.character(pkg_list),","))
# Strip the version info from the name
pkg_info <- str_match(str_trim(pkg_full_names),
"^([a-zA-Z0-9]+)([[:space:]]+\\(>=[[:space:]]+[0-9.-]*\\))?$")
# Only return the package names
pkg_names <- pkg_info[,2]
pkg_names[!is.na(pkg_names)]
}
#' Get recursive package dependencies
#'
#' Checks the package description and recursively adds identified dependencies until
#' no new dependencies are found.
#'
#' @param pkg character value name(s) of package(s) to search through
#' @param imports whether to include packages under \code{Imports} as dependencies
#' @param recursive whether to include indirect/recursive dependencies as well as immediate dependencies
#' @param exclude character vector containing any package to exclude from the dependencies
#'
package_dependencies <- function(pkg, imports=TRUE, recursive=TRUE,
exclude=c("R",getOption("defaultPackages"))){
all_pkgs <- c(exclude)
pkgs_to_check <- c(pkg)
while(length(pkgs_to_check)){
# Pop the next package off the list
pkg <- pkgs_to_check[1]
pkgs_to_check <- pkgs_to_check[-1]
pkg_deps <- package_names_from_description(pkg,imports=imports)
new_pkgs <- setdiff(pkg_deps, all_pkgs)
all_pkgs <- c(all_pkgs, new_pkgs)
# Push all new dependencies to the list of packages to check
# (if recursive)
if (recursive) pkgs_to_check <- c(pkgs_to_check, new_pkgs)
}
setdiff(all_pkgs,exclude)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment