Debian Codegraph @

R/connection.R

raw
1 #' Connections which close themselves
2 #'
3 #' R file connections which are automatically closed.
4 #'
5 #' @template with
6 #' @param con For `with_connection()` a named list with the connection(s) to
7 #' create. For `local_connection()` the code to create a single connection,
8 #' which is then returned.
9 #' @param .local_envir `[environment]`\cr The environment to use for scoping.
10 #' @examples
11 #' with_connection(list(con = file("foo", "w")), {
12 #' writeLines(c("foo", "bar"), con)
13 #' })
14 #'
15 #' read_foo <- function() {
16 #' readLines(local_connection(file("foo", "r")))
17 #' }
18 #' read_foo()
19 #'
20 #' unlink("foo")
21 #' @export
22 with_connection <- function(con, code) {
23 stopifnot(all(is.named(con)))
24
25 on.exit({
26 for (connection in con) {
27 close(connection)
28 }
29 })
30 eval(substitute(code), envir = con, enclos = parent.frame())
31 }
32
33 #' @rdname with_connection
34 #' @export
35 local_connection <- function(con, .local_envir = parent.frame()) {
36 defer(close(con), envir = .local_envir)
37 con
38 }