R/dependencies-r.R

Defines functions r_package_origin check_r_packages_on_repos merge_r_dependencies detect_r_dependencies

Documented in check_r_packages_on_repos detect_r_dependencies merge_r_dependencies r_package_origin

# Base and recommended packages that ship with R -- never need to be installed
BASE_R_PACKAGES <- c(
  "base", "compiler", "datasets", "grDevices", "graphics", "grid",
  "methods", "parallel", "splines", "stats", "stats4", "tcltk",
  "tools", "utils",
  "boot", "class", "cluster", "codetools", "foreign", "KernSmooth",
  "lattice", "MASS", "Matrix", "mgcv", "nlme", "nnet", "rpart",
  "spatial", "survival"
)

#' Detect R package dependencies from source files
#'
#' Uses `renv::dependencies()` to scan R source files for package
#' references. This catches `library()`, `require()`,
#' `pkg::func()`, `loadNamespace()`, and other patterns.
#'
#' @param appdir Character string. Path to the app directory.
#' @return Character vector of unique package names (sorted), excluding
#'   base and recommended R packages.
#' @keywords internal
detect_r_dependencies <- function(appdir) {
  if (!requireNamespace("renv", quietly = TRUE)) {
    cli::cli_abort(c(
      "The {.pkg renv} package is required to detect R dependencies",
      "i" = "Install with: {.code install.packages('renv')}"
    ))
  }

  deps_df <- tryCatch(
    renv::dependencies(appdir, quiet = TRUE),
    error = function(e) {
      cli::cli_warn(c(
        "Failed to detect R dependencies",
        "x" = "Error: {e$message}",
        "i" = "Falling back to empty dependency list"
      ))
      data.frame(Package = character(0))
    }
  )

  packages <- unique(deps_df$Package)
  packages <- setdiff(packages, BASE_R_PACKAGES)
  sort(packages)
}

#' Merge detected R dependencies with config declarations
#'
#' Combines auto-detected packages with user-declared packages from config.
#' When auto_detect is FALSE, only declared packages are used.
#'
#' @param detected Character vector of detected package names.
#' @param config_deps List from config$dependencies.
#' @return List with `packages` (character vector) and `repos` (list).
#' @keywords internal
merge_r_dependencies <- function(detected, config_deps) {
  repos <- config_deps$r$repos %||% SHINYELECTRON_DEFAULTS$dependencies$r$repos

  declared <- unlist(config_deps$r$packages %||% list())
  extra <- unlist(config_deps$extra_packages %||% list())

  packages <- if (isTRUE(config_deps$auto_detect %||% TRUE)) {
    sort(unique(c(detected, declared, extra)))
  } else {
    sort(unique(c(declared, extra)))
  }

  list(packages = packages, repos = repos)
}

#' Check that an app's R packages are on its repositories
#'
#' The `system`, `auto-download` and `container` strategies install an app's
#' R packages from `dependencies.r.repos` when the app first starts, and the
#' `bundled` strategy installs them from there at build time. A package the
#' repositories lack, such as one installed on the build machine from GitHub
#' or a local folder, stops the export here, before anything is downloaded.
#'
#' Each repository's source index is read without R's filters for the build
#' machine's R version and operating system, since the app's R may differ.
#' A repository that cannot be read is passed over. When a package is on none
#' of the repositories that were read and one could not be read, the check
#' warns and the export goes on, so an offline build still works.
#'
#' @param packages Character vector. The app's R packages, without the local
#'   packages of a bundled build.
#' @param repos Character vector or list. Repository URLs.
#' @param strategy Character. The runtime strategy, for the advice given.
#' @param lib.loc Character vector or `NULL`. Libraries to look in for the
#'   installed copy of a missing package.
#' @return Invisibly, the packages that were not found.
#' @keywords internal
check_r_packages_on_repos <- function(packages, repos, strategy, lib.loc = NULL) {
  packages <- setdiff(unique(packages), BASE_R_PACKAGES)
  if (length(packages) == 0) return(invisible(character(0)))

  available <- character(0)
  unread <- character(0)
  for (repo in unlist(repos)) {
    # R answers an index it cannot read with a warning and no rows, and an
    # empty repository with no rows alone.
    index <- tryCatch(
      utils::available.packages(repos = repo, type = "source", filters = "duplicates"),
      warning = function(w) NULL,
      error = function(e) NULL
    )
    if (is.null(index)) {
      unread <- c(unread, repo)
    } else {
      available <- c(available, rownames(index))
    }
  }

  missing <- setdiff(packages, available)
  if (length(missing) == 0) return(invisible(character(0)))

  n <- length(missing)
  # A package not found on the repositories that were read may be on one that
  # was not, so this is a warning and the export goes on.
  if (length(unread) > 0) {
    cli::cli_warn(c(
      "Could not read the package index of {.url {unread}}.",
      "i" = "The export did not check that {cli::qty(n)}{?this package is/these packages are} on {.field dependencies.r.repos}: {.pkg {missing}}."
    ), class = "shinyelectron_repos_unreachable")
    return(invisible(character(0)))
  }

  origins <- vapply(missing, r_package_origin, character(1), lib.loc = lib.loc)
  bullets <- stats::setNames(
    sprintf("{.pkg {missing[[%1$d]]}}: {origins[[%1$d]]}", seq_len(n)),
    rep("x", n)
  )
  local_fix <- if (identical(strategy, "bundled")) {
    "or list {cli::qty(n)}{?its/their} source{?s} under {.field dependencies.r.local_packages}"
  } else {
    "or build with the {.val bundled} strategy and list {cli::qty(n)}{?its/their} source{?s} under {.field dependencies.r.local_packages}"
  }
  cli::cli_abort(c(
    "{cli::qty(n)}{?A package/Packages} the app uses {?is/are} not on {.field dependencies.r.repos}:",
    bullets,
    "i" = paste0("Add a repository that has {cli::qty(n)}{?it/them} to {.field dependencies.r.repos}, such as an r-universe address, ", local_fix, "."),
    "i" = "If the app runs without {cli::qty(n)}{?it/them}, set {.field dependencies.auto_detect} to {.val false} and list the packages it needs under {.field dependencies.r.packages}."
  ), class = "shinyelectron_r_packages_unavailable")
}

#' Where the installed copy of an R package came from
#'
#' Reads the fields that remotes, pak and R repositories write into an
#' installed package's DESCRIPTION.
#'
#' @param package Character. A package name.
#' @param lib.loc Character vector or `NULL`. Libraries to look in.
#' @return A phrase such as `"installed here from GitHub (user/repo)"`.
#' @keywords internal
r_package_origin <- function(package, lib.loc = NULL) {
  desc <- suppressWarnings(utils::packageDescription(package, lib.loc = lib.loc))
  if (!inherits(desc, "packageDescription")) return("not installed here")

  type <- tolower(desc$RemoteType %||% "")
  hosts <- c(github = "GitHub", gitlab = "GitLab", bitbucket = "Bitbucket")
  if (type %in% names(hosts) && !is.null(desc$RemoteUsername) && !is.null(desc$RemoteRepo)) {
    return(sprintf("installed here from %s (%s/%s)", hosts[[type]],
                   desc$RemoteUsername, desc$RemoteRepo))
  }
  if (type == "local") return("installed here from a local source")
  if (!is.null(desc$RemoteUrl)) return(paste("installed here from", desc$RemoteUrl))
  if (!is.null(desc$Repository)) return(paste("installed here from", desc$Repository))
  "installed here from a local source"
}

Try the shinyelectron package in your browser

Any scripts or data that you put into this service are public.

shinyelectron documentation built on Dec. 3, 2026, 9:07 a.m.