| 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 |
file_nms <- names2(file) |
| 20 |
unnamed <- file_nms == "" |
| 21 |
file_nms[unnamed] <- as.character(file[unnamed]) |
| 22 |
on.exit(unlink(file_nms, recursive = TRUE)) |
| 23 |
force(code) |
| 24 |
|
| 25 |
invisible(file) |
| 26 |
} |
| 27 |
|
| 28 |
#' @rdname with_file |
| 29 |
#' @export |
| 30 |
local_file <- function(.file, ..., .local_envir = parent.frame()) { |
| 31 |
.file <- utils::modifyList(as.list(.file), list(...)) |
| 32 |
.file <- as_character(.file) |
| 33 |
|
| 34 |
file_nms <- names2(.file) |
| 35 |
unnamed <- file_nms == "" |
| 36 |
file_nms[unnamed] <- as.character(.file[unnamed]) |
| 37 |
defer(unlink(file_nms, recursive = TRUE), envir = .local_envir) |
| 38 |
|
| 39 |
invisible(.file) |
| 40 |
} |