Debian Codegraph @

R/files.R

raw
1
2 # NOTE: all methods here should either return TRUE if they were able to
3 # operate successfully, or throw an error if not
4 #
5 # TODO: some of these operations are a bit racy
6 renv_file_preface <- function(source, target, overwrite) {
7
8 callback <- function() {}
9 if (!renv_file_exists(source))
10 stopf("source file '%s' does not exist", source)
11
12 if (overwrite)
13 callback <- renv_file_backup(target)
14
15 if (renv_file_exists(target))
16 stopf("target file '%s' already exists", target)
17
18 callback
19
20 }
21
22 renv_file_copy <- function(source, target, overwrite = FALSE) {
23
24 if (renv_file_same(source, target))
25 return(TRUE)
26
27 callback <- renv_file_preface(source, target, overwrite)
28 defer(callback())
29
30 # check to see if we're copying a plain file -- if so, things are simpler
31 if (dir.exists(source))
32 renv_file_copy_dir(source, target)
33 else
34 renv_file_copy_file(source, target)
35
36 }
37
38 renv_file_copy_file <- function(source, target) {
39
40 # copy to temporary path
41 tmpfile <- renv_scope_tempfile(".renv-copy-", tmpdir = dirname(target))
42 status <- catchall(file.copy(source, tmpfile))
43 if (inherits(status, "condition"))
44 stop(status)
45
46 # move from temporary path to final target
47 status <- catchall(renv_file_move(tmpfile, target))
48 if (inherits(status, "condition"))
49 stop(status)
50
51 # validate that the target file exists
52 if (!renv_file_exists(target)) {
53 fmt <- "attempt to copy file %s to %s failed (unknown reason)"
54 stopf(fmt, renv_path_pretty(source), renv_path_pretty(target))
55 }
56
57 invisible(TRUE)
58
59 }
60
61 renv_file_copy_dir_robocopy <- function(source, target) {
62 renv_robocopy_copy(source, target)
63 }
64
65 # TODO: the version of rsync distributed with macOS
66 # does not reliably copy file modified times, etc.
67 renv_file_copy_dir_rsync <- function(source, target) {
68 source <- sub("/*$", "/", source)
69 flags <- if (renv_platform_macos()) "-aAX" else "-a"
70 args <- c(flags, renv_shell_path(source), renv_shell_path(target))
71 renv_system_exec("rsync", args, action = "copying directory")
72 }
73
74 renv_file_copy_dir_cp <- function(source, target) {
75
76 # ensure 'source' ends with a single trailing slash
77 source <- sub("/*$", "/", source)
78
79 # ensure tildes are path-expanded
80 source <- path.expand(source)
81 target <- path.expand(target)
82
83 # build 'cp' arguments
84 args <- c("-PR", renv_shell_path(source), renv_shell_path(target))
85
86 # execute command
87 renv_system_exec("cp", args, action = "copying directory")
88
89 }
90
91 renv_file_copy_dir_r <- function(source, target) {
92
93 # create sub-directory to host copy attempt
94 tempdir <- renv_scope_tempfile(".renv-copy-", tmpdir = dirname(target))
95 ensure_directory(tempdir)
96
97 # attempt to copy to generated folder
98 status <- catchall(
99 file.copy(
100 source,
101 tempdir,
102 recursive = TRUE,
103 copy.mode = TRUE,
104 copy.date = TRUE
105 )
106 )
107
108 if (inherits(status, "condition"))
109 stop(status)
110
111 # R will copy the directory to a sub-directory in the
112 # requested folder with the same filename as the source
113 # folder, so peek into that folder to grab it and rename
114 tempfile <- file.path(tempdir, basename(source))
115 status <- catchall(renv_file_move(tempfile, target))
116 if (inherits(status, "condition"))
117 stop(status)
118
119 }
120
121 renv_file_copy_dir_impl <- function(source, target) {
122
123 methods <- list(
124 cp = renv_file_copy_dir_cp,
125 r = renv_file_copy_dir_r,
126 robocopy = renv_file_copy_dir_robocopy,
127 rsync = renv_file_copy_dir_rsync
128 )
129
130 copy <- config$copy.method()
131 if (is.function(copy))
132 return(copy(source, target))
133
134 method <- methods[[tolower(copy)]]
135 if (!is.null(method))
136 return(method(source, target))
137
138 if (renv_platform_windows())
139 renv_file_copy_dir_robocopy(source, target)
140 else if (renv_platform_unix())
141 renv_file_copy_dir_cp(source, target)
142 else
143 renv_file_copy_dir_r(source, target)
144
145 file.exists(target)
146
147 }
148
149 renv_file_copy_dir <- function(source, target) {
150
151 # create temporary sub-directory
152 tmpdir <- dirname(target)
153 ensure_directory(tmpdir)
154 tempdir <- renv_scope_tempfile(".renv-copy-", tmpdir = tmpdir)
155
156 # copy to that directory
157 status <- catchall(renv_file_copy_dir_impl(source, tempdir))
158 if (inherits(status, "condition"))
159 stop(status)
160
161 # move directory to final location
162 status <- catchall(renv_file_move(tempdir, target))
163 if (inherits(status, "condition"))
164 stop(status)
165
166 # validate that the target file exists
167 if (!renv_file_exists(target)) {
168 fmt <- "attempt to copy directory %s to %s failed (unknown reason)"
169 stopf(fmt, renv_path_pretty(source), renv_path_pretty(target))
170 }
171
172 invisible(TRUE)
173
174 }
175
176 renv_file_move <- function(source, target, overwrite = FALSE) {
177
178 if (renv_file_same(source, target))
179 return(TRUE)
180
181 callback <- renv_file_preface(source, target, overwrite)
182 defer(callback())
183
184 # first, attempt to do a plain rename
185 # use catchall since this might fail for e.g. cross-device links
186 # (note that junction points on Windows will be copies as-is)
187 move <- catchall(file.rename(source, target))
188 if (renv_file_exists(target))
189 return(TRUE)
190
191 # expand tildes
192 source <- path.expand(source)
193 target <- path.expand(target)
194
195 # on unix, try using 'mv' command directly
196 # (can handle cross-device copies / moves a bit more efficiently)
197 if (renv_platform_unix()) {
198 args <- c(renv_shell_path(source), renv_shell_path(target))
199 status <- catchall(system2("mv", args, stdout = FALSE, stderr = FALSE))
200 if (renv_file_exists(target))
201 return(TRUE)
202 }
203
204 # on Windows, similarly try 'robocopy' command
205 # (should be faster than 'move' for large directories)
206 if (renv_platform_windows()) {
207 status <- catchall(renv_robocopy_move(source, target))
208 if (renv_file_exists(target))
209 return(TRUE)
210 }
211
212 # nocov start
213 # rename failed; fall back to copying
214 # (and be sure to remove the source file / directory on success)
215 copy <- catchall(renv_file_copy(source, target, overwrite = overwrite))
216 if (identical(copy, TRUE) && file.exists(target)) {
217 unlink(source, recursive = TRUE)
218 return(TRUE)
219 }
220
221 # rename and copy both failed: inform the user
222 fmt <- stack()
223 fmt$push("could not copy / move file '%s' to '%s'")
224 if (inherits(move, "condition"))
225 fmt$push(paste("move:", conditionMessage(move)))
226 if (inherits(copy, "condition"))
227 fmt$push(paste("copy:", conditionMessage(copy)))
228
229 text <- paste(fmt$data(), collapse = "\n")
230 stopf(text, source, target)
231 # nocov end
232
233 }
234
235 renv_file_link <- function(source, target, overwrite = FALSE) {
236
237 if (renv_file_same(source, target))
238 return(TRUE)
239
240 callback <- renv_file_preface(source, target, overwrite)
241 defer(callback())
242
243 if (renv_platform_windows()) {
244
245 # use junction points on Windows by default as symlinks
246 # are unreliable / un-deletable in some circumstances
247 status <- catchall(Sys.junction(source, target))
248 if (identical(status, TRUE))
249 return(TRUE)
250
251 # if Sys.junction() fails, it may leave behind an empty
252 # directory. this may occur if the source and target files
253 # reside on different volumes. either way, remove an empty
254 # left-behind directory on failure
255 unlink(target, recursive = TRUE, force = TRUE)
256
257 } else {
258
259 # on non-Windows, we can try to create a symlink
260 status <- catchall(file.symlink(source, target))
261 if (identical(status, TRUE))
262 return(TRUE)
263
264 # file.symlink() may leave behind a broken symlink on filesystems
265 # that don't support symlinks (e.g. CIFS / SMB network mounts)
266 unlink(target)
267
268 }
269
270 # all else fails, just perform a copy
271 renv_file_copy(source, target, overwrite = overwrite)
272
273 }
274
275 renv_file_junction <- function(source, target) {
276
277 if (!renv_platform_windows())
278 stopf("'renv_file_junction()' is only available on Windows")
279
280 if (renv_file_exists(target))
281 stopf("file '%s' already exists")
282
283 status <- catchall(Sys.junction(source, target))
284 if (inherits(status, "condition")) {
285 unlink(target, recursive = TRUE, force = TRUE)
286 stop(status)
287 }
288
289 TRUE
290
291 }
292
293 renv_file_same <- function(source, target) {
294
295 # if the paths are the same, we can return early
296 if (identical(source, target))
297 return(TRUE)
298
299 # check to see if they're equal after normalization
300 # (e.g. for symlinks pointing to same file)
301 source <- renv_path_normalize(source)
302 target <- renv_path_normalize(target)
303 if (identical(source, target))
304 return(TRUE)
305
306
307 # for hard links + junction points, it's difficult to detect
308 # whether the two files point to the same object; use some
309 # heuristics to guess (note that these aren't perfect)
310 sinfo <- renv_file_info(source)
311 if (is.na(sinfo$isdir))
312 return(FALSE)
313
314 tinfo <- renv_file_info(target)
315 if (is.na(tinfo$isdir))
316 return(FALSE)
317
318 # NOTE: we intentionally exclude 'size' for directories, as
319 # on Windows the 'size' field might be reported as 0 for
320 # junction points?
321 if (renv_platform_windows()) {
322 if (sinfo$isdir || tinfo$isdir)
323 sinfo$size <- tinfo$size <- 0L
324 }
325
326 identical(c(sinfo), c(tinfo))
327
328 }
329
330 # NOTE: returns a callback which should be used in e.g. an defer handler
331 # to restore the file if the attempt to update the file failed
332 renv_file_backup <- function(path) {
333
334 # if no file exists then nothing to backup
335 if (!renv_file_exists(path))
336 return(function() {})
337
338 # normalize the path (since the working directory could change
339 # by the time the callback is invoked). note that the file may
340 # be a broken symlink so construct the path by normalizing the
341 # parent directory and building path relative to that
342 parent <- renv_path_normalize(dirname(path), mustWork = TRUE)
343 path <- file.path(parent, basename(path))
344
345 # attempt to rename the file
346 pattern <- sprintf(".renv-backup-%i-%s", Sys.getpid(), basename(path))
347 tempfile <- tempfile(pattern, tmpdir = dirname(path))
348 if (!renv_file_move(path, tempfile))
349 stopf("couldn't rename '%s' prior to transaction", renv_path_pretty(path))
350
351 # return callback that will restore if needed
352 function() {
353
354 if (!renv_file_exists(path))
355 renv_file_move(tempfile, path)
356 else
357 unlink(tempfile, recursive = TRUE)
358
359 }
360
361 }
362
363 renv_file_info <- function(paths, extra_cols = FALSE) {
364 suppressWarnings(file.info(paths, extra_cols = extra_cols))
365 }
366
367 # NOTE: returns true for files that are broken symlinks
368 renv_file_exists <- function(path) {
369
370 if (renv_platform_windows())
371 renv_file_exists_win32(path)
372 else
373 renv_file_exists_unix(path)
374
375 }
376
377 renv_file_exists_win32 <- function(path) {
378 file.exists(path)
379 }
380
381 renv_file_exists_unix <- function(path) {
382 !is.na(Sys.readlink(path)) | file.exists(path)
383 }
384
385 renv_file_list <- function(path, full.names = TRUE) {
386
387 # list files
388 files <- renv_file_list_impl(path)
389
390 # NOTE: paths may be marked with UTF-8 encoding;
391 # if that's the case we need to use paste rather
392 # than file.path to preserve the encoding
393 if (full.names && length(files))
394 files <- paste(path, files, sep = "/")
395
396 files
397
398 }
399
400 renv_file_list_impl <- function(path) {
401 if (renv_platform_unix())
402 renv_file_list_impl_unix(path)
403 else
404 renv_file_list_impl_win32(path)
405 }
406
407 renv_file_list_impl_unix <- function(path) {
408 list.files(path, all.files = TRUE, no.. = TRUE)
409 }
410
411 # nocov start
412 renv_file_list_impl_win32 <- function(path) {
413
414 # first, try a plain list.files to see if we can get away with that
415 files <- list.files(path, all.files = TRUE, no.. = TRUE)
416 if (!any(grepl("?", files, fixed = TRUE)))
417 return(files)
418
419 # otherwise, try some madness ...
420 #
421 # change working directory (done just to avoid encoding issues
422 # when submitting path to cmd shell)
423 renv_scope_wd(path)
424
425 # NOTE: a sub-shell is required here in some contexts; e.g. when running
426 # tests non-interactively or building in the RStudio pane
427 command <- paste(comspec(), "/U /C dir /B")
428 conn <- pipe(command, open = "rb", encoding = "native.enc")
429 defer(close(conn))
430
431 # read binary output from connection
432 output <- stack()
433
434 while (TRUE) {
435
436 data <- readBin(conn, what = "raw", n = 1024L)
437 if (empty(data))
438 break
439
440 output$push(data)
441
442 }
443
444 # join into single raw vector
445 encoded <- unlist(output$data(), recursive = FALSE, use.names = FALSE)
446
447 # convert raw data (encoded as UTF-16LE) to UTF-8
448 converted <- iconv(list(encoded), from = "UTF-16LE", to = "UTF-8")
449
450 # split on (Windows) newlines
451 paths <- strsplit(converted, "\r\n", fixed = TRUE)[[1]]
452
453 # just in case?
454 paths[nzchar(paths)]
455
456 }
457 # nocov end
458
459 renv_file_type <- function(paths, symlinks = TRUE) {
460
461 info <- renv_file_info(paths)
462
463 types <- character(length(paths))
464 types[info$isdir %in% FALSE] <- "file"
465 types[info$isdir %in% TRUE ] <- "directory"
466
467 if (symlinks && !renv_platform_windows()) {
468 links <- Sys.readlink(paths)
469 types[!is.na(links) & nzchar(links)] <- "symlink"
470 }
471
472 types
473
474 }
475
476 # nocov start
477 renv_file_edit <- function(path) {
478
479 # https://github.com/rstudio/renv/issues/44
480 dlls <- getLoadedDLLs()
481 if (is.null(dlls[["(embedding)"]]))
482 return(utils::file.edit(path))
483
484 routines <- getDLLRegisteredRoutines("(embedding)")
485 routine <- routines[[".Call"]][["rs_editFile"]]
486 if (is.null(routine))
487 return(utils::file.edit(path))
488
489 do.call(.Call, list(routine, path, PACKAGE = "(embedding)"))
490
491 }
492 # nocov end
493
494 renv_file_find <- function(path, predicate) {
495
496 # canonicalize path
497 # (note: don't normalize as we don't want to follow symlinks)
498 path <- renv_path_canonicalize(path)
499 parent <- dirname(path)
500
501 # compute number of slashes
502 # (avoid searching beyond home directory, unless we're virtualized)
503 virtualized <- renv_virtualization_type() != "native"
504 slashes <- gregexpr("/", path, fixed = TRUE)[[1L]]
505 n <- length(slashes) - if (virtualized) 0L else 2L
506
507 for (i in 1:n) {
508
509 if (file.exists(path)) {
510 status <- predicate(path)
511 if (!is.null(status))
512 return(status)
513 }
514
515 path <- parent
516 parent <- dirname(path)
517
518 }
519
520 predicate(path)
521
522 }
523
524 renv_file_read <- function(path) {
525 renv_scope_options(warn = -1L)
526 contents <- readLines(path, warn = FALSE, encoding = "UTF-8")
527 paste(contents, collapse = "\n")
528 }
529
530 renv_file_shebang <- function(path) {
531
532 # NOTE: we use 'condition' as a cheap way to capture both errors and warnings
533 # since 'file()' may just report a warning rather than an error if it fails
534 # to open a file due to inadequate permissions
535 tryCatch(
536 renv_file_shebang_impl(path),
537 condition = function(e) ""
538 )
539
540 }
541
542 renv_file_shebang_impl <- function(path) {
543
544 renv_scope_options(warn = -1L)
545
546 # open connection to file
547 con <- file(path, open = "rb", encoding = "native.enc")
548 defer(close(con))
549
550 # validate file starts with '#!' -- read using 'raw' vector to avoid
551 # issues which files that might start with null bytes
552 bytes <- readBin(con, what = "raw", n = 2L)
553 expected <- as.raw(c(0x23L, 0x21L))
554 if (!identical(bytes, expected))
555 return("")
556
557 # read a single line from the connection
558 readLines(con, n = 1L, warn = FALSE)
559
560 }
561
562 # here, 'broken' implies a file which is a link pointing to a file that
563 # doesn't exist, so only returns true if the file is "link"-y and the
564 # file it points to doesn't exist
565 renv_file_broken <- function(paths) {
566 if (renv_platform_unix())
567 renv_file_broken_unix(paths)
568 else
569 renv_file_broken_win32(paths)
570 }
571
572 renv_file_broken_unix <- function(paths) {
573 # a symlink is broken if:
574 # - the file is a symlink (tested via Sys.readlink)
575 # - the file it points to does not exist (tested via file.exists)
576 !is.na(Sys.readlink(paths)) & !file.exists(paths)
577 }
578
579 # unfortunately, as far as I know, there isn't a more reliable
580 # way of detecting broken junction points on Windows using vanilla R
581 renv_file_broken_win32 <- function(paths) {
582 time <- Sys.time()
583 map_lgl(paths, function(path) {
584 file.access(path) == 0L && !Sys.setFileTime(path, time)
585 })
586 }
587
588 renv_file_size <- function(path) {
589 file.info(path, extra_cols = FALSE)$size
590 }
591
592 renv_file_remove <- function(paths) {
593 if (renv_platform_windows())
594 renv_file_remove_win32(paths)
595 else
596 renv_file_remove_unix(paths)
597 }
598
599 renv_file_remove_win32 <- function(paths) {
600 for (path in paths) {
601 command <- paste("rmdir /S /Q", renv_shell_path(path))
602 shell(command)
603 }
604 }
605
606 renv_file_remove_unix <- function(paths) {
607 unlink(paths, recursive = TRUE, force = TRUE)
608 }
609
610 renv_file_writable <- function(path) {
611
612 # allow users to opt-out just in case
613 override <- getOption("renv.download.check_writable", default = TRUE)
614 if (!identical(override, TRUE))
615 return(TRUE)
616
617 # if we're given the path to a file, use the parent directory instead
618 info <- renv_file_info(path)
619 if (!identical(info$isdir, TRUE))
620 path <- dirname(path)
621
622 # if we still don't have a directory, bail
623 info <- renv_file_info(path)
624 if (!identical(info$isdir, TRUE))
625 return(FALSE)
626
627 # try creating and removing a temporary file in this directory
628 tempfile <- renv_scope_tempfile(".renv-write-test-", tmpdir = path)
629 ok <- dir.create(tempfile, showWarnings = FALSE)
630
631 # return ok if we succeeded
632 ok
633
634 }