简体   繁体   中英

How can I automatically load and attach imported functions on project open in package dev?

When I'm opening a R package project on my computer, I'd like to automatically load and attach library() all the packages which are listed in the respective NAMESPACE of the given package as import() s (not importFrom() s).

This is helpful, because it allows me to more quickly interactively evaluate code. Otherwise, I waste time with dealing, with, say,

glue("foo")
# Error in glue("foo") : could not find function "glue"

even though I have glue in my NAMESPACE .

Not a huge thing, bit shaves off some seconds and quite a bit of frustration.

Please notice that this only applies in the context of package development. In non-package projects, I can just place library() into my .Rprofile , but this would be redundant in the case of packages, where said packages are already declared in NAMESPACE .

My approach would be to add the following to the .Rprofile at my project (and package) root:

if (Sys.getenv()["LOGNAME"] %in% c("foo_user", "bar_user")) {
  message("I seem to be running on a dev machine, so I am doing some preparatory steps.")
  imports <- devtools::parse_ns_file()$imports  # capture all imports from namespace file
  imports <- purrr::discard(.x = imports, .p = is.list)  # only take the import(), not the importFrom() declarations.
  purrr::walk(.x = imports, .f = library, character.only = TRUE)
}

Does this seem like an ok way to go about it?


Update (already included in the above)

It seems that some CI systems (Appveyor) don't like devtools::... ) and other calls in .Rprofile , perhaps because they don't have this and other packages available at whatever stage in the build cycle .Rprofile is called (pretty early?). So it might seem wise to wrap the whole shebang in an if clause to call it only on the local dev machines.

On macOS, Sys.getenv()["LOGNAME"] gives the short user name, so I'm using that to identify my dev machine.

Let me know if anyone has better ideas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM