Debian Codegraph @

R/delete.R

raw
1 #' Delete files, directories, or links
2 #'
3 #' @description
4 #' `file_delete()` and `link_delete()` delete file and links. Compared to
5 #' [file.remove] they always fail if they cannot delete the object rather than
6 #' changing return value or signalling a warning. If any inputs are
7 #' directories, they are passed to `dir_delete()`, so `file_delete()` can
8 #' therefore be used to delete any filesystem object.
9 #'
10 #' `dir_delete()` will first delete the contents of the directory, then remove
11 #' the directory. Compared to [unlink] it will always throw an error if the
12 #' directory cannot be deleted rather than being silent or signalling a warning.
13 #' @template fs
14 #' @export
15 #' @return The deleted paths (invisibly).
16 #' @name delete
17 #' @examples
18 #' \dontshow{.old_wd <- setwd(tempdir())}
19 #' # create a directory, with some files and a link to it
20 #' dir_create("dir")
21 #' files <- file_create(path("dir", letters[1:5]))
22 #' link <- link_create(path_abs("dir"), "link")
23 #'
24 #' # All files created
25 #' dir_exists("dir")
26 #' file_exists(files)
27 #' link_exists("link")
28 #' file_exists(link_path("link"))
29 #'
30 #' # Delete a file
31 #' file_delete(files[1])
32 #' file_exists(files[1])
33 #'
34 #' # Delete the directory (which deletes the files as well)
35 #' dir_delete("dir")
36 #' file_exists(files)
37 #' dir_exists("dir")
38 #'
39 #' # The link still exists, but what it points to does not.
40 #' link_exists("link")
41 #' dir_exists(link_path("link"))
42 #'
43 #' # Delete the link
44 #' link_delete("link")
45 #' link_exists("link")
46 #' \dontshow{setwd(.old_wd)}
47 file_delete <- function(path) {
48 assert_no_missing(path)
49
50 old <- path_expand(path)
51
52 dirs <- is_dir(old)
53 dir_delete(old[dirs])
54
55 .Call(fs_unlink_, old[!dirs])
56
57 invisible(path_tidy(path))
58 }
59
60 #' @rdname delete
61 #' @export
62 dir_delete <- function(path) {
63 assert_no_missing(path)
64
65 old <- path_expand(path)
66
67 dirs <- dir_ls(old, type = "directory", recurse = TRUE, all = TRUE)
68 files <- dir_ls(
69 old,
70 type = c(
71 "unknown",
72 "file",
73 "symlink",
74 "FIFO",
75 "socket",
76 "character_device",
77 "block_device"
78 ),
79 recurse = TRUE,
80 all = TRUE
81 )
82 .Call(fs_unlink_, files)
83 .Call(fs_rmdir_, rev(c(old, dirs)))
84
85 invisible(path_tidy(path))
86 }
87
88 #' @rdname delete
89 #' @export
90 link_delete <- function(path) {
91 assert_no_missing(path)
92
93 assert("`path` must be a link", all(is_link(path)))
94
95 old <- path_expand(path)
96
97 .Call(fs_unlink_, old)
98
99 invisible(path_tidy(path))
100 }