Skip to content

Commit

Permalink
Use a file connection instead of a text connection
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed Jun 18, 2024
1 parent 64c114c commit 5483021
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 25 deletions.
4 changes: 4 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@ defer <- function(expr, frame = parent.frame(), after = FALSE) {
thunk <- as.call(list(function() expr))
do.call(on.exit, list(thunk, TRUE, after), envir = frame)
}

compact <- function(x) {
x[!vapply(x, is.null, logical(1))]
}
50 changes: 25 additions & 25 deletions R/watcher.R
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@
watchout <- function(handler = new_output_handler(),
debug = FALSE,
frame = parent.frame()) {
output <- character()
prev <- character()

con <- textConnection("output", "wr", local = TRUE)
con <- file("", "w+b")
defer(frame = frame, {
if (!test_con(con, isOpen)) {
con_error('The connection has been closed')

Check warning on line 16 in R/watcher.R

View check run for this annotation

Codecov / codecov/patch

R/watcher.R#L16

Added line #L16 was not covered by tests
Expand All @@ -27,30 +24,33 @@ watchout <- function(handler = new_output_handler(),
old <- options(try.outFile = con)
defer(options(old), frame = frame)

function(plot = FALSE, incomplete_plots = FALSE) {
incomplete <- test_con(con, isIncomplete)
if (incomplete) cat("\n")

out <- list()

if (plot) {
out$graphics <- plot_snapshot(incomplete_plots)
if (!is.null(out$graphics)) handler$graphics(out$graphics)
function(plot = TRUE, incomplete_plots = FALSE) {
out <- list(
if (plot) plot_snapshot(incomplete_plots),
read_con(con)
)
if (!is.null(out[[1]])) {
handler$graphics(out[[1]])
}

n0 <- length(prev)
n1 <- length(output)
if (n1 > n0) {
new <- output[n0 + seq_len(n1 - n0)]
prev <<- output

out$text <- paste0(new, collapse = "\n")
if (!incomplete) out$text <- paste0(out$text, "\n")

handler$text(out$text)
if (!is.null(out[[2]])) {
handler$text(out[[2]])
}

compact(out)
}
}

unname(out)
read_con <- function(con, buffer = 1024) {
bytes <- raw()
repeat {
new <- readBin(con, "raw", n = buffer)
if (length(new) == 0) break
bytes <- c(bytes, new)
}
if (length(bytes) == 0) {
NULL
} else {
rawToChar(bytes)
}
}

Expand Down

0 comments on commit 5483021

Please sign in to comment.