Skip to content

Commit

Permalink
Add local_restore_options() function which *actually* restores `opt…
Browse files Browse the repository at this point in the history
…ions()` and envvars, including `NULL` and `""`, to their original state on exit
  • Loading branch information
rossellhayes committed Jul 1, 2021
1 parent a836094 commit 6b32eeb
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions R/exercise.R
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,7 @@ evaluate_exercise <- function(
exercise, envir, evaluate_global_setup = FALSE, data_dir = NULL
) {
# Protect global options and environment vars from permanent modification
withr::local_options(list())
withr::local_envvar(as.list(Sys.getenv()))
local_restore_options()

# adjust exercise version to match the current learnr version
exercise <- upgrade_exercise(
Expand Down Expand Up @@ -439,8 +438,7 @@ get_checker_func <- function(exercise, name, envir) {

render_exercise <- function(exercise, envir) {
# Protect global options and environment vars from modification by student
withr::local_options(list())
withr::local_envvar(as.list(Sys.getenv()))
local_restore_options()

# Make sure exercise (& setup) chunk options and code are prepped for rendering
exercise <- prepare_exercise(exercise)
Expand Down Expand Up @@ -794,6 +792,27 @@ merge_options <- function(preserved_opts, inherited_opts, static_opts = list())
opts[!grepl("^exercise", names(opts))]
}

local_restore_options <- function(.local_envir = parent.frame()) {
options <- options()
withr::defer(restore_options(options), envir = .local_envir)

envvars <- Sys.getenv()
withr::defer(restore_envvars(envvars), envir = .local_envir)
}

restore_options <- function(old) {
current <- options()
nulls <- setdiff(names(current), names(old))
old[nulls] <- list(NULL)
options(old)
}

restore_envvars <- function(old) {
current <- Sys.getenv()
nulls <- setdiff(names(current), names(old))
Sys.unsetenv(nulls)
do.call(Sys.setenv, as.list(old))
}

#' An Exercise Checker for Debugging
#'
Expand Down

0 comments on commit 6b32eeb

Please sign in to comment.