1
# env ------------------------------------------------------------------------
2

3
set_envvar <- function(envs, action = "replace") {
4 0
  if (length(envs) == 0) return()
5

6 1
  stopifnot(is.named(envs))
7 1
  stopifnot(is.character(action), length(action) == 1)
8 1
  action <- match.arg(action, c("replace", "prefix", "suffix"))
9

10
  # if there are duplicated entries keep only the last one
11 1
  envs <- envs[!duplicated(names(envs), fromLast = TRUE)]
12

13 1
  old <- Sys.getenv(names(envs), names = TRUE, unset = NA)
14 1
  set <- !is.na(envs)
15

16 1
  both_set <- set & !is.na(old)
17 1
  if (any(both_set)) {
18 1
    if (action == "prefix") {
19 1
      envs[both_set] <- paste(envs[both_set], old[both_set])
20 1
    } else if (action == "suffix") {
21 1
      envs[both_set] <- paste(old[both_set], envs[both_set])
22
    }
23
  }
24

25 1
  if (any(set))  do.call("Sys.setenv", as.list(envs[set]))
26 1
  if (any(!set)) Sys.unsetenv(names(envs)[!set])
27

28 1
  invisible(old)
29
}
30

31
#' Environment variables
32
#'
33
#' Temporarily change system environment variables.
34
#'
35
#' @template with
36
#' @param new,.new `[named character]`\cr New environment variables
37
#' @param ... Named arguments with new environment variables.
38
#' @param action should new values `"replace"`, `"prefix"` or
39
#'   `"suffix"` existing variables with the same name.
40
#' @inheritParams with_collate
41
#' @details if `NA` is used those environment variables will be unset.
42
#' If there are any duplicated variable names only the last one is used.
43
#' @seealso [Sys.setenv()]
44
#' @examples
45
#' with_envvar(new = c("GITHUB_PAT" = "abcdef"), Sys.getenv("GITHUB_PAT"))
46
#'
47
#' # with_envvar unsets variables after usage
48
#' Sys.getenv("TEMP_SECRET")
49
#' with_envvar(new = c("TEMP_SECRET" = "secret"), Sys.getenv("TEMP_SECRET"))
50
#' Sys.getenv("TEMP_SECRET")
51
#' @export
52
with_envvar <- with_(set_envvar)
53

54
#' @rdname with_envvar
55
#' @export
56
local_envvar <- local_(set_envvar, dots = TRUE)

Read our documentation on viewing source code .

Loading