pkgconfig
pkgconfig copied to clipboard
Feature request: `set_config()` invisibly returns prior values like `options()`
options()
invisibly returns its prior value. This can be helpful for use in a single test or function, with lines like:
op <- options(scipen = 1000)
on.exit(options(op), add = TRUE)
set_config()
could benefit from being able to use a similar workflow. The most obvious case would be in unit testing, where this could aid cleanup. It could also be useful when one function requires a different configuration than the rest of the package.
In my own package, I use the following code to achieve this:
set_config <- function (...) {
input <- list(...)
if (is.null(names(input))) {input <- unlist(input, recursive = FALSE)}
if (is.null(names(input)) || any(names(input) == "")) {
stop("Some parameters are not named")
}
values <- lapply(names(input), pkgconfig::get_config)
names(values) <- names(input)
do.call(pkgconfig::set_config_in, c(input, .in = parent.frame()))
return(invisible(values))
}
x <- set_config("foo" = "bar")
on.exit(set_config(x), add = TRUE)
It's certainly not the most elegant, but it seems to get the job done.