Debian Codegraph @

R/env.R

raw
1 # env ------------------------------------------------------------------------
2
3 get_envvar <- function(envs, action = "replace") {
4 envs <- as_envvars(envs)
5 Sys.getenv(names(envs), names = TRUE, unset = NA)
6 }
7
8 set_envvar <- function(envs, action = "replace") {
9 envs <- as_envvars(envs)
10
11 stopifnot(is.character(action), length(action) == 1)
12 action <- match.arg(action, c("replace", "prefix", "suffix"))
13
14 if (length(envs) == 0) {
15 return()
16 }
17
18 old <- Sys.getenv(names(envs), names = TRUE, unset = NA)
19 set <- !is.na(envs)
20
21 both_set <- set & !is.na(old)
22 if (any(both_set)) {
23 if (action == "prefix") {
24 envs[both_set] <- paste(envs[both_set], old[both_set])
25 } else if (action == "suffix") {
26 envs[both_set] <- paste(old[both_set], envs[both_set])
27 }
28 }
29
30 if (any(set)) {
31 do.call("Sys.setenv", as.list(envs[set]))
32 }
33 if (any(!set)) {
34 Sys.unsetenv(names(envs)[!set])
35 }
36
37 invisible(old)
38 }
39
40 as_envvars <- function(envs) {
41 if (length(envs) == 0) {
42 return(envs)
43 }
44
45 stopifnot(is.named(envs))
46
47 # if any envs are null make them NA instead
48 envs[vlapply(envs, is.null)] <- NA
49
50 # if there are duplicated entries keep only the last one
51 envs <- envs[!duplicated(names(envs), fromLast = TRUE)]
52
53 envs
54 }
55
56 #' Environment variables
57 #'
58 #' Temporarily change system environment variables.
59 #'
60 #' @template with
61 #' @param new,.new `[named character]`\cr New environment variables
62 #' @param ... Named arguments with new environment variables.
63 #' @param action should new values `"replace"`, `"prefix"` or
64 #' `"suffix"` existing variables with the same name.
65 #' @inheritParams with_collate
66 #' @details if `NA` is used those environment variables will be unset.
67 #' If there are any duplicated variable names only the last one is used.
68 #' @seealso [Sys.setenv()]
69 #' @examples
70 #' with_envvar(new = c("GITHUB_PAT" = "abcdef"), Sys.getenv("GITHUB_PAT"))
71 #'
72 #' # with_envvar unsets variables after usage
73 #' Sys.getenv("TEMP_SECRET")
74 #' with_envvar(new = c("TEMP_SECRET" = "secret"), Sys.getenv("TEMP_SECRET"))
75 #' Sys.getenv("TEMP_SECRET")
76 #' @export
77 with_envvar <- with_(set_envvar, get = get_envvar)
78
79 #' @rdname with_envvar
80 #' @export
81 local_envvar <- local_(set_envvar, get = get_envvar, dots = TRUE)