Skip to content

Instantly share code, notes, and snippets.

@geotheory
Last active March 2, 2022 02:06
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 geotheory/43cc6e33f1b61b0eb8084a84e84c67f1 to your computer and use it in GitHub Desktop.
Save geotheory/43cc6e33f1b61b0eb8084a84e84c67f1 to your computer and use it in GitHub Desktop.
# Function to report all explicit R dependencies in current directory (recursive)
# This ignores dependencies of dependencies, but output can be piped to tools::package_dependencies()
report_dependencies = function(path = './', print = FALSE, simple = TRUE){
files = list.files(path = path, pattern = '.R$', recursive = TRUE, full.names = TRUE)
scripts = lapply(files, readLines, warn = FALSE) |> unlist() |> paste(collapse = '\n')
loaded = scripts |> stringr::str_extract_all('(?<=(library|require)\\()[a-zA-Z0-9_.]+') |> unlist() |>
stringr::str_remove_all('["\']') |> stringr::str_remove(',.*') |> unique() |> sort()
invoked = scripts |> stringr::str_extract_all('[a-zA-Z0-9_.]+(?=::)') |> unlist() |> unique() |> sort()
dependencies = loaded |> c(invoked) |> unique() |> sort()
if(print) { message('Dependencies:\n', paste(dependencies, collapse=', ')); return() }
if(simple) return(dependencies)
return(list(all_dependencies = dependencies, pre_loaded = loaded, invoked_in_line = invoked))
}
# Example usage
report_dependencies()
#> Loading required package: stringr
#> [1] "reprex" "stringr"
# to report all potential dependencies (inc. dependencies of dependencies)
report_dependencies() |> tools::package_dependencies(reverse = FALSE) |> unlist() |> unique()
#> [1] "callr" "cli" "clipr" "fs" "glue"
#> [6] "knitr" "rlang" "rmarkdown" "rstudioapi" "utils"
#> [11] "withr" "magrittr" "stringi"
report_dependencies(print = TRUE)
#> Dependencies:
#> reprex, stringr
#> NULL
report_dependencies(simple = FALSE)
#> $all_dependencies
#> [1] "reprex" "stringr"
#>
#> $pre_loaded
#> [1] "stringr"
#>
#> $invoked_in_line
#> [1] "reprex"
report_dependencies('~/Documents/github', print = TRUE)
#> Dependencies:
#> anytime, base, beepr, broom, clue, countrycode, curl, devtools, digest, dplyr, EBImage, fields, forcats, ggplot2, ggplot2movies, ggthemes, glue, grDevices, grid, gridExtra, gtrendsR, here, hms, httr, janitor, jsonlite, knitr, lubridate, magick, magrittr, mxnet, openssl, patchwork, plotly, plyr, purrr, Rcpp, readr, readxl, rmarkdown, RSelenium, rtweet, rvest, rworldmap, safer, scales, shiny, shinyjs, shinythemes, sodium, stats, stringDataFrame, stringi, stringr, testthat, tfse, tibble, tidyr, tidyverse, tools, urltools, utils, vdiffr, viridis, wdman, webshot, withr, xml2, zoo
#> NULL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment