Debian Codegraph @

R/path.R

raw
1 #' Path computations
2 #'
3 #' All functions apart from `path_real()` are purely path computations, so the
4 #' files in question do not need to exist on the filesystem.
5 #' @template fs
6 #' @name path_math
7 #' @return The new path(s) in an `fs_path` object, which is a character vector
8 #' that also has class `fs_path`. Except `path_split()`, which returns a list
9 #' of character vectors of path components.
10 #' @seealso [path_expand()] for expansion of user's home directory.
11 #' @examples
12 #' \dontshow{.old_wd <- setwd(tempdir())}
13 #' dir_create("a")
14 #' file_create("a/b")
15 #' link_create(path_abs("a"), "c")
16 #'
17 #' # Realize the path
18 #' path_real("c/b")
19 #'
20 #' # Split a path
21 #' parts <- path_split("a/b")
22 #' parts
23 #'
24 #' # Join it together
25 #' path_join(parts)
26 #'
27 #' # Find the absolute path
28 #' path_abs("..")
29 #'
30 #' # Normalize a path
31 #' path_norm("a/../b\\c/.")
32 #'
33 #' # Compute a relative path
34 #' path_rel("/foo/abc", "/foo/bar/baz")
35 #'
36 #' # Find the common path between multiple paths
37 #' path_common(c("/foo/bar/baz", "/foo/bar/abc", "/foo/xyz/123"))
38 #'
39 #' # Cleanup
40 #' dir_delete("a")
41 #' link_delete("c")
42 #' \dontshow{setwd(.old_wd)}
43 NULL
44
45 #' Construct path to a file or directory
46 #'
47 #' `path()` constructs a relative path, `path_wd()` constructs an absolute path
48 #' from the current working directory.
49 #'
50 #' @param ... character vectors, if any values are NA, the result will also be
51 #' NA. The paths follow the recycling rules used in the tibble package,
52 #' namely that only length 1 arguments are recycled.
53 #' @param ext An optional extension to append to the generated path.
54 #' @export
55 #' @seealso [path_home()], [path_package()] for functions to construct paths
56 #' relative to the home and package directories respectively.
57 #' @examples
58 #' path("foo", "bar", "baz", ext = "zip")
59 #'
60 #' path("foo", letters[1:3], ext = "txt")
61 path <- function(..., ext = "") {
62 args <- list(...)
63 assert_recyclable(c(args, list(ext)))
64
65 path_tidy(.Call(
66 fs_path_,
67 lapply(args, function(x) enc2utf8(as.character(x))),
68 ext
69 ))
70 }
71
72 assert_recyclable <- function(x) {
73 if (length(x) == 0) {
74 return()
75 }
76 len <- vapply(x, length, integer(1))
77 max_len <- max(len)
78 different <- which(len != 0 & len != max_len)
79 assert(
80 "Arguments must have consistent lengths, only values of length one are recycled.",
81 all(len[different] == 1)
82 )
83 }
84
85 #' @rdname path
86 #' @export
87 path_wd <- function(..., ext = "") {
88 path(getwd(), ..., ext = ext)
89 }
90
91 #' @describeIn path_math returns the canonical path, eliminating any symbolic
92 #' links and the special references `~`, `~user`, `.`, and `..`, , i.e. it
93 #' calls `path_expand()` (literally) and `path_norm()` (effectively).
94 #' @export
95 path_real <- function(path) {
96 path <- enc2utf8(as.character(path))
97 old <- path_expand(path)
98
99 is_missing <- is.na(path)
100 old[!is_missing] <- .Call(fs_realize_, old[!is_missing])
101
102 path_tidy(old)
103 }
104
105 #' Tidy paths
106 #'
107 #' Untidy paths are all different, tidy paths are all the same.
108 #' Tidy paths always use `/` to delimit directories, never have
109 #' multiple `/` or trailing `/` and have colourised output based on the file
110 #' type.
111 #'
112 #' @return An `fs_path` object, which is a character vector that also has class
113 #' `fs_path`
114 #' @template fs
115 #' @export
116 path_tidy <- function(path) {
117 path <- enc2utf8(as.character(path))
118 new_fs_path(.Call(fs_tidy_, path))
119 }
120
121
122 #' @describeIn path_math splits paths into parts.
123 #' @export
124 # TODO: examples
125 path_split <- function(path) {
126 path <- path_tidy(path)
127
128 # Split drive / UNC parts
129 # split keep unc paths together, but keep root paths as first part.
130 # //foo => '//foo' 'bar'
131 # /foo/bar => '/' 'foo' 'bar'
132 strsplit(path, "^(?=/)(?!//)|(?<!^)(?<!^/)/", perl = TRUE)
133 }
134
135 #' @describeIn path_math joins parts together. The inverse of [path_split()].
136 #' See [path()] to concatenate vectorized strings into a path.
137 #' @param parts A character vector or a list of character vectors, corresponding
138 #' to split paths.
139 #' @export
140 path_join <- function(parts) {
141 if (length(parts) == 0) {
142 return(path_tidy(""))
143 }
144 if (!is.list(parts)) {
145 return(path_tidy(.Call(
146 fs_path_,
147 as.list(enc2utf8(as.character(parts))),
148 ""
149 )))
150 }
151 path_tidy(vapply(parts, path_join, character(1)))
152 }
153
154 #' @describeIn path_math returns a normalized, absolute version of a path.
155 #' @export
156 path_abs <- function(path, start = ".") {
157 if (!is_absolute_path(start)) {
158 start <- path_norm(path(getwd(), start))
159 }
160 is_abs <- is_absolute_path(path)
161 path[is_abs] <- path_norm(path[is_abs])
162 path[!is_abs] <- path_norm(path(start, path[!is_abs]))
163 path_tidy(path)
164 }
165
166
167 #' @describeIn path_math eliminates `.` references and rationalizes up-level
168 #' `..` references, so `A/./B` and `A/foo/../B` both become `A/B`, but `../B`
169 #' is not changed. If one of the paths is a symbolic link, this may change the
170 #' meaning of the path, so consider using `path_real()` instead.
171 #' @export
172 path_norm <- function(path) {
173 non_missing <- !is.na(path)
174
175 parts <- path_split(path)
176 path_norm_one <- function(p) {
177 p <- p[p != "."]
178 double_dots <- p == ".."
179 if (any(double_dots)) {
180 res <- character(length(p))
181 size <- 0
182 is_abs <- is_absolute_path(p[[1]])
183 for (i in seq_along(p)) {
184 if (
185 p[[i]] != ".." ||
186 (!is_abs && size == 0) ||
187 (size > 0 && res[[size]] == "..")
188 ) {
189 res[[size <- size + 1]] <- p[[i]]
190 } else if (size > 0) {
191 size <- size - 1
192 }
193 }
194 res <- res[seq(1, size)]
195 if (is_abs && res[[1]] != p[[1]]) {
196 res <- c(p[[1]], res)
197 }
198 p <- res
199 }
200 if (length(p) == 0) {
201 return(path_tidy("."))
202 }
203 path_join(p)
204 }
205 parts[non_missing] <- vapply(parts[non_missing], path_norm_one, character(1))
206 path_tidy(parts)
207 }
208
209 #' @describeIn path_math computes the path relative to the `start` path,
210 #' which can be either an absolute or relative path.
211 #' @export
212 #' @param start A starting directory to compute the path relative to.
213 # This implementation is partially derived from
214 # https://github.com/python/cpython/blob/9c99fd163d5ca9bcc0b7ddd0d1e3b8717a63237c/Lib/posixpath.py#L446
215 path_rel <- function(path, start = ".") {
216 if (length(start) > 1L) {
217 stop(
218 "`start` must be a single path to a starting directory.",
219 call. = FALSE
220 )
221 }
222
223 start <- path_abs(path_expand(start))
224 path <- path_abs(path_expand(path))
225
226 path_rel_one <- function(p) {
227 common <- path_common(c(start, p))
228 starts <- path_split(start)[[1]]
229 paths <- path_split(p)[[1]]
230
231 i <- length(path_split(common)[[1]])
232 double_dot_part <- rep("..", (length(starts) - i))
233 if (i + 1 <= length(paths)) {
234 path_part <- paths[seq(i + 1, length(paths))]
235 } else {
236 path_part <- character()
237 }
238 rels <- c(double_dot_part, path_part)
239 if (length(rels) == 0) {
240 return(path_tidy("."))
241 }
242
243 path_join(rels)
244 }
245 if (is.na(start)) {
246 return(path_tidy(NA_character_))
247 }
248
249 is_missing <- is.na(path)
250
251 path[!is_missing] <- vapply(path[!is_missing], path_rel_one, character(1))
252
253 path_tidy(path)
254 }
255
256 #' Finding the User Home Directory
257 #'
258 #' * `path_expand()` performs tilde expansion on a path, replacing instances of
259 #' `~` or `~user` with the user's home directory.
260 #' * `path_home()` constructs a path within the expanded users home directory,
261 #' calling it with _no_ arguments can be useful to verify what fs considers the
262 #' home directory.
263 #' * `path_expand_r()` and `path_home_r()` are equivalents which always use R's
264 #' definition of the home directory.
265 #' @details
266 #' `path_expand()` differs from [base::path.expand()] in the interpretation of
267 #' the home directory of Windows. In particular `path_expand()` uses the path
268 #' set in the `USERPROFILE` environment variable and, if unset, then uses
269 #' `HOMEDRIVE`/`HOMEPATH`.
270 #'
271 #' In contrast [base::path.expand()] first checks for `R_USER` then `HOME`,
272 #' which in the default configuration of R on Windows are both set to the user's
273 #' document directory, e.g. `C:\\Users\\username\\Documents`.
274 #' [base::path.expand()] also does not support `~otheruser` syntax on Windows,
275 #' whereas `path_expand()` does support this syntax on all systems.
276 #'
277 #' This definition makes fs more consistent with the definition of home
278 #' directory used on Windows in other languages, such as
279 #' [python](https://docs.python.org/3/library/os.path.html#os.path.expanduser)
280 #' and [rust](https://doc.rust-lang.org/std/env/fn.home_dir.html#windows). This
281 #' is also more compatible with external tools such as git and ssh, both of
282 #' which put user-level files in `USERPROFILE` by default. It also allows you to
283 #' write portable paths, such as `~/Desktop` that points to the Desktop location
284 #' on Windows, macOS and (most) Linux systems.
285 #'
286 #' Users can set the `R_FS_HOME` environment variable to override the
287 #' definitions on any platform.
288 #' @seealso [R for Windows FAQ - 2.14](https://cran.r-project.org/bin/windows/base/rw-FAQ.html#What-are-HOME-and-working-directories_003f)
289 #' for behavior of [base::path.expand()].
290 #' @param ... Additional paths appended to the home directory by [path()].
291 #' @inheritParams path_math
292 #' @export
293 #' @examples
294 #' # Expand a path
295 #' path_expand("~/bin")
296 #'
297 #' # You can use `path_home()` without arguments to see what is being used as
298 #' # the home diretory.
299 #' path_home()
300 #' path_home("R")
301 #'
302 #' # This will likely differ from the above on Windows
303 #' path_home_r()
304 path_expand <- function(path) {
305 path <- enc2utf8(path)
306
307 # We use the windows implementation if R_FS_HOME is set or if on windows
308 path_tidy(.Call(
309 fs_expand_,
310 path,
311 Sys.getenv("R_FS_HOME") != "" || is_windows()
312 ))
313 }
314
315 #' @rdname path_expand
316 #' @export
317 path_expand_r <- function(path) {
318 path <- enc2utf8(path)
319
320 # Unconditionally use R_ExpandFileName
321 path_tidy(.Call(fs_expand_, path, FALSE))
322 }
323
324 #' @rdname path_expand
325 #' @export
326 path_home <- function(...) {
327 path(path_expand("~/"), ...)
328 }
329
330 #' @rdname path_expand
331 #' @export
332 path_home_r <- function(...) {
333 path(path_expand_r("~/"), ...)
334 }
335
336 #' Manipulate file paths
337 #'
338 #' * `path_file()` returns the filename portion of the path
339 #' * `path_dir()` returns the directory portion of the path
340 #' * `path_ext()` returns the last extension (if any) for a path
341 #' * `path_ext_remove()` removes the last extension and returns the rest of
342 #' the path
343 #' * `path_ext_set()` replaces the extension with a new extension. If there is
344 #' no existing extension the new extension is appended
345 #'
346 #' Note because these are not full file paths they return regular character
347 #' vectors, not [`fs_path`][fs_path()] objects.
348 #' @template fs
349 #' @param ext,value The new file extension.
350 #' @seealso [base::basename()], [base::dirname()]
351 #' @export
352 #' @examples
353 #' path_file("dir/file.zip")
354 #'
355 #' path_dir("dir/file.zip")
356 #'
357 #' path_ext("dir/file.zip")
358 #'
359 #' path_ext("file.tar.gz")
360 #'
361 #' path_ext_remove("file.tar.gz")
362 #'
363 #' # Only one level of extension is removed
364 #' path_ext_set(path_ext_remove("file.tar.gz"), "zip")
365 #' @export
366 path_file <- function(path) {
367 is_missing <- is.na(path)
368 path[!is_missing] <- call_with_deduplication(basename, path[!is_missing])
369 as.character(path)
370 }
371
372
373 #' @rdname path_file
374 #' @export
375 path_dir <- function(path) {
376 is_missing <- is.na(path)
377 path[!is_missing] <- call_with_deduplication(dirname, path[!is_missing])
378 as.character(path_tidy(path))
379 }
380
381 #' @rdname path_file
382 #' @export
383 path_ext <- function(path) {
384 if (length(path) == 0) {
385 return(character())
386 }
387
388 res <- captures(
389 path_file(path),
390 regexpr("(?<!^|[.]|/)[.]+([^.]+)$", path_file(path), perl = TRUE)
391 )[[1]]
392 res[!is.na(path) & is.na(res)] <- ""
393 res
394 }
395
396 #' @rdname path_file
397 #' @export
398 path_ext_remove <- function(path) {
399 dir <- path_dir(path)
400 file <- sub("(?<!^|[.])\\.+([^.]+)$", "", path_file(path), perl = TRUE)
401
402 na <- is.na(path)
403 no_dir <- dir == "." | dir == ""
404
405 path[!na & no_dir] <- path_tidy(file[!na & no_dir])
406
407 path[!na & !no_dir] <- path(dir[!na & !no_dir], file[!na & !no_dir])
408
409 path
410 }
411
412 #' @rdname path_file
413 #' @export
414 path_ext_set <- function(path, ext) {
415 if (!(length(ext) == length(path) || length(ext) == 1)) {
416 assert_recyclable(list(path, ext))
417 }
418
419 # Remove a leading . if present
420 ext <- sub("^[.]", "", ext)
421
422 has_ext <- nzchar(ext)
423 to_set <- !is.na(path) & has_ext
424
425 if (length(ext) == 1) {
426 ext <- rep(ext, sum(to_set))
427 }
428
429 path[to_set] <- paste0(
430 path_ext_remove(path[to_set]),
431 ".",
432 ext
433 )
434
435 path_tidy(path)
436 }
437
438 #' @rdname path_file
439 #' @export
440 `path_ext<-` <- function(path, value) {
441 path_ext_set(path, value)
442 }
443
444 #' @describeIn path_math finds the common parts of two (or more) paths.
445 #' @export
446 path_common <- function(path) {
447 is_missing <- is.na(path)
448
449 if (any(is_missing)) {
450 return(path_tidy(NA))
451 }
452
453 is_abs <- is_absolute_path(path)
454
455 # We must either have all absolute paths, or all relative paths.
456 if (!(all(is_abs) || all(!is_abs))) {
457 stop(fs_error("Can't mix absolute and relative paths"))
458 }
459
460 path <- path_norm(path)
461 path <- sort(path)
462
463 # remove . entries from the split paths
464 parts <- lapply(path_split(path), function(x) x[x != "."])
465 s1 <- parts[[1]]
466 s2 <- parts[[length(parts)]]
467 common <- s1
468 for (i in seq_along(s1)) {
469 if (s1[[i]] != s2[[i]]) {
470 if (i == 1) {
471 common <- ""
472 } else {
473 common <- s1[seq(1, i - 1)]
474 }
475 break
476 }
477 }
478 path_join(common)
479 }
480
481 #' Filter paths
482 #'
483 #' @template fs
484 #' @param glob A wildcard aka globbing pattern (e.g. `*.csv`) passed on to [grep()] to filter paths.
485 #' @param regexp A regular expression (e.g. `[.]csv$`) passed on to [grep()] to filter paths.
486 #' @param invert If `TRUE` return files which do _not_ match
487 #' @param ... Additional arguments passed to [grep].
488 #' @export
489 #' @examples
490 #' path_filter(c("foo", "boo", "bar"), glob = "*oo")
491 #' path_filter(c("foo", "boo", "bar"), glob = "*oo", invert = TRUE)
492 #'
493 #' path_filter(c("foo", "boo", "bar"), regexp = "b.r")
494 path_filter <- function(path, glob = NULL, regexp = NULL, invert = FALSE, ...) {
495 if (!is.null(glob)) {
496 if (!is.null(regexp)) {
497 stop(fs_error("`glob` and `regexp` cannot both be set."))
498 }
499 regexp <- utils::glob2rx(glob)
500 }
501 if (!is.null(regexp)) {
502 path <- grep(
503 x = path,
504 pattern = regexp,
505 value = TRUE,
506 invert = isTRUE(invert),
507 ...
508 )
509 }
510 setNames(path_tidy(path), path)
511 }
512
513 #' @describeIn path_math determine if a path has a given parent.
514 #' @param parent The parent path.
515 #' @export
516 path_has_parent <- function(path, parent) {
517 path <- path_abs(path)
518 path <- path_expand(path)
519 parent <- path_abs(parent)
520 parent <- path_expand(parent)
521
522 res <- logical(length(path))
523
524 assert_recyclable(list(path, parent))
525 if (length(path) == 1) {
526 path <- rep(path, length(parent))
527 }
528
529 if (length(parent) == 1) {
530 parent <- rep(parent, length(path))
531 }
532
533 for (i in seq_along(path)) {
534 res[[i]] <- identical(
535 as.character(path_common(c(path[[i]], parent[[i]]))),
536 as.character(parent[[i]])
537 )
538 }
539 res
540 }