R/defaults.R

# Default location of an app, typically used when wrapping an app into a docker image
DEFAULT_APP_DIR <- "/app"

# Default data directory, typically used when wrapping an app into a docker image
DEFAULT_DATA_DIR <- "/fastgenomics"

# summary key for the FGProcess.output
SUMMARY_KEY <- "summary"

#' 1. try the env variable
#' 2. try the data_dir/config/input_file_mapping.json
#' 3. report an error
get_input_file_mapping <- function(data_dir){

    data_dir <- normalizePath(data_dir)
    mapping_file_path <- file.path(data_dir, "config", "input_file_mapping.json")
    mapping_str <- Sys.getenv("INPUT_FILE_MAPPING")

    if (mapping_str != "") {
        mapping <- jsonlite::fromJSON(mapping_str)
    } else {
        message(stringr::str_interp("Environmental variable INPUT_FILE_MAPPING undefined, falling back to an input_file_mapping.json under ${mapping_file_path}"))
        assertthat::is.readable(mapping_file_path)
        mapping <- jsonlite::fromJSON(mapping_file_path)
    }
    mapping <- Map(expand_env_vars, mapping)
    return(mapping)
}

get_data_dir <- function(){
    dir <- Sys.getenv("FG_DATA_ROOT")
    if( dir == "" ){
        message(stringr::str_interp("Environmental variable FG_DATA_ROOT undefined, using the default value of \"${DEFAULT_DATA_DIR}\"."))
        dir <- DEFAULT_DATA_DIR
    }
    return(expand_env_vars(dir))
}

get_app_dir <- function(){
    dir <- Sys.getenv("FG_APP_DIR")
    if( dir == "" ){
        dir <- DEFAULT_APP_DIR
    }
    message(stringr::str_interp("App directory set to \"${dir}\"."))
    return(dir)
}

expand_raise <- function(env){
    val = Sys.getenv(env)
    if(val == ""){
        stop(stringr::str_interp("Variable ${env} referenced in import_file_mapping is undefined."))
    }
    return(val)
}

replace_env <- function(path, env){
    val = expand_raise(substring(env,2))
    return(sub(env, val, path, fixed=TRUE))
}

expand_env_vars <- function(path){
    string_sub = purrr::reduce(
                            .x=stringr::str_extract_all(path, "\\$[a-zA-Z0-9_]+")[[1]],
                            .f=replace_env,
                            .init=path
                        )
    return(string_sub)
}
FASTGenomics/fastgenomicsR documentation built on June 26, 2019, 12:38 p.m.