Debian Codegraph @

R/sink.R

raw
1 # sink -----------------------------------------------------------------------
2
3 # FIXME: Use (a better version of) pryr:::partial2 when available
4 output_sink <- function(file = NULL, append = FALSE, split = FALSE) {
5 sink(file = file, append = append, type = "output", split = split)
6 }
7
8 message_sink <- function(file = NULL, append = FALSE) {
9 sink(file = file, append = append, type = "message", split = FALSE)
10 }
11
12 #' @include wrap.R
13 set_output_sink <- wrap(
14 output_sink,
15 if (is.null(file)) {
16 stop("file cannot be NULL", call. = FALSE)
17 },
18 list(n = sink.number())
19 )
20
21 set_message_sink <- wrap(
22 message_sink,
23 {
24 if (is.null(file)) {
25 stop("file cannot be NULL,", call. = FALSE)
26 }
27 if (sink.number(type = "message") != 2L) {
28 stop(
29 "Cannot establish message sink when another sink is active.",
30 call. = FALSE
31 )
32 }
33 con <- if (is.character(file)) {
34 file <- file(file, if (append) "a" else "w")
35 }
36 },
37 {
38 list(n = sink.number(type = "message"), con = con)
39 }
40 )
41
42 reset_output_sink <- function(sink_info) {
43 repeat {
44 n <- sink.number()
45 delta <- n - sink_info$n
46
47 if (delta >= 0L) {
48 sink()
49
50 if (delta > 0L) {
51 warning("Removing a different sink.", call. = FALSE)
52 } else {
53 return()
54 }
55 } else {
56 warning("Sink #", sink_info$n, " already removed.", call. = FALSE)
57 return()
58 }
59 }
60 }
61
62 reset_message_sink <- function(sink_info) {
63 if (!is.null(sink_info$con)) {
64 on.exit(close(sink_info$con), add = TRUE)
65 }
66
67 do_reset_message_sink(sink_info)
68 }
69
70 do_reset_message_sink <- function(sink_info) {
71 n <- sink.number(type = "message")
72 if (n == 2L) {
73 warning("No message sink to remove.", call. = FALSE)
74 } else if (n == sink_info$n) {
75 sink(type = "message")
76 } else {
77 warning("Not removing a different message sink.", call. = FALSE)
78 }
79 }
80
81 #' Output redirection
82 #'
83 #' Temporarily divert output to a file via [sink()]. For
84 #' sinks of type `message`, an error is raised if such a sink is already
85 #' active.
86 #'
87 #' @template with
88 #' @param new `[character(1)|connection]`\cr
89 #' A writable \link{connection} or a character string naming the file to write
90 #' to. Passing `NULL` will throw an error.
91 #' @inheritParams base::sink
92 #' @inheritParams with_collate
93 #' @seealso [sink()]
94 #' @export
95 #' @name with_sink
96 with_output_sink <- with_(set_output_sink, reset_output_sink)
97
98 #' @rdname with_sink
99 #' @export
100 local_output_sink <- local_(set_output_sink, reset_output_sink)
101
102 #' @rdname with_sink
103 #' @export
104 with_message_sink <- with_(set_message_sink, reset_message_sink)
105
106 #' @rdname with_sink
107 #' @export
108 local_message_sink <- local_(set_message_sink, reset_message_sink)