| 1 |
#' Attach or load packages, and automatically install missing packages if |
| 2 |
#' requested |
| 3 |
#' |
| 4 |
#' `pkg_attach()` is a vectorized version of [library()] over |
| 5 |
#' the `package` argument to attach multiple packages in a single function |
| 6 |
#' call. `pkg_load()` is a vectorized version of |
| 7 |
#' [requireNamespace()] to load packages (without attaching them). |
| 8 |
#' The functions `pkg_attach2()` and `pkg_load2()` are wrappers of |
| 9 |
#' `pkg_attach(install = TRUE)` and `pkg_load(install = TRUE)`, |
| 10 |
#' respectively. `loadable()` is an abbreviation of |
| 11 |
#' `requireNamespace(quietly = TRUE)`. `pkg_available()` tests if a |
| 12 |
#' package with a minimal version is available. |
| 13 |
#' |
| 14 |
#' These are convenience functions that aim to solve these common problems: (1) |
| 15 |
#' We often need to attach or load multiple packages, and it is tedious to type |
| 16 |
#' several `library()` calls; (2) We are likely to want to install the |
| 17 |
#' packages when attaching/loading them but they have not been installed. |
| 18 |
#' @param ... Package names (character vectors, and must always be quoted). |
| 19 |
#' @param install Whether to automatically install packages that are not |
| 20 |
#' available using [install.packages()]. Besides `TRUE` and |
| 21 |
#' `FALSE`, the value of this argument can also be a function to install |
| 22 |
#' packages (`install = TRUE` is equivalent to `install = |
| 23 |
#' install.packages`), or a character string `"pak"` (equivalent to |
| 24 |
#' `install = pak::pkg_install`, which requires the \pkg{pak} package). |
| 25 |
#' You are recommended to set a CRAN mirror in the global option `repos` |
| 26 |
#' via [options()] if you want to automatically install packages. |
| 27 |
#' @param message Whether to show the package startup messages (if any startup |
| 28 |
#' messages are provided in a package). |
| 29 |
#' @return `pkg_attach()` returns `NULL` invisibly. `pkg_load()` |
| 30 |
#' returns a logical vector, indicating whether the packages can be loaded. |
| 31 |
#' @seealso `pkg_attach2()` is similar to `pacman::p_load()`, but does |
| 32 |
#' not allow non-standard evaluation (NSE) of the `...` argument, i.e., |
| 33 |
#' you must pass a real character vector of package names to it, and all names |
| 34 |
#' must be quoted. Allowing NSE adds too much complexity with too little gain |
| 35 |
#' (the only gain is that it saves your effort in typing two quotes). |
| 36 |
#' @import utils |
| 37 |
#' @export |
| 38 |
#' @examples library(xfun) |
| 39 |
#' pkg_attach('stats', 'graphics') |
| 40 |
#' # pkg_attach2('servr') # automatically install servr if it is not installed |
| 41 |
#' |
| 42 |
#' (pkg_load('stats', 'graphics')) |
| 43 |
pkg_attach = function( |
| 44 |
..., install = FALSE, message = getOption('xfun.pkg_attach.message', TRUE) |
| 45 |
) { |
| 46 |
if (!message) library = function(...) { |
| 47 |
suppressPackageStartupMessages(base::library(...)) |
| 48 |
} |
| 49 |
for (i in c(...)) { |
| 50 |
if (!identical(install, FALSE) && !loadable(i)) pkg_install(i, install) |
| 51 |
library(i, character.only = TRUE) |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
#' @param error Whether to signal an error when certain packages cannot be loaded. |
| 56 |
#' @rdname pkg_attach |
| 57 |
#' @export |
| 58 |
pkg_load = function(..., error = TRUE, install = FALSE) { |
| 59 |
n = length(pkg <- c(...)); res = logical(n) |
| 60 |
if (n == 0) return(invisible(res)) |
| 61 |
for (i in seq_len(n)) { |
| 62 |
res[i] = loadable(p <- pkg[i]) |
| 63 |
if (!identical(install, FALSE) && !res[i]) { |
| 64 |
pkg_install(p, install); res[i] = loadable(p) |
| 65 |
} |
| 66 |
} |
| 67 |
if (error && any(!res)) stop('Package(s) not loadable: ', paste(pkg[!res], collapse = ' ')) |
| 68 |
invisible(res) |
| 69 |
} |
| 70 |
|
| 71 |
#' @param pkg A single package name. |
| 72 |
#' @param strict If `TRUE`, use [requireNamespace()] to test if |
| 73 |
#' a package is loadable; otherwise only check if the package is in |
| 74 |
#' [`.packages`]`(TRUE)` (this does not really load the package, so it |
| 75 |
#' is less rigorous but on the other hand, it can keep the current R session |
| 76 |
#' clean). |
| 77 |
#' @param new_session Whether to test if a package is loadable in a new R |
| 78 |
#' session. Note that `new_session = TRUE` implies `strict = TRUE`. |
| 79 |
#' @rdname pkg_attach |
| 80 |
#' @export |
| 81 |
loadable = function(pkg, strict = TRUE, new_session = FALSE) { |
| 82 |
if (length(pkg) != 1L) stop("'pkg' must be a character vector of length one") |
| 83 |
if (new_session) { |
| 84 |
Rscript(c('-e', shQuote(sprintf('library("%s")', pkg))), stdout = FALSE, stderr = FALSE) == 0 |
| 85 |
} else { |
| 86 |
if (strict) { |
| 87 |
suppressPackageStartupMessages(requireNamespace(pkg, quietly = TRUE)) |
| 88 |
} else pkg %in% .packages(TRUE) |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
#' @param version A minimal version number. If `NULL`, only test if a |
| 93 |
#' package is available and do not check its version. |
| 94 |
#' @rdname pkg_attach |
| 95 |
#' @export |
| 96 |
pkg_available = function(pkg, version = NULL) { |
| 97 |
loadable(pkg) && (is.null(version) || packageVersion(pkg) >= version) |
| 98 |
} |
| 99 |
|
| 100 |
#' @rdname pkg_attach |
| 101 |
#' @export |
| 102 |
pkg_attach2 = function(...) pkg_attach(..., install = TRUE) |
| 103 |
|
| 104 |
#' @rdname pkg_attach |
| 105 |
#' @export |
| 106 |
pkg_load2 = function(...) pkg_load(..., install = TRUE) |
| 107 |
|
| 108 |
pkg_require = function(pkgs, which = length(sys.calls()) - 1) { |
| 109 |
f = func_name(which) |
| 110 |
for (p in pkgs) if (!loadable(p)) stop2( |
| 111 |
"The '", p, "' package is required by the function '", f, "' but not available.", |
| 112 |
if (is_R_CMD_check()) c( |
| 113 |
" If you are developing an R package, you need to declare the dependency on '", |
| 114 |
p, "' in the DESCRIPTION file (e.g., in 'Imports')." |
| 115 |
) |
| 116 |
) |
| 117 |
} |
| 118 |
|
| 119 |
# update all packages in libraries that are writable by the current user |
| 120 |
pkg_update = function(...) { |
| 121 |
libs = .libPaths() |
| 122 |
libs = libs[file.access(libs, 2) >= 0] |
| 123 |
for (l in libs) update.packages(l, ask = FALSE, checkBuilt = TRUE, ...) |
| 124 |
} |
| 125 |
|
| 126 |
# allow users to specify a custom install.packages() function via the global |
| 127 |
# option xfun.install.packages |
| 128 |
pkg_install = function(pkgs, install = TRUE, ...) { |
| 129 |
if (length(pkgs) == 0) return(invisible()) |
| 130 |
# in case the CRAN repo is not set up |
| 131 |
repos = getOption('repos') |
| 132 |
if (length(repos) == 0 || identical(repos, c(CRAN = '@CRAN@'))) { |
| 133 |
opts = options(repos = c(CRAN = 'https://cloud.r-project.org')) |
| 134 |
on.exit(options(opts), add = TRUE) |
| 135 |
} |
| 136 |
if (length(pkgs) > 1) |
| 137 |
message('Installing ', length(pkgs), ' packages: ', paste(pkgs, collapse = ' ')) |
| 138 |
if (isTRUE(install)) install = getOption( |
| 139 |
'xfun.install.packages', |
| 140 |
if (is.na(Sys.getenv('RENV_PROJECT', NA)) || !loadable('renv')) install.packages else { |
| 141 |
function(pkgs, lib = NULL, ...) getFromNamespace('install', 'renv')(pkgs, library = lib, ...) |
| 142 |
} |
| 143 |
) |
| 144 |
if (identical(install, 'pak')) install = pak::pkg_install |
| 145 |
invisible(retry(install, pkgs, ..., .pause = 0)) |
| 146 |
} |
| 147 |
|
| 148 |
#' Find out broken packages and reinstall them |
| 149 |
#' |
| 150 |
#' If a package is broken (i.e., not [loadable()]), reinstall it. |
| 151 |
#' |
| 152 |
#' Installed R packages could be broken for several reasons. One common reason |
| 153 |
#' is that you have upgraded R to a newer `x.y` version, e.g., from `4.0.5` to |
| 154 |
#' `4.1.0`, in which case you need to reinstall previously installed packages. |
| 155 |
#' @param reinstall Whether to reinstall the broken packages, or only list their |
| 156 |
#' names. |
| 157 |
#' @return A character vector of names of broken package. |
| 158 |
#' @export |
| 159 |
broken_packages = function(reinstall = TRUE) { |
| 160 |
libs = .libPaths() |
| 161 |
pkgs = unlist(lapply(libs, function(lib) { |
| 162 |
p = unlist(lapply(.packages(TRUE, lib), function(p) { |
| 163 |
if (!loadable(p, new_session = TRUE)) p |
| 164 |
})) |
| 165 |
if (length(p) && reinstall) { |
| 166 |
remove.packages(p, lib); pkg_install(p, lib = lib) |
| 167 |
} |
| 168 |
p |
| 169 |
})) |
| 170 |
if(reinstall) invisible(pkgs) else pkgs |
| 171 |
} |
| 172 |
|
| 173 |
#' Install a source package from a directory |
| 174 |
#' |
| 175 |
#' Run \command{R CMD build} to build a tarball from a source directory, and run |
| 176 |
#' \command{R CMD INSTALL} to install it. |
| 177 |
#' @param pkg The package source directory. |
| 178 |
#' @param build Whether to build a tarball from the source directory. If |
| 179 |
#' `FALSE`, run \command{R CMD INSTALL} on the directory directly (note |
| 180 |
#' that vignettes will not be automatically built). |
| 181 |
#' @param build_opts The options for \command{R CMD build}. |
| 182 |
#' @param install_opts The options for \command{R CMD INSTALL}. |
| 183 |
#' @export |
| 184 |
#' @return Invisible status from \command{R CMD INSTALL}. |
| 185 |
install_dir = function(pkg = '.', build = TRUE, build_opts = NULL, install_opts = NULL) { |
| 186 |
if (build) { |
| 187 |
pkg = pkg_build(pkg, build_opts) |
| 188 |
on.exit(unlink(pkg), add = TRUE) |
| 189 |
} |
| 190 |
res = Rcmd(c('INSTALL', install_opts, pkg)) |
| 191 |
if (res != 0) stop('Failed to install the package ', pkg) |
| 192 |
invisible(res) |
| 193 |
} |
| 194 |
|
| 195 |
pkg_build = function(dir = '.', opts = NULL) { |
| 196 |
desc = file.path(dir, 'DESCRIPTION') |
| 197 |
pv = read.dcf(desc, fields = c('Package', 'Version')) |
| 198 |
# delete existing tarballs |
| 199 |
unlink(sprintf('%s_*.tar.gz', pv[1, 1])) |
| 200 |
Rcmd(c('build', opts, shQuote(dir))) |
| 201 |
pkg = sprintf('%s_%s.tar.gz', pv[1, 1], pv[1, 2]) |
| 202 |
if (!file_exists(pkg)) stop('Failed to build the package ', pkg) |
| 203 |
pkg |
| 204 |
} |
| 205 |
|
| 206 |
# install dependencies given a package DESCRIPTION |
| 207 |
install_deps = function(dir = '.') { |
| 208 |
d = read.dcf(file.path(dir, 'DESCRIPTION')) |
| 209 |
d = d[1, intersect(colnames(d), c('Depends', 'Imports', 'Suggests', 'LinkingTo'))] |
| 210 |
d = unlist(strsplit(d, ',\\s*'), use.names = FALSE) |
| 211 |
d = gsub('\\(.*\\)', '', d) |
| 212 |
d = gsub('^\\s+|\\s+$', '', d) |
| 213 |
d = setdiff(d, c('R', base_pkgs())) |
| 214 |
if (length(d)) { |
| 215 |
db = available.packages() |
| 216 |
d2 = NULL |
| 217 |
for (p in intersect(d, rownames(db))) d2 = c(d2, tryCatch( |
| 218 |
if (packageVersion(p) < db[p, 'Version']) p, |
| 219 |
error = function(e) p |
| 220 |
)) |
| 221 |
pkg_install(d2) |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
#' An alias of `remotes::install_github()` |
| 226 |
#' |
| 227 |
#' This alias is to make autocomplete faster via `xfun::install_github`, because |
| 228 |
#' most `remotes::install_*` functions are never what I want. I only use |
| 229 |
#' `install_github` and it is inconvenient to autocomplete it, e.g. |
| 230 |
#' `install_git` always comes before `install_github`, but I never use it. In |
| 231 |
#' RStudio, I only need to type `xfun::ig` to get `xfun::install_github`. |
| 232 |
#' @param ... Arguments to be passed to [remotes::install_github()]. |
| 233 |
#' @export |
| 234 |
install_github = function(...) remotes::install_github(...) |
| 235 |
|
| 236 |
# Remove packages not installed from CRAN |
| 237 |
reinstall_from_cran = function(dry_run = TRUE, skip_github = TRUE) { |
| 238 |
r = paste(c('Repository', if (skip_github) 'GithubRepo'), collapse = '|') |
| 239 |
r = paste0('^(', r, '): ') |
| 240 |
for (lib in .libPaths()) { |
| 241 |
pkgs = .packages(TRUE, lib) |
| 242 |
pkgs = setdiff(pkgs, c('xfun', 'rstudio', base_pkgs())) |
| 243 |
for (p in pkgs) { |
| 244 |
desc = read_utf8(system.file('DESCRIPTION', package = p, lib.loc = lib)) |
| 245 |
if (!any(grepl(r, desc))) { |
| 246 |
if (dry_run) message(p, ': ', lib) else install.packages(p, lib = lib) |
| 247 |
} |
| 248 |
} |
| 249 |
} |
| 250 |
} |
| 251 |
|
| 252 |
#' Convert package news to the Markdown format |
| 253 |
#' |
| 254 |
#' Read the package news with [news()], convert the result to |
| 255 |
#' Markdown, and write to an output file (e.g., \file{NEWS.md}). Each package |
| 256 |
#' version appears in a first-level header, each category (e.g., \samp{NEW |
| 257 |
#' FEATURES} or \samp{BUG FIXES}) is in a second-level header, and the news |
| 258 |
#' items are written into bullet lists. |
| 259 |
#' @param package,... Arguments to be passed to [news()]. |
| 260 |
#' @param output The output file path. |
| 261 |
#' @param category Whether to keep the category names. |
| 262 |
#' @return If `output = NA`, returns the Markdown content as a character |
| 263 |
#' vector, otherwise the content is written to the output file. |
| 264 |
#' @export |
| 265 |
#' @examplesIf interactive() |
| 266 |
#' # news for the current version of R |
| 267 |
#' xfun::news2md('R', Version == getRversion(), output = NA) |
| 268 |
news2md = function(package, ..., output = 'NEWS.md', category = TRUE) { |
| 269 |
db = news(package = package, ...) |
| 270 |
k = db[, 'Category'] |
| 271 |
db[is.na(k), 'Category'] = '' # replace NA category with '' |
| 272 |
res = unlist(lapply(unique(db[, 'Version']), function(v) { |
| 273 |
d1 = db[db[, 'Version'] == v, ] |
| 274 |
res = unlist(lapply(unique(d1[, 'Category']), function(k) { |
| 275 |
txt = d1[d1[, 'Category'] == k, 'Text'] |
| 276 |
txt = txt[txt != ''] |
| 277 |
if (k == '' && length(txt) == 0) return() |
| 278 |
txt = gsub('\n *', ' ', txt) |
| 279 |
c(if (category && k != '') paste('##', k), if (length(txt)) paste('-', txt)) |
| 280 |
})) |
| 281 |
if (is.na(dt <- d1[1, 'Date'])) dt = '' else dt = paste0(' (', dt, ')') |
| 282 |
c(sprintf('# CHANGES IN %s VERSION %s%s', package, v, dt), res) |
| 283 |
})) |
| 284 |
res = c(rbind(res, '')) # add a blank line after each line |
| 285 |
if (is.na(output)) raw_string(res) else write_utf8(res, output) |
| 286 |
} |
| 287 |
|
| 288 |
#' Get base R package names |
| 289 |
#' |
| 290 |
#' Return base R package names. |
| 291 |
#' @return A character vector of base R package names. |
| 292 |
#' @export |
| 293 |
#' @examples |
| 294 |
#' xfun::base_pkgs() |
| 295 |
base_pkgs = function() { |
| 296 |
if (is.function(f <- asNamespace('tools')$standard_package_names)) f()[['base']] else c( |
| 297 |
'base', 'compiler', 'datasets', 'graphics', 'grDevices', 'grid', 'methods', |
| 298 |
'parallel', 'splines', 'stats', 'stats4', 'tcltk', 'tools', 'utils' |
| 299 |
) |
| 300 |
} |