# Dependencies, read from DESCRIPTION: writes a small DESCRIPTION into a temp # folder, lists its dependencies with their minimum versions, flags two # common mistakes, and shows a guard for a package that is only suggested. # # Rscript dependencies-demo.R # Writes a DESCRIPTION with three dependency fields and returns its folder. write_demo_description <- function(path = tempfile("demopkg")) { dir.create(path, showWarnings = FALSE) d <- desc::desc( text = c( "Package: demopkg", "Title: Demo Package", "Version: 0.1.0", "Description: Shows how a package declares its dependencies.", "License: MIT + file LICENSE" ) ) d$set_dep("R", "Depends", ">= 4.1") d$set_dep("cli", "Imports", ">= 3.6.0") d$set_dep("rlang", "Imports") d$set_dep("testthat", "Suggests", ">= 3.0.0") d$set_dep("knitr", "Suggests") d$write(file = file.path(path, "DESCRIPTION")) path } # One row per dependency: its field, whether default installation needs it # (Depends, Imports, LinkingTo), and the minimum version, if any. dependency_table <- function(path) { deps <- desc::desc_get_deps(path) data.frame( package = deps$package, field = deps$type, required = deps$type %in% c("Depends", "Imports", "LinkingTo"), min_version = ifelse( deps$version == "*", NA_character_, sub("^>=\\s*", "", deps$version) ) ) } # Two rules from Writing R Extensions: a package belongs in only one field, # and Depends is for R itself and (rarely) packages users need attached. dependency_problems <- function(path) { deps <- desc::desc_get_deps(path) counts <- table(deps$package) c( sprintf("%s is listed in more than one field", names(counts)[counts > 1]), sprintf( "%s is in Depends: prefer Imports", setdiff(deps$package[deps$type == "Depends"], "R") ) ) } # The guard for a suggested package: stops with a classed error that says # what the package is needed for. Call it at the top of the function that # uses the package, then call that package's functions with pkg::fun(). check_suggested <- function(pkg, reason, call = rlang::caller_env()) { rlang::check_installed(pkg, reason = reason, call = call) } # An example user: writes a Markdown table with knitr (a suggested package). markdown_table <- function(data) { rlang::check_installed("knitr", reason = "to format the table as Markdown") knitr::kable(data, format = "pipe") } # Run only when called as a script (not when sourced by the tests). if (sys.nframe() == 0L) { path <- write_demo_description() cat(readLines(file.path(path, "DESCRIPTION")), sep = "\n") print(dependency_table(path)) message("A package in two fields, and one in Depends:") desc::desc_set_dep("rlang", "Suggests", file = path) desc::desc_set_dep("dplyr", "Depends", file = path) print(dependency_problems(path)) message("A suggested package that is installed:") print(markdown_table(head(mtcars[, 1:3], 3))) message("A suggested package that is not installed:") tryCatch( check_suggested("notarealpkg", "to run this example"), error = function(e) { cat(conditionMessage(e), "\n") } ) }