Tools to manage configuration files in R projects.
Assume you have a configuration file located at ~/.config.R
. It may
look something like:
~/.config.R
user = "user"
password = "pwd"
...
Now the question is, how do you make these settings available to your R
project. cnf
provides the following mechanisms:
register
: Register a configuration file. It adds to a list of configurations.getcnf
: get the value of a config. It is always alist
returned with the values in the config as elements.
cnf::register(config = "~/.config.R")
cnf::getcnf("config")
With getcnf
we get the config for a given name. You can and should give
project specific names to rule out name clashes between them:
cnf::register(
projA = "pathA/config.R",
projB = "pathB/config.R"
)
We now have access to these configs using:
cnf::getcnf("projA")
cnf::getcnf("projB")
Note that we can override configurations using this approach; simply by using the same name twice. A warning is raised, however this may be entirely by intention. Consider that you have projects A and B. A has its own configuration and loads it. B depends on A but needs to reconfigure project A. Think of the number of cores, database credentials, and the like. Using this approach we will inherit the configuration but can override what needs to be overridden.
To make this work the order of registering is important. Thus the
registration goes into the .onLoad
hook of your package. If you do not
have a package: you are doomed, go and write a package!
.onLoad <- function(libname, pkgname) {
cnf::register(
projA = "pathA/config.R",
projB = "pathB/config.R",
maybe = TRUE,
quiet = TRUE,
warn = FALSE
)
}
maybe
allows this call to fail, but will print a message. This is important when we install a package and have no configuration, yet.quiet
suppresses all warnings and messages.warn
turns warnings into messages.
Sometimes configurations are stored as R object within the package. As R code and in version control. We can register them preferably as load hook:
.onLoad <- function(libname, pkgname) {
cnf::register(
cnf = configObject
)
}
In this case configObject
is a list. We can go wild and provide a
fallback/default configuration and allow for override by a file or
environment variable:
.onLoad <- function(libname, pkgname) {
cnf::register(
config = configObject,
config = "~/.config.R",
config = Sys.getenv("CONFIG"),
maybe = TRUE
)
}
Using this pattern, we can override the configuration, or parts of it, by an environment variable or config file. The file path in the environment variable has highest priority.
Happy coding…