| 1 |
#' Functions to test for file types |
| 2 |
#' |
| 3 |
#' @return A named logical vector, where the names give the paths. If the given |
| 4 |
#' object does not exist, `NA` is returned. |
| 5 |
#' @seealso [file_exists()], [dir_exists()] and [link_exists()] if you want |
| 6 |
#' to ensure that the path also exists. |
| 7 |
#' @template fs |
| 8 |
#' @importFrom stats setNames |
| 9 |
#' @inheritParams file_info |
| 10 |
#' @export |
| 11 |
#' @examples |
| 12 |
#' \dontshow{.old_wd <- setwd(tempdir())} |
| 13 |
#' dir_create("d") |
| 14 |
#' |
| 15 |
#' file_create("d/file.txt") |
| 16 |
#' dir_create("d/dir") |
| 17 |
#' link_create(path(path_abs("d"), "file.txt"), "d/link") |
| 18 |
#' |
| 19 |
#' paths <- dir_ls("d") |
| 20 |
#' is_file(paths) |
| 21 |
#' is_dir(paths) |
| 22 |
#' is_link(paths) |
| 23 |
#' |
| 24 |
#' # Cleanup |
| 25 |
#' dir_delete("d") |
| 26 |
#' \dontshow{setwd(.old_wd)} |
| 27 |
is_file <- function(path, follow = TRUE) { |
| 28 |
res <- file_info(path, follow = follow) |
| 29 |
setNames(!is.na(res$type) & res$type == "file", path) |
| 30 |
} |
| 31 |
|
| 32 |
#' @rdname is_file |
| 33 |
#' @export |
| 34 |
is_dir <- function(path, follow = TRUE) { |
| 35 |
res <- file_info(path, follow = follow) |
| 36 |
setNames(!is.na(res$type) & res$type == "directory", path) |
| 37 |
} |
| 38 |
|
| 39 |
#' @rdname is_file |
| 40 |
#' @export |
| 41 |
is_link <- function(path) { |
| 42 |
res <- file_info(path) |
| 43 |
setNames(!is.na(res$type) & res$type == "symlink", path) |
| 44 |
} |
| 45 |
|
| 46 |
#' @rdname is_file |
| 47 |
#' @export |
| 48 |
is_file_empty <- function(path, follow = TRUE) { |
| 49 |
res <- file_info(path, follow = follow) |
| 50 |
|
| 51 |
setNames(!is.na(res$size) & res$size == 0, res$path) |
| 52 |
} |
| 53 |
|
| 54 |
#' Test if a path is an absolute path |
| 55 |
#' |
| 56 |
#' @template fs |
| 57 |
#' @export |
| 58 |
#' @examples |
| 59 |
#' is_absolute_path("/foo") |
| 60 |
#' is_absolute_path("C:\\foo") |
| 61 |
#' is_absolute_path("\\\\myserver\\foo\\bar") |
| 62 |
#' |
| 63 |
#' is_absolute_path("foo/bar") |
| 64 |
is_absolute_path <- function(path) { |
| 65 |
tidy_path <- path_tidy(path) |
| 66 |
grepl("^~", path) | grepl("^(/+|[A-Za-z]:)", tidy_path) |
| 67 |
} |
| 68 |
|
| 69 |
#' Check if a directory is empty |
| 70 |
#' |
| 71 |
#' This function checks whether a given directory is empty or not. |
| 72 |
#' |
| 73 |
#' @param path A character string specifying the path to the directory to check. |
| 74 |
#' |
| 75 |
#' @return A logical value. Returns \code{TRUE} if the directory is empty, |
| 76 |
#' \code{FALSE} otherwise. |
| 77 |
#' |
| 78 |
#' @examples |
| 79 |
#' \dontrun{ |
| 80 |
#' is_dir_empty("path/to/empty/directory") # Returns TRUE |
| 81 |
#' is_dir_empty("path/to/non-empty/directory") # Returns FALSE |
| 82 |
#' } |
| 83 |
#' |
| 84 |
#' @export |
| 85 |
is_dir_empty <- function(path) { |
| 86 |
length(dir_ls(path)) == 0 |
| 87 |
} |