R/safe_read_csv.R

Defines functions safe_read_ops safe_read_csv

Documented in safe_read_csv safe_read_ops

# safe_read_csv.R


#' @include internals.R


#' @rdname safe_read_csv
#' @template safe_read_csv
#' @export
safe_read_csv <- function(x, ...)
{
    if (length(x) > 1L || !is.character(x)) {
        stop("'x' must be a character of length 1.",
             call. = FALSE)
    }
    if (!utils::file_test("-f", x)) {
        stop("'x' points to a file that does not exist.",
             call. = FALSE)
    }
    if (!identical(.file_ext(basename(x)), "csv")) {
        stop("'x' does not point to a CSV (Comma Separated Value) file.",
             call. = FALSE)
    }
    if (!isOpen(con <- file(x, "rb"), rw = "read")) {
        stop("a connection error occured.", call. = FALSE)
    } else {
        close(con)
    }

    tryCatch(
        {
            return(do.call(data.table::fread, safe_read_ops(file = x, ...)))
        },
        error = function(cond) {
            stop(conditionMessage(cond), call. = FALSE)
        },
        warning = function(cond) {
            stop(conditionMessage(cond), call. = FALSE)
        }
    )
}


#' @rdname safe_read_csv
#' @export
safe_read_ops <- function(...)
{
    default_params <- list(
        na.strings   = ",,",
        sep          = "auto",
        sep2         = "auto",
        dec          = ".",
        quote        = "\"",
        nrows        = Inf,
        header       = TRUE,
        verbose      = FALSE,
        integer64    = "character",
        encoding     = "unknown",
        fill         = FALSE,
        showProgress = FALSE,
        data.table   = TRUE,
        logical01    = FALSE
    )

    if (...length()) {
        user_params <- list(...)
        default_params[names(user_params)] <- user_params
    }

    return(default_params)
}
jeanmathieupotvin/cargo documentation built on Oct. 27, 2020, 5:22 p.m.