File: checkInstalled.R

package info (click to toggle)
r-bioc-biocbaseutils 1.8.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 196 kB
  • sloc: makefile: 2
file content (50 lines) | stat: -rw-r--r-- 1,571 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#' Check packages are installed otherwise suggest
#'
#' `checkInstalled` allows to check if a package is installed. If the package is
#' not available, a convenient copy-and-paste message is provided for package
#' installation with `BiocManager`. The function is typically used within
#' functions that check for package availability from the `Suggests` field.
#'
#' @param pkgs `character()` package names required for a function
#'
#' @return `TRUE` if all packages are installed, otherwise stops with a message
#'   and suggests installation of missing packages
#'
#' @author M. Morgan, M. Ramos
#'
#' @examples
#' if (interactive()) {
#'     checkInstalled(
#'         c("BiocParallel", "SummarizedExperiment")
#'     )
#' }
#' @export
checkInstalled <- function(pkgs) {
    inst <- vapply(pkgs, FUN = function(pkg) {
        !nzchar(system.file(package = pkg))
    }, logical(1L))
    toinst <- pkgs[inst]
    if (length(toinst))
        .install_suggestion(toinst)
    else
        TRUE
}

.install_suggestion <- function(pkgs) {
    n <- length(pkgs)
    txt <- if (identical(n, 1L)) '"%s"' else 'c(\n    "%s"\n  )'
    fmt <- '  BiocManager::install(%s)'
    fmt <- sprintf(fmt, txt)
    pkgs <- paste(strwrap(
        paste(pkgs, collapse='", "'),
        width = getOption("width") - 4L
    ), collapse="\n    ")
    cat(
        "The following package(s) are required for this function:",
        "\n\n", sprintf(fmt, pkgs), "\n\n", sep = ""
    )
    stop(
        "To use this function, install missing package dependencies.",
        call. = FALSE
    )
}