Last active
March 5, 2025 17:32
-
-
Save jmbarbone/9ad73e9d8c0918475de5a669d067bcb6 to your computer and use it in GitHub Desktop.
custom wrappers for installing R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pak_install_pkgs <- function( | |
pkg, | |
new_lib = old_lib, | |
old_lib = .libPaths()[1L], | |
upgrade = FALSE, | |
update = TRUE, | |
dependencies = NA, | |
force = FALSE, | |
use_temp = FALSE, | |
pak_lib = NULL | |
) { | |
stopifnot(dir.exists(old_lib)) | |
if (!nzchar(Sys.getenv("GITHUB_PAT"))) { | |
warning("GITHUB_PAT not set") | |
} | |
if (force) { | |
if (any(grepl("?", pkg, fixed = TRUE))) { | |
warning("\"?\" found in `pkg` and `force = TRUE`") | |
} | |
pkg <- paste0(pkg, "?reinstall&nocache") | |
} | |
old_lib <- normalizePath(old_lib, "/", TRUE) | |
new_lib <- normalizePath(new_lib, "/", FALSE) | |
dir.create(new_lib, showWarnings = FALSE, recursive = TRUE) | |
lockfile <- tempfile(pattern = "pak_pkg_", fileext = ".lock") | |
on.exit(if (file.exists(lockfile)) file.remove(lockfile), add = TRUE) | |
temp_lib <- tempfile("pak_library_") | |
dir.create(temp_lib) | |
on.exit(unlink(temp_lib, recursive = TRUE), add = TRUE) | |
if (is.null(pak_lib)) { | |
# {pak} uses some 'remote()' function which tries to find functions inside | |
# of {pak} but doesn't appear to have controls for | |
pak_lib <- find.package("pak", lib.loc = pak_lib) | |
# https://github.com/r-lib/pak/issues/539 | |
system2("ln", shQuote(c("-s", pak_lib, new_lib))) | |
pak_lib <- dirname(pak_lib) | |
} | |
# just needed for R CMD check | |
requireNamespace("pak", lib.loc = pak_lib) | |
pak <- loadNamespace("pak", lib.loc = pak_lib) | |
pak$lockfile_create( | |
pkg = pkg, | |
lockfile = lockfile, | |
lib = old_lib, # Package library to install the packages to | |
upgrade = upgrade, | |
dependencies = dependencies | |
) | |
pak$lockfile_install( | |
lockfile = lockfile, | |
# Library to carry out the installation on | |
lib = if (use_temp) temp_lib else new_lib, | |
update = update | |
) | |
if (use_temp) { | |
unlink(file.path(temp_lib, "_cache"), recursive = TRUE) | |
pkgs <- list.files(temp_lib, full.names = TRUE) | |
pkgs <- pkgs[dir.exists(pkgs)] | |
n <- length(pkgs) | |
if (n) { | |
message( | |
"Moving ", | |
length(pkgs), | |
" package(s) to ", | |
new_lib, | |
paste0("\n", pkgs) | |
) | |
file.copy(pkgs, new_lib, recursive = TRUE) | |
} | |
} | |
message( | |
"Be sure to load in packages with:\n ", | |
sprintf("library({package}, lic.loc = \"%s\")", new_lib) | |
) | |
invisible(new_lib) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment