R/environment.R

### ----------------------------------------------------------------- ###
### ENVIRONMENT VARIABLES ----
### ----------------------------------------------------------------- ###

#' Get notes folder path
#' 
#' Reading environment variables either specified in the \code{.Renviron} file, or
#' directly from the environment variables set via \code{\link{set_notes_folder}}.
#' 
#' @importFrom tools file_path_as_absolute
#' @return a character vector contains path and folder.name.
#' @export
get_notes_folder_path <- function() { #nocov start
  folder.name <- sn_folder_name()
  folder.path <- sn_folder_path()
  abs.path <- tools::file_path_as_absolute(folder.path)
  full <- file.path(abs.path, folder.name)
  full
} #nocov end

#' Set notes folder environment variables
#'
#' @param folder.path absolute or relative path for the location notes folder. Default
#'   value is the current working directory.
#' @param folder.name name of the folder. Default value is \code{notes}.
#' @examples \dontrun{
#' ## Set folder path in home directory:
#' set_notes_folder_path(Sys.getenv("HOME"), "shiny-notes")
#' ## Use a temporary directory for folder path:
#' set_notes_folder_path(folder.path = tempdir())
#' }
#' @export
set_notes_folder_path <- function(folder.path = NULL, folder.name = NULL) { #nocov start
  if (is.null(folder.path)) {
    folder.path <- sn_folder_path()
  }
  if (is.null(folder.name)) {
    folder.name <- sn_folder_name()
  }
  ## type checking:
  x <- list(folder.path, folder.name)
  cond <- vapply(x, function(i) is.character(i) && length(i) == 1L, logical(1))
  if (!all(cond)) {
    ## display only the first cond error at a time:
    stop(
      paste(
        sprintf("\"%s\" not valid.", unlist(x[!cond])[1L]), 
        "Provide only character type in the arguments with length one.",
        sep = "\n"
      )
    )
  }
  ## recode vars:
  vars <- list(
    SHINYNOTES.NOTES.FOLDER.PATH = folder.path,
    SHINYNOTES.NOTES.FOLDER.NAME = folder.name
  )
  do.call(Sys.setenv, vars)
} #nocov end

sn_folder_path <- function() { #nocov start
  path <- read_renvr("SHINYNOTES.NOTES.FOLDER.PATH")
  if (is.null(path)) {
    path <- "."
  }
  path
} #nocov end

sn_folder_name <- function() { #nocov start
  name <- read_renvr("SHINYNOTES.NOTES.FOLDER.NAME")
  if (is.null(name)) {
    name <- "notes"
  }
  name
} #nocov end

read_renvr <- function(var) { #nocov start
  pat <- Sys.getenv(var)
  if (identical(pat, "")) {
    pat <- NULL
  }
  pat
} #nocov end
strboul/shinyNotes documentation built on June 2, 2019, 10:56 p.m.