Spacedman
Spacedman

Reputation: 94267

Detecting how an R file is being run

R code can get run in various ways, such as being called via source, loaded from a package, or read in from stdin. I'd like to detect this in order to create files that can work in a multitude of contexts.

Current experimental detector script is here: https://gitlab.com/-/snippets/2268211

Some of the tests are a bit heuristic based on observation and not documentation. For example I'm not sure which of the two tests for running under littler are better:

if(Sys.getenv("R_PACKAGE_NAME") == "littler"){
    message("++ R_PACKAGE_NAME suggests running under littler")
    mode_found <- TRUE
}

if(Sys.getenv("R_INSTALL_PKG") == "littler"){
    message("++ R_INSTALL_PKG suggests running under littler")
    mode_found <- TRUE
}

and the test for being loaded from a package is simply seeing if the current environment is a namespace:

if(isNamespace(environment())){
    message("++ Being loaded by a package")
    mode_found <- TRUE
}

which seems to be true during package load but I suppose could be true in other contexts, for example reading with source with a local argument that is a namespace.

In the end I suspect most of these cases won't matter to my application too much, but it might be useful to someone to have a set - as complete as possible - of detection tests.

So, are the tests in my detector script okay, and how could they be improved?

Upvotes: 2

Views: 32

Answers (0)

Related Questions