Skip to content

Commit

Permalink
Import on_load() and on_package_load()
Browse files Browse the repository at this point in the history
  • Loading branch information
lionel- committed Jul 31, 2024
1 parent 0242c0a commit 472b894
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 58 deletions.
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,5 @@ export(with_tempfile)
export(with_tiff)
export(with_timezone)
export(with_xfig)
importFrom(rlang,on_load)
importFrom(rlang,on_package_load)
58 changes: 0 additions & 58 deletions R/aaa.R
Original file line number Diff line number Diff line change
@@ -1,59 +1 @@
# From https://github.com/r-lib/rlang/blob/main/R/aaa.R

on_load <- function(expr, env = parent.frame(), ns = topenv(env)) {
expr <- substitute(expr)
force(env)

callback <- function() {
# Evaluate with promise semantics rather than `base::eval()`
do <- NULL
do.call(delayedAssign, list("do", expr, env))
do
}
ns$.__rlang_hook__. <- c(ns$.__rlang_hook__., list(callback))
}

run_on_load <- function(ns = topenv(parent.frame())) {
hook <- ns$.__rlang_hook__.
rm(envir = ns, list = ".__rlang_hook__.")

# FIXME: Transform to `while` loop to allow hooking into on-load
# from an on-load hook?
for (callback in hook) {
callback()
}
}

.onLoad <- function(...) {
run_on_load()
}

the <- new.env()

on_package_load <- function(pkg, expr, env = parent.frame()) {
expr <- substitute(expr)
force(env)

run <- function(...) {
# Evaluate with promise semantics rather than `base::eval()`
do <- NULL
do.call(delayedAssign, list("do", expr, env))
do
}

# Always register hook in case package is later unloaded & reloaded
setHook(packageEvent(pkg, "onLoad"), run)

# For compatibility with R < 4.0 where base isn't locked
is_sealed <- function(pkg) {
identical(pkg, "base") || environmentIsLocked(asNamespace(pkg))
}

# Run right away if package is already loaded but only if its
# namespace is locked. The registering package might be a dependency
# of `package`. In that case, `package` might not be fully populated
# yet (#1225).
if (isNamespaceLoaded(pkg) && is_sealed(pkg)) {
run()
}
}
6 changes: 6 additions & 0 deletions R/with.R
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,13 @@
#' Sys.getenv("WITHR")
#' }
#' Sys.getenv("WITHR")
#'
#' @importFrom rlang on_load on_package_load
"_PACKAGE"

# Enable pkgload to hotpatch `::` in detached namespaces
on_load(`::` <- base::`::`)

.onLoad <- function(...) {
rlang::run_on_load()
}
1 change: 1 addition & 0 deletions man/withr.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 472b894

Please sign in to comment.