Debian Codegraph @

R/temp.R

raw
1 env <- new.env(parent = emptyenv())
2 env$temp_names <- character()
3
4 #' Create names for temporary files
5 #'
6 #' `file_temp()` returns the name which can be used as a temporary file.
7 #'
8 #' `file_temp_push()` can be used to supply deterministic entries in the
9 #' temporary file stack. This can be useful for reproducibility in like example
10 #' documentation and vignettes.
11 #'
12 #' `file_temp_pop()` can be used to explicitly remove an entry from the
13 #' internal stack, however generally this is done instead by calling
14 #' `file_temp()`.
15 #'
16 #' `path_temp()` constructs a path within the session temporary directory.
17 #' @param pattern A character vector with the non-random portion of the name.
18 #' @param tmp_dir The directory the file will be created in.
19 #' @param ext The file extension of the temporary file.
20 #' @param ... Additional paths appended to the temporary directory by `path()`.
21 #' @template fs
22 #' @export
23 #' @examples
24 #' \dontshow{file_temp_push("/tmp/filedd461c46df20")}
25 #'
26 #' path_temp()
27 #' path_temp("does-not-exist")
28 #'
29 #' file_temp()
30 #' file_temp(ext = "png")
31 #' file_temp("image", ext = "png")
32 #'
33 #'
34 #' # You can make the temp file paths deterministic
35 #' file_temp_push(letters)
36 #' file_temp()
37 #' file_temp()
38 #'
39 #' # Or explicitly remove values
40 #' while (!is.null(file_temp_pop())) next
41 #' file_temp_pop()
42 file_temp <- function(pattern = "file", tmp_dir = tempdir(), ext = "") {
43 assert_no_missing(tmp_dir)
44
45 has_extension <- nzchar(ext)
46
47 # ensure the extension starts with _one_ .
48 ext[has_extension] <- paste0(".", sub("^[.]", "", ext[has_extension]))
49
50 path_tidy(file_temp_pop() %||% tempfile(pattern, tmp_dir, ext))
51 }
52
53 #' @export
54 #' @rdname file_temp
55 file_temp_push <- function(path) {
56 assert_no_missing(path)
57
58 old <- path_expand(path)
59
60 env$temp_names <- c(env$temp_names, old)
61
62 invisible(path_tidy(path))
63 }
64
65
66 #' @export
67 #' @rdname file_temp
68 file_temp_pop <- function() {
69 n <- length(env$temp_names)
70 if (n == 0) {
71 return(NULL)
72 }
73
74 out <- env$temp_names[[1]]
75 env$temp_names <- env$temp_names[-1]
76 path_tidy(out)
77 }
78
79 #' @export
80 #' @rdname file_temp
81 path_temp <- function(...) {
82 path(tempdir(), ...)
83 }