| 1 |
#' Manipulate filename extensions |
| 2 |
#' |
| 3 |
#' Functions to obtain (`file_ext()`), remove (`sans_ext()`), and |
| 4 |
#' change (`with_ext()`) extensions in filenames. |
| 5 |
#' |
| 6 |
#' `file_ext()` is similar to [tools::file_ext()], and |
| 7 |
#' `sans_ext()` is similar to [tools::file_path_sans_ext()]. |
| 8 |
#' The main differences are that they treat `tar.(gz|bz2|xz)` and |
| 9 |
#' `nb.html` as extensions (but functions in the \pkg{tools} package |
| 10 |
#' doesn't allow double extensions by default), and allow characters `~` |
| 11 |
#' and `#` to be present at the end of a filename. |
| 12 |
#' @param x A character of file paths. |
| 13 |
#' @param extra Extra characters to be allowed in the extensions. By default, |
| 14 |
#' only alphanumeric characters are allowed (and also some special cases in |
| 15 |
#' \sQuote{Details}). If other characters should be allowed, they can be |
| 16 |
#' specified in a character string, e.g., `"-+!_#"`. |
| 17 |
#' @export |
| 18 |
#' @return A character vector of the same length as `x`. |
| 19 |
#' @examples library(xfun) |
| 20 |
#' p = c('abc.doc', 'def123.tex', 'path/to/foo.Rmd', 'backup.ppt~', 'pkg.tar.xz') |
| 21 |
#' file_ext(p); sans_ext(p); with_ext(p, '.txt') |
| 22 |
#' with_ext(p, c('.ppt', '.sty', '.Rnw', 'doc', 'zip')); with_ext(p, 'html') |
| 23 |
#' |
| 24 |
#' # allow for more characters in extensions |
| 25 |
#' p = c('a.c++', 'b.c--', 'c.e##') |
| 26 |
#' file_ext(p) # -/+/# not recognized by default |
| 27 |
#' file_ext(p, extra = '-+#') |
| 28 |
file_ext = function(x, extra = '') { |
| 29 |
ext = character(length(x)) |
| 30 |
i = grep(r <- reg_path(extra), x) |
| 31 |
ext[i] = sub(r, '\\3', x[i]) |
| 32 |
ext |
| 33 |
} |
| 34 |
|
| 35 |
#' @rdname file_ext |
| 36 |
#' @export |
| 37 |
sans_ext = function(x, extra = '') { |
| 38 |
sub(reg_path(extra), '\\1', x) |
| 39 |
} |
| 40 |
|
| 41 |
#' @param ext A vector of new extensions. It must be either of length 1, or the |
| 42 |
#' same length as `x`. |
| 43 |
#' @rdname file_ext |
| 44 |
#' @export |
| 45 |
with_ext = function(x, ext, extra = '') { |
| 46 |
if (anyNA(ext)) stop("NA is not allowed in 'ext'") |
| 47 |
n1 = length(x); n2 = length(ext) |
| 48 |
if (n1 * n2 == 0) return(x) |
| 49 |
i = !grepl('^[.]', ext) & ext != '' |
| 50 |
ext[i] = paste0('.', ext[i]) |
| 51 |
|
| 52 |
if (all(ext == '')) ext = '' |
| 53 |
r = sub('[$]$', '?$', reg_ext(extra)) # make extensions in 'x' optional |
| 54 |
if (length(ext) == 1) return(sub(r, ext, x)) |
| 55 |
|
| 56 |
if (n1 > 1 && n1 != n2) stop("'ext' must be of the same length as 'x'") |
| 57 |
mapply(sub, r, ext, x, USE.NAMES = FALSE) |
| 58 |
} |
| 59 |
|
| 60 |
# regex to extract base path and extension from a file path |
| 61 |
reg_ext = function(extra = '') { |
| 62 |
sprintf('([.](([%s[:alnum:]]+|tar[.](gz|bz2|xz)|nb[.]html)[~#]?))$', extra) |
| 63 |
} |
| 64 |
reg_path = function(...) paste0('^(.*?)', reg_ext(...)) |
| 65 |
|
| 66 |
#' Normalize paths |
| 67 |
#' |
| 68 |
#' A wrapper function of `normalizePath()` with different defaults. |
| 69 |
#' @param x,winslash,must_work Arguments passed to |
| 70 |
#' [normalizePath()]. |
| 71 |
#' @param resolve_symlink Whether to resolve symbolic links. |
| 72 |
#' @export |
| 73 |
#' @examples library(xfun) |
| 74 |
#' normalize_path('~') |
| 75 |
normalize_path = function(x, winslash = '/', must_work = FALSE, resolve_symlink = TRUE) { |
| 76 |
if (!resolve_symlink) { |
| 77 |
# apply the trick on all files on Windows since Sys.readlink() doesn't work |
| 78 |
# and we can't know which files are symlinks |
| 79 |
i = if (is_windows()) file_test('-f', x) else is_symlink(x) |
| 80 |
b = basename(x[i]) |
| 81 |
x[i] = dirname(x[i]) # normalize the dirs of symlinks instead |
| 82 |
} |
| 83 |
res = normalizePath(x, winslash = winslash, mustWork = must_work) |
| 84 |
if (is_windows()) res[is.na(x)] = NA |
| 85 |
if (!resolve_symlink) { |
| 86 |
res[i] = file.path(res[i], b, fsep = winslash) |
| 87 |
} |
| 88 |
res |
| 89 |
} |
| 90 |
|
| 91 |
is_symlink = function(x) { |
| 92 |
!is.na(y <- Sys.readlink(x)) & (y != '') |
| 93 |
} |
| 94 |
|
| 95 |
#' Test if two paths are the same after they are normalized |
| 96 |
#' |
| 97 |
#' Compare two paths after normalizing them with the same separator (`/`). |
| 98 |
#' @param p1,p2 Two vectors of paths. |
| 99 |
#' @param ... Arguments to be passed to [normalize_path()]. |
| 100 |
#' @export |
| 101 |
#' @examples library(xfun) |
| 102 |
#' same_path('~/foo', file.path(Sys.getenv('HOME'), 'foo')) |
| 103 |
same_path = function(p1, p2, ...) { |
| 104 |
normalize_path(p1, ...) == normalize_path(p2, ...) |
| 105 |
} |
| 106 |
|
| 107 |
#' Find file paths that exist |
| 108 |
#' |
| 109 |
#' This is a shorthand of `x[file.exists(x)]`, and optionally returns the |
| 110 |
#' first existing file path. |
| 111 |
#' @param x A vector of file paths. |
| 112 |
#' @param first Whether to return the first existing path. If `TRUE` and no |
| 113 |
#' specified files exist, it will signal an error unless the argument |
| 114 |
#' `error = FALSE`. |
| 115 |
#' @param error Whether to throw an error when `first = TRUE` but no files |
| 116 |
#' exist. It can also take a character value, which will be used as the error |
| 117 |
#' message. |
| 118 |
#' @return A vector of existing file paths. |
| 119 |
#' @export |
| 120 |
#' @examples |
| 121 |
#' xfun::existing_files(c('foo.txt', system.file('DESCRIPTION', package='xfun'))) |
| 122 |
existing_files = function(x, first = FALSE, error = TRUE) { |
| 123 |
x = x[file_exists(x)] |
| 124 |
if (!first) return(x) |
| 125 |
x = head(x, 1) |
| 126 |
if (length(x) != 1 && !identical(error, FALSE)) { |
| 127 |
if (isTRUE(error)) error = 'None of the specified files exist.' |
| 128 |
stop(error, call. = FALSE) |
| 129 |
} |
| 130 |
x |
| 131 |
} |
| 132 |
|
| 133 |
#' Return the (possible) root directory of a project |
| 134 |
#' |
| 135 |
#' Given a path of a file (or dir) in a potential project (e.g., an R package or |
| 136 |
#' an RStudio project), return the path to the project root directory. |
| 137 |
#' |
| 138 |
#' The search for the root directory is performed by a series of tests, |
| 139 |
#' currently including looking for a \file{DESCRIPTION} file that contains |
| 140 |
#' `Package: *` (which usually indicates an R package), and a |
| 141 |
#' \file{*.Rproj} file that contains `Version: *` (which usually indicates |
| 142 |
#' an RStudio project). If files with the expected patterns are not found in the |
| 143 |
#' initial directory, the search will be performed recursively in upper-level |
| 144 |
#' directories. |
| 145 |
#' @param path The initial path to start the search. If it is a file path, its |
| 146 |
#' parent directory will be used. |
| 147 |
#' @param rules A matrix of character strings of two columns: the first column |
| 148 |
#' contains regular expressions to look for filenames that match the patterns, |
| 149 |
#' and the second column contains regular expressions to match the content of |
| 150 |
#' the matched files. The regular expression can be an empty string, meaning |
| 151 |
#' that it will match anything. |
| 152 |
#' @return Path to the root directory if found, otherwise `NULL`. |
| 153 |
#' @export |
| 154 |
#' @note This function was inspired by the \pkg{rprojroot} package, but is much |
| 155 |
#' less sophisticated. It is a rather simple function designed to be used in |
| 156 |
#' some of packages that I maintain, and may not meet the need of general |
| 157 |
#' users until this note is removed in the future (which should be unlikely). |
| 158 |
#' If you are sure that you are working on the types of projects mentioned in |
| 159 |
#' the \sQuote{Details} section, this function may be helpful to you, |
| 160 |
#' otherwise please consider using \pkg{rprojroot} instead. |
| 161 |
proj_root = function(path = './', rules = root_rules) { |
| 162 |
path = normalize_path(path) |
| 163 |
dir = if (dir_exists(path)) path else dirname(path) |
| 164 |
if (same_path(dir, file.path(dir, '..'))) return() |
| 165 |
if (is.null(dim(rules))) dim(rules) = c(1, length(rules)) |
| 166 |
for (i in seq_len(nrow(rules))) { |
| 167 |
file = rules[i, 1]; pattern = rules[i, 2] |
| 168 |
for (f in list.files(dir, file, full.names = TRUE)) { |
| 169 |
if (pattern == '' || length(grep(pattern, read_utf8(f)))) return(dir) |
| 170 |
} |
| 171 |
} |
| 172 |
proj_root(dirname(dir), rules) |
| 173 |
} |
| 174 |
|
| 175 |
#' @rdname proj_root |
| 176 |
#' @export |
| 177 |
root_rules = matrix(c( |
| 178 |
'^DESCRIPTION$', '^Package: ', |
| 179 |
'.+[.]Rproj$', '^Version: ' |
| 180 |
), ncol = 2, byrow = TRUE, dimnames = list(NULL, c('file', 'pattern'))) |
| 181 |
|
| 182 |
#' Get the relative path of a path relative to a directory |
| 183 |
#' |
| 184 |
#' Given a directory, return the relative path that is relative to this |
| 185 |
#' directory. For example, the path \file{foo/bar.txt} relative to the directory |
| 186 |
#' \file{foo/} is \file{bar.txt}, and the path \file{/a/b/c.txt} relative to |
| 187 |
#' \file{/d/e/} is \file{../../a/b/c.txt}. |
| 188 |
#' @param dir Path to a directory. |
| 189 |
#' @param x A vector of paths to be converted to relative paths. |
| 190 |
#' @param use.. Whether to use double-dots (\file{..}) in the relative path. A |
| 191 |
#' double-dot indicates the parent directory (starting from the directory |
| 192 |
#' provided by the `dir` argument). |
| 193 |
#' @param error Whether to signal an error if a path cannot be converted to a |
| 194 |
#' relative path. |
| 195 |
#' @return A vector of relative paths if the conversion succeeded; otherwise the |
| 196 |
#' original paths when `error = FALSE`, and an error when `error = |
| 197 |
#' TRUE`. |
| 198 |
#' @export |
| 199 |
#' @examples |
| 200 |
#' xfun::relative_path('foo/bar.txt', 'foo/') |
| 201 |
#' xfun::relative_path('foo/bar/a.txt', 'foo/haha/') |
| 202 |
#' xfun::relative_path(getwd()) |
| 203 |
relative_path = function(x, dir = '.', use.. = TRUE, error = TRUE) { |
| 204 |
res = x |
| 205 |
for (i in seq_along(x)) res[i] = relative_path_one(x[i], dir, use.., error) |
| 206 |
res |
| 207 |
} |
| 208 |
|
| 209 |
relative_path_one = function(x, dir, use.., error) { |
| 210 |
# on Windows, if a relative path doesn't exist, normalizePath() will use |
| 211 |
# getwd() as its parent dir; however, normalizePath() just returns the |
| 212 |
# relative path on *nix, and we have to assume it's relative to getwd() |
| 213 |
abs_path = function(p) { |
| 214 |
if (!file.exists(p) && is_unix() && is_rel_path(p)) p = file.path(getwd(), p) |
| 215 |
normalize_path(p) |
| 216 |
} |
| 217 |
p = abs_path(x); n1 = nchar(p) |
| 218 |
if ((n1 <- nchar(p)) == 0) return(x) # not sure what you mean |
| 219 |
d = abs_path(dir); n2 = nchar(d) |
| 220 |
if (is_sub_path(p, d, n2)) { |
| 221 |
p2 = get_subpath(p, n1, n2) |
| 222 |
if (p2 == '') p2 = '.' # if the subpath is empty, it means the current dir |
| 223 |
return(p2) |
| 224 |
} |
| 225 |
if (!use..) { |
| 226 |
if (error) stop("When use.. = FALSE, the path 'x' must be under the 'dir'") |
| 227 |
return(x) |
| 228 |
} |
| 229 |
s = '../'; d1 = d |
| 230 |
while (!is_sub_path(p, d2 <- dirname(d1))) { |
| 231 |
if (same_path(d1, d2)) { |
| 232 |
if (error) stop( |
| 233 |
"The path 'x' cannot be converted to a relative path to 'dir'. ", |
| 234 |
"Perhaps they are on different volumes of the disk." |
| 235 |
) |
| 236 |
return(x) |
| 237 |
} |
| 238 |
s = paste0('../', s) |
| 239 |
d1 = d2 # go to one level up |
| 240 |
} |
| 241 |
paste0(s, get_subpath(p, n1, nchar(d2))) |
| 242 |
} |
| 243 |
|
| 244 |
#' Test if a path is a subpath of a dir |
| 245 |
#' |
| 246 |
#' Check if the path starts with the dir path. |
| 247 |
#' @inheritParams is_abs_path |
| 248 |
#' @param dir A vector of directory paths. |
| 249 |
#' @param n The length of `dir` paths. |
| 250 |
#' @return A logical vector. |
| 251 |
#' @note You may want to normalize the values of the `x` and `dir` arguments |
| 252 |
#' first (with [xfun::normalize_path()]), to make sure the path separators |
| 253 |
#' are consistent. |
| 254 |
#' @export |
| 255 |
#' @examples |
| 256 |
#' xfun::is_sub_path('a/b/c.txt', 'a/b') # TRUE |
| 257 |
#' xfun::is_sub_path('a/b/c.txt', 'd/b') # FALSE |
| 258 |
#' xfun::is_sub_path('a/b/c.txt', 'a\\b') # FALSE (even on Windows) |
| 259 |
is_sub_path = function(x, dir, n = nchar(dir)) substr(x, 1, n) == dir |
| 260 |
|
| 261 |
# remove the first n2 characters and the possible / from the path |
| 262 |
get_subpath = function(p, n1, n2) { |
| 263 |
p = substr(p, n2 + 1, n1) |
| 264 |
sub('^/', '', p) |
| 265 |
} |
| 266 |
|
| 267 |
#' Test if paths are relative or absolute |
| 268 |
#' |
| 269 |
#' On Unix, check if the paths start with \file{/} or \file{~} (if they do, they |
| 270 |
#' are absolute paths). On Windows, check if a path remains the same (via |
| 271 |
#' [xfun::same_path()]) if it is prepended with \file{./} (if it does, it is a |
| 272 |
#' relative path). |
| 273 |
#' @param x A vector of paths. |
| 274 |
#' @return A logical vector. |
| 275 |
#' @export |
| 276 |
#' @examples |
| 277 |
#' xfun::is_abs_path(c('C:/foo', 'foo.txt', '/Users/john/', tempdir())) |
| 278 |
#' xfun::is_rel_path(c('C:/foo', 'foo.txt', '/Users/john/', tempdir())) |
| 279 |
is_abs_path = function(x) { |
| 280 |
if (is_unix()) grepl('^[/~]', x) else !same_path(x, file.path('.', x)) |
| 281 |
} |
| 282 |
|
| 283 |
#' @rdname is_abs_path |
| 284 |
#' @export |
| 285 |
is_rel_path = function(x) !is_abs_path(x) |
| 286 |
|
| 287 |
#' Test if a path is a web path |
| 288 |
#' |
| 289 |
#' Check if a path starts with \file{http://} or \file{https://} or |
| 290 |
#' \file{ftp://} or \file{ftps://}. |
| 291 |
#' @inheritParams is_abs_path |
| 292 |
#' @return A logical vector. |
| 293 |
#' @export |
| 294 |
#' @examples |
| 295 |
#' xfun::is_web_path('https://www.r-project.org') # TRUE |
| 296 |
#' xfun::is_web_path('www.r-project.org') # FALSE |
| 297 |
is_web_path = function(x) { |
| 298 |
grepl('^(f|ht)tps?://', x) |
| 299 |
} |
| 300 |
|
| 301 |
#' Get the relative path of a path in a project relative to the current working |
| 302 |
#' directory |
| 303 |
#' |
| 304 |
#' First compose an absolute path using the project root directory and the |
| 305 |
#' relative path components, i.e., [`file.path`]`(root, ...)`. Then |
| 306 |
#' convert it to a relative path with [relative_path()], which is |
| 307 |
#' relative to the current working directory. |
| 308 |
#' |
| 309 |
#' This function was inspired by `here::here()`, and the major difference |
| 310 |
#' is that it returns a relative path by default, which is more portable. |
| 311 |
#' @param ... A character vector of path components *relative to the root |
| 312 |
#' directory of the project*. |
| 313 |
#' @param root The root directory of the project. |
| 314 |
#' @param error Whether to signal an error if the path cannot be converted to a |
| 315 |
#' relative path. |
| 316 |
#' @return A relative path, or an error when the project root directory cannot |
| 317 |
#' be determined or the conversion failed and `error = TRUE`. |
| 318 |
#' @export |
| 319 |
#' @examples |
| 320 |
#' \dontrun{ |
| 321 |
#' xfun::from_root('data', 'mtcars.csv') |
| 322 |
#' } |
| 323 |
from_root = function(..., root = proj_root(), error = TRUE) { |
| 324 |
if (is.null(root)) stop('Cannot determine the root directory of the current project.') |
| 325 |
p = file.path(root, ..., fsep = '/') |
| 326 |
relative_path(p, error = error) |
| 327 |
} |
| 328 |
|
| 329 |
#' Find a file or directory under a root directory |
| 330 |
#' |
| 331 |
#' Given a path, try to find it recursively under a root directory. The input |
| 332 |
#' path can be an incomplete path, e.g., it can be a base filename, and |
| 333 |
#' `magic_path()` will try to find this file under subdirectories. |
| 334 |
#' @param ... A character vector of path components. |
| 335 |
#' @param root The root directory under which to search for the path. If |
| 336 |
#' `NULL`, the current working directory is used. |
| 337 |
#' @param relative Whether to return a relative path. |
| 338 |
#' @param error Whether to signal an error if the path is not found, or multiple |
| 339 |
#' paths are found. |
| 340 |
#' @param message Whether to emit a message when multiple paths are found and |
| 341 |
#' `error = FALSE`. |
| 342 |
#' @param n_dirs The number of subdirectories to recursively search. The |
| 343 |
#' recursive search may be time-consuming when there are a large number of |
| 344 |
#' subdirectories under the root directory. If you really want to search for |
| 345 |
#' all subdirectories, you may try `n_dirs = Inf`. |
| 346 |
#' @return The path found under the root directory, or an error when `error |
| 347 |
#' = TRUE` and the path is not found (or multiple paths are found). |
| 348 |
#' @export |
| 349 |
#' @examples |
| 350 |
#' \dontrun{ |
| 351 |
#' xfun::magic_path('mtcars.csv') # find any file that has the base name mtcars.csv |
| 352 |
#' } |
| 353 |
magic_path = function( |
| 354 |
..., root = proj_root(), relative = TRUE, error = TRUE, |
| 355 |
message = getOption('xfun.magic_path.message', TRUE), |
| 356 |
n_dirs = getOption('xfun.magic_path.n_dirs', 10000) |
| 357 |
) { |
| 358 |
if (file.exists(p <- file.path(...))) return(p) |
| 359 |
if (is.null(root)) root = getwd() |
| 360 |
nd = 0 |
| 361 |
# find a path 'f' recursively under a directory 'd' |
| 362 |
find_it = function(f, d) { |
| 363 |
if (nd > n_dirs) { |
| 364 |
if (error) stop( |
| 365 |
'Failed to find the path under ', n_dirs, ' subdirectories. If you want ', |
| 366 |
'to search for the path in more subdirectories, increase the value of ', |
| 367 |
"the 'n_dirs' argument of magic_path()." |
| 368 |
) |
| 369 |
return(p) |
| 370 |
} |
| 371 |
ds = list.files(d, full.names = TRUE) |
| 372 |
ds = ds[dir_exists(ds)] |
| 373 |
if ((n1 <- length(ds)) == 0) return() |
| 374 |
nd <<- nd + n1 |
| 375 |
fs = file.path(ds, f) |
| 376 |
fs = fs[file.exists(fs)] |
| 377 |
if ((n2 <- length(fs)) == 1) return(fs) |
| 378 |
if (n2 > 1) { |
| 379 |
msg = c( |
| 380 |
'Found more than one path containing the input path "', f, '":\n\n', |
| 381 |
paste('*', fs, collapse = '\n') |
| 382 |
) |
| 383 |
if (error) stop(msg) |
| 384 |
if (message) base::message(msg, '\n\nReturned the first one.') |
| 385 |
return(fs[1]) |
| 386 |
} |
| 387 |
# look into subdirectories one by one |
| 388 |
for (i in seq_len(n1)) { |
| 389 |
fs = find_it(f, file.path(ds[i])) |
| 390 |
if (length(fs)) return(fs) |
| 391 |
} |
| 392 |
} |
| 393 |
f = find_it(p, root) |
| 394 |
if (is.null(f)) { |
| 395 |
if (error) stop('Could not find the path "', p, '" in any subdirectories.') |
| 396 |
p |
| 397 |
} else { |
| 398 |
if (relative) relative_path(f, error = error) else f |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
#' Test the existence of files and directories |
| 403 |
#' |
| 404 |
#' These are wrapper functions of [`utils::file_test()]` to test the |
| 405 |
#' existence of directories and files. Note that `file_exists()` only tests |
| 406 |
#' files but not directories, which is the main difference between |
| 407 |
#' [file.exists()] in base R. If you use are using the R version |
| 408 |
#' 3.2.0 or above, `dir_exists()` is the same as [dir.exists()] |
| 409 |
#' in base R. |
| 410 |
#' @param x A vector of paths. |
| 411 |
#' @export |
| 412 |
#' @return A logical vector. |
| 413 |
dir_exists = function(x) file_test('-d', x) |
| 414 |
|
| 415 |
#' @rdname dir_exists |
| 416 |
#' @export |
| 417 |
file_exists = function(x) file_test('-f', x) |
| 418 |
|
| 419 |
#' Create a directory recursively by default |
| 420 |
#' |
| 421 |
#' First check if a directory exists. If it does, return `TRUE`, otherwise |
| 422 |
#' create it with [`dir.create`]`(recursive = TRUE)` by default. |
| 423 |
#' @param x A path name. |
| 424 |
#' @param recursive Whether to create all directory components in the path. |
| 425 |
#' @param ... Other arguments to be passed to [dir.create()]. |
| 426 |
#' @return A logical value indicating if the directory either exists or is |
| 427 |
#' successfully created. |
| 428 |
#' @export |
| 429 |
dir_create = function(x, recursive = TRUE, ...) { |
| 430 |
dir_exists(x) || dir.create(x, recursive = recursive, ...) |
| 431 |
} |
| 432 |
|
| 433 |
#' Rename files with a sequential numeric prefix |
| 434 |
#' |
| 435 |
#' Rename a series of files and add an incremental numeric prefix to the |
| 436 |
#' filenames. For example, files \file{a.txt}, \file{b.txt}, and \file{c.txt} |
| 437 |
#' can be renamed to \file{1-a.txt}, \file{2-b.txt}, and \file{3-c.txt}. |
| 438 |
#' @param pattern A regular expression for [list.files()] to obtain |
| 439 |
#' the files to be renamed. For example, to rename `.jpeg` files, use |
| 440 |
#' `pattern = "[.]jpeg$"`. |
| 441 |
#' @param format The format for the numeric prefix. This is passed to |
| 442 |
#' [sprintf()]. The default format is `"\%0Nd"` where `N |
| 443 |
#' = floor(log10(n)) + 1` and `n` is the number of files, which means the |
| 444 |
#' prefix may be padded with zeros. For example, if there are 150 files to be |
| 445 |
#' renamed, the format will be `"\%03d"` and the prefixes will be |
| 446 |
#' `001`, `002`, ..., `150`. |
| 447 |
#' @param replace Whether to remove existing numeric prefixes in filenames. |
| 448 |
#' @param start The starting number for the prefix (it can start from 0). |
| 449 |
#' @param dry_run Whether to not really rename files. To be safe, the default is |
| 450 |
#' `TRUE`. If you have looked at the new filenames and are sure the new |
| 451 |
#' names are what you want, you may rerun `rename_seq()` with |
| 452 |
#' `dry_run = FALSE` to actually rename files. |
| 453 |
#' @return A named character vector. The names are original filenames, and the |
| 454 |
#' vector itself is the new filenames. |
| 455 |
#' @export |
| 456 |
#' @examples xfun::rename_seq() |
| 457 |
#' xfun::rename_seq('[.](jpeg|png)$', format = '%04d') |
| 458 |
rename_seq = function( |
| 459 |
pattern = '^[0-9]+-.+[.]Rmd$', format = 'auto', replace = TRUE, start = 1, |
| 460 |
dry_run = TRUE |
| 461 |
) { |
| 462 |
n = length(files <- list.files('.', pattern)) |
| 463 |
if (n == 0) return(files) |
| 464 |
|
| 465 |
files2 = if (replace) sub('^[0-9]+-*', '', files) else files |
| 466 |
if (format == 'auto') format = paste0('%0', floor(log10(n)) + 1, 'd') |
| 467 |
files2 = paste(sprintf(format, seq_len(n) + start - 1), files2, sep = '-') |
| 468 |
|
| 469 |
if (!dry_run) file.rename(files, files2) |
| 470 |
structure(setNames(files2, files), class = 'xfun_rename_seq') |
| 471 |
} |
| 472 |
|
| 473 |
#' @export |
| 474 |
print.xfun_rename_seq = function(x, ...) { |
| 475 |
x = unclass(x) |
| 476 |
tab = data.frame(original = names(x), ' ' = '->', new = unname(x), check.names = FALSE) |
| 477 |
if (loadable('knitr')) tab = knitr::kable(tab, 'simple') |
| 478 |
print(tab) |
| 479 |
} |
| 480 |
|
| 481 |
#' Rename files and directories |
| 482 |
#' |
| 483 |
#' First try [file.rename()]. If it fails (e.g., renaming a file from one volume |
| 484 |
#' to another on disk is likely to fail), try [file.copy()] instead, and clean |
| 485 |
#' up the original files if the copy succeeds. |
| 486 |
#' @param from,to Original and target paths, respectively. |
| 487 |
#' @return A logical vector (`TRUE` for success and `FALSE` for failure). |
| 488 |
#' @export |
| 489 |
file_rename = function(from, to) { |
| 490 |
for (d in dirname(to)) dir_create(d) # make sure target directories exist |
| 491 |
|
| 492 |
res = suppressWarnings(file.rename(from, to)) |
| 493 |
|
| 494 |
for (i in which(!res)) { |
| 495 |
f1 = from[i]; f2 = to[i] |
| 496 |
if (dir_exists(f1)) { |
| 497 |
if (res[i] <- dir_create(f2) && all(file.copy( |
| 498 |
list.files(f1, full.names = TRUE, all.files = TRUE), f2, recursive = TRUE |
| 499 |
))) unlink(f1, recursive = TRUE) |
| 500 |
} else { |
| 501 |
if (res[i] <- file.copy(f1, f2, overwrite = TRUE)) file.remove(f1) |
| 502 |
} |
| 503 |
} |
| 504 |
res |
| 505 |
} |
| 506 |
|
| 507 |
# return path to R's svg logo if it exists, otherwise return the jpg logo; or |
| 508 |
# specify a regex to match the logo path, e.g., ext = 'jpg$' |
| 509 |
R_logo = function(ext = NULL, all = FALSE) { |
| 510 |
x = file.path(R.home('doc'), 'html', c('Rlogo.svg', 'logo.jpg')) |
| 511 |
if (!is.null(ext)) x = grep(ext, x, value = TRUE) |
| 512 |
existing_files(x, first = !all) |
| 513 |
} |
| 514 |
|
| 515 |
#' Extract filenames from a URLs |
| 516 |
#' |
| 517 |
#' Get the base names of URLs via [basename()], and remove the |
| 518 |
#' possible query parameters or hash from the names. |
| 519 |
#' @param x A character vector of URLs. |
| 520 |
#' @param default The default filename when it cannot be determined from the |
| 521 |
#' URL, e.g., when the URL ends with a slash. |
| 522 |
#' @return A character vector of filenames at the end of URLs. |
| 523 |
#' @export |
| 524 |
#' @examples |
| 525 |
#' xfun::url_filename('https://yihui.org/images/logo.png') |
| 526 |
#' xfun::url_filename('https://yihui.org/index.html') |
| 527 |
#' xfun::url_filename('https://yihui.org/index.html?foo=bar') |
| 528 |
#' xfun::url_filename('https://yihui.org/index.html#about') |
| 529 |
#' xfun::url_filename('https://yihui.org') |
| 530 |
#' xfun::url_filename('https://yihui.org/') |
| 531 |
url_filename = function(x, default = 'index.html') { |
| 532 |
# protocol shouldn't be treated as dir name, and query/hash should be removed |
| 533 |
x = gsub('^https?://|[?#].*$', '', x) |
| 534 |
f = basename(x) |
| 535 |
ifelse(grepl('/$', x) | x == f, default, f) |
| 536 |
} |
| 537 |
|
| 538 |
#' Delete an empty directory |
| 539 |
#' |
| 540 |
#' Use `list.file()` to check if there are any files or subdirectories |
| 541 |
#' under a directory. If not, delete this empty directory. |
| 542 |
#' @param dir Path to a directory. If `NULL` or the directory does not |
| 543 |
#' exist, no action will be performed. |
| 544 |
#' @export |
| 545 |
del_empty_dir = function(dir) { |
| 546 |
if (is.null(dir) || !dir_exists(dir)) return() |
| 547 |
files = list.files(dir, all.files = TRUE, no.. = TRUE) |
| 548 |
if (length(files) == 0) unlink(dir, recursive = TRUE) |
| 549 |
} |
| 550 |
|
| 551 |
#' Mark some paths as directories |
| 552 |
#' |
| 553 |
#' Add a trailing backlash to a file path if this is a directory. This is useful |
| 554 |
#' in messages to the console for example to quickly identify directories from |
| 555 |
#' files. |
| 556 |
#' |
| 557 |
#' If `x` is a vector of relative paths, directory test is done with path |
| 558 |
#' relative to the current working dir. Use [xfun::in_dir()] or use absolute |
| 559 |
#' paths. |
| 560 |
#' |
| 561 |
#' @param x Character vector of paths to files and directories. |
| 562 |
#' @examples |
| 563 |
#' mark_dirs(list.files(find.package("xfun"), full.names = TRUE)) |
| 564 |
#' @export |
| 565 |
mark_dirs = function(x) { |
| 566 |
i = dir_exists(x) & !grepl("/$", x) |
| 567 |
x[i] = paste0(x[i], "/") |
| 568 |
x |
| 569 |
} |
| 570 |
|
| 571 |
# change list.files()'s default argument values |
| 572 |
all_files = function( |
| 573 |
pattern = NULL, dir = '.', ignore.case = TRUE, full.names = TRUE, |
| 574 |
recursive = TRUE, ... |
| 575 |
) { |
| 576 |
list.files( |
| 577 |
dir, pattern, ignore.case = ignore.case, full.names = full.names, |
| 578 |
recursive = recursive, no.. = TRUE, ... |
| 579 |
) |
| 580 |
} |