File: file.R

package info (click to toggle)
r-cran-withr 3.0.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 620 kB
  • sloc: sh: 13; makefile: 2
file content (41 lines) | stat: -rw-r--r-- 1,137 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#' Files which delete themselves
#'
#' Create files, which are then automatically removed afterwards.
#' @template with
#' @param file,.file `[named list]`\cr Files to create.
#' @param ... Additional (possibly named) arguments of files to create.
#' @param .local_envir `[environment]`\cr The environment to use for scoping.
#' @examples
#' with_file("file1", {
#'   writeLines("foo", "file1")
#'   readLines("file1")
#' })
#'
#' with_file(list("file1" = writeLines("foo", "file1")), {
#'   readLines("file1")
#' })
#' @export
with_file <- function(file, code) {

  file_nms <- names2(file)
  unnamed <- file_nms == ""
  file_nms[unnamed] <- as.character(file[unnamed])
  on.exit(unlink(file_nms, recursive = TRUE))
  force(code)

  invisible(file)
}

#' @rdname with_file
#' @export
local_file <- function(.file, ..., .local_envir = parent.frame()) {
  .file <- utils::modifyList(as.list(.file), list(...))
  .file <- as_character(.file)

  file_nms <- names2(.file)
  unnamed <- file_nms == ""
  file_nms[unnamed] <- as.character(.file[unnamed])
  defer(unlink(file_nms, recursive = TRUE), envir = .local_envir)

  invisible(.file)
}