1
#' Files which delete themselves
2
#'
3
#' Create files, which are then automatically removed afterwards.
4
#' @template with
5
#' @param file,.file `[named list]`\cr Files to create.
6
#' @param ... Additional (possibly named) arguments of files to create.
7
#' @param .local_envir `[environment]`\cr The environment to use for scoping.
8
#' @examples
9
#' with_file("file1", {
10
#'   writeLines("foo", "file1")
11
#'   readLines("file1")
12
#' })
13
#'
14
#' with_file(list("file1" = writeLines("foo", "file1")), {
15
#'   readLines("file1")
16
#' })
17
#' @export
18
with_file <- function(file, code) {
19

20 1
  file_nms <- names2(file)
21 1
  unnamed <- file_nms == ""
22 1
  file_nms[unnamed] <- as.character(file[unnamed])
23 1
  on.exit(unlink(file_nms, recursive = TRUE))
24 1
  eval.parent(code)
25

26 1
  invisible(file)
27
}
28

29
#' @rdname with_file
30
#' @export
31
local_file <- function(.file, ..., .local_envir = parent.frame()) {
32 1
  .file <- utils::modifyList(as.list(.file), list(...))
33 1
  .file <- as_character(.file)
34

35 1
  file_nms <- names2(.file)
36 1
  unnamed <- file_nms == ""
37 1
  file_nms[unnamed] <- as.character(.file[unnamed])
38 1
  defer(unlink(file_nms, recursive = TRUE), envir = .local_envir)
39

40 1
  invisible(.file)
41
}

Read our documentation on viewing source code .

Loading