Skip to contents

Check if arg is a path to an existing file or directory.

Usage

check_file_exists(arg, signal = "error", msg = NULL, call. = FALSE)

check_dir_exists(arg, signal = "error", msg = NULL, call. = FALSE)

Arguments

arg

(string)
A file system path.

signal

(string: c("error", "warning", "message"))
Must be one of "error", "warning", or "message". "error" (default) calls base::stop() to signal an error message. "warning" calls base::warning() to signal a warning message. "message" calls base::message() to signal a message.

msg

(string or NULL: NULL)
A string that replaces the default message. Set as NULL to use the default message.

call.

(Scalar logical: c(FALSE, TRUE))
Passed to stop() or warning(). The default msg includes it's own formatted call, hence call. should be FALSE (default). If you insert your own msg, then you may want call. = TRUE.

Value

invisible(arg) or condition determined by argument signal.

Details

check_file_exists() requires arg to point to an existing file. An existing directory fails, matching the split base R draws between base::file.exists(), which is TRUE for both files and directories, and base::dir.exists(), which is TRUE for directories only. check_dir_exists() requires arg to point to an existing directory.

A missing value (NA) fails, since it names no path. A vector of length other than one fails, since each check validates a single path.

Examples

#----------------------------------------------------------------------------
# check path existence examples
#----------------------------------------------------------------------------
library(bkcheck)

f_file <- function(x) {
  x |>
    check_file_exists()
}

f_dir <- function(x) {
  x |>
    check_dir_exists()
}

#----------------------------------------------------------------------------
# check_file_exists()
#----------------------------------------------------------------------------
file <- tempfile()
invisible(file.create(file))

f_file(x = file)

try(f_file(x = tempfile()))
#> Error : Argument `x` must be a path to an existing file.
#> 
#> `x` = '/tmp/Rtmpd23ZX7/file55ba37dc1bc0'
#> Reason: no file exists at this path.
#> 
#> Call: f_file(x = tempfile())
try(f_file(tempdir()))
#> Error : Argument `x` must be a path to an existing file.
#> 
#> `x` = '/tmp/Rtmpd23ZX7'
#> Reason: this path is a directory, not a file.
#> 
#> Call: f_file(x = tempdir())

#----------------------------------------------------------------------------
# check_dir_exists()
#----------------------------------------------------------------------------
f_dir(x = tempdir())

try(f_dir(x = tempfile()))
#> Error : Argument `x` must be a path to an existing directory.
#> 
#> `x` = '/tmp/Rtmpd23ZX7/file55ba76c929f'
#> Reason: no directory exists at this path.
#> 
#> Call: f_dir(x = tempfile())