R/write.R

Defines functions write.config

Documented in write.config

#' Write config in a file (JSON/YAML/INI) 
#'
#' @param config.dat a list of config (eg. generated by read.config)
#' @param file.path File path of configuration to write. Defaults to the value of
#' the 'R_CONFIGFILE_ACTIVE' environment variable ('config.cfg' if the
#' variable does not exist)
#' @param write.type json/ini/yaml
#' @param sections Sections that need be write in file, default is NULL and use all of sections
#' @param ... Arguments for \code{\link[ini]{write.ini}}, 
#' \code{\link[jsonlite]{prettify}}, \code{\link[jsonlite]{toJSON}}, 
#' \code{\link[yaml]{as.yaml}} and \code{\link{cat}}
#' encoding if not specifield
#' @seealso
#' \code{\link[jsonlite]{toJSON}} convert a list to JSON string, 
#' \code{\link[jsonlite]{prettify}} convert a JSON string to user friendly view, 
#' \code{\link[ini]{write.ini}} write a list in a INI format file, 
#' \code{\link[yaml]{as.yaml}} convert a list to YAML format
#' @return 
#' Logical indicating whether the specified configuration file be writed successful
#' @export
#' @examples
#' list.test <- list(a=c(123,456))
#' out.yaml <- sprintf('%s/test.yaml', tempdir()) 
#' write.config(list.test, out.yaml, write.type = 'yaml')
write.config <- function(config.dat, file.path = Sys.getenv("R_CONFIGFILE_ACTIVE", 
  "config.cfg"), write.type = "ini", sections = NULL, ...) {
  if (!is.list(config.dat)) {
    warning("config.dat need be a list.")
    return(FALSE)
  }
  if (!is.null(sections)) {
    if (any(!sections %in% c(names(config.dat), 1:length(config.dat)))) {
      stop(sprintf("Section %s were not existed in config.dat!"))
    } else {
      config.dat <- config.dat[sections]
    }
  }
  write.config.list(config.dat = config.dat, file.path = file.path, write.type = write.type, 
    ...)
  if (file.exists(file.path) && file.size(file.path) > 0) {
    return(TRUE)
  } else {
    return(FALSE)
  }
}

Try the configr package in your browser

Any scripts or data that you put into this service are public.

configr documentation built on July 17, 2020, 5:07 p.m.