Skip to contents

Extracts the names of the packages/libraries a code file loads. Where code_library_lines() only reports the lines on which imports occur (to check they are grouped), this returns the actual package identifiers so they can be catalogued and searched, or written to a requirements.txt.

Usage

code_library_names(
  code_text,
  lang = c("R", "Python", "SPSS", "SAS", "Stata", "Mplus", "MATLAB")
)

Arguments

code_text

the code text for a single file

lang

the language (R, Python, SPSS, SAS, Stata, Mplus, MATLAB)

Value

a data frame with columns package, source (how the package was referenced: library, require, requireNamespace, p_load, groundhog, namespace, install, or import), and line (the line number). Rows are unique on package + source + line. An empty frame (same columns) when none found.

Details

For R this captures library() / require() / requireNamespace() (bare or quoted argument), pacman's p_load() (which may list several packages at once), groundhog.library(), namespace-qualified calls (pkg::fun / pkg:::fun), and install.packages() / renv::install(). For Python it captures import a, import a as b, import a, b, and from a.b import c (recording the top-level package a). SAS / SPSS / Stata have no package concept, so an empty frame is returned.

The extraction is regex-based (like the rest of the module) so it degrades gracefully on files that will not parse. It can therefore miss dynamically constructed package names, and does not know which version was used — only the names appear in the source.

Where a call takes a variable rather than a package name — install.packages(pkgs), requireNamespace(pkg), library(pkg, character.only = TRUE), lapply(pkgs, library, ...) — the variable is resolved to the names it holds when the file assigns it a literal vector (pkgs <- c("a", "b"), including a for (pkg in pkgs) loop variable), and dropped otherwise. The variable's own name is never reported as a package.

Examples

code_text <- c(
  "library(dplyr)",
  "require('tidyr')",
  "pacman::p_load(ggplot2, readr)",
  "x <- stringr::str_trim(' a ')"
)
code_library_names(code_text, "R")
#>   package    source line
#> 1   dplyr   library    1
#> 2   tidyr   require    2
#> 3 ggplot2    p_load    3
#> 4   readr    p_load    3
#> 5  pacman namespace    3
#> 6 stringr namespace    4