Debian Codegraph @

R/record.R

raw
1 #' Run R code and record the results
2 #'
3 #' Run R code and capture various types of output, including text output, plots,
4 #' messages, warnings, and errors.
5 #' @param code A character vector of R source code.
6 #' @param dev A graphics device. It can be a function name, a function, or a
7 #' character string that can be evaluated to a function to open a graphics
8 #' device.
9 #' @param dev.path A base file path for plots. Actual plot filenames will be
10 #' this base path plus incremental suffixes. For example, if `dev.path =
11 #' "foo"`, the plot files will be `foo-1.png`, `foo-2.png`, and so on. If
12 #' `dev.path` is not character (e.g., `FALSE`), plots will not be recorded.
13 #' @param dev.ext The file extension for plot files. By default, it will be
14 #' inferred from the first argument of the device function if possible.
15 #' @param dev.args Extra arguments to be passed to the device. The default
16 #' arguments are `list(units = 'in', onefile = FALSE, width = 7, height = 7,
17 #' res = 96)`. If any of these arguments is not present in the device
18 #' function, it will be dropped.
19 #' @param dev.keep Indices of plots to be kept. The indices can be either
20 #' numeric (positive or negative integers) or logical. Negative integers and
21 #' false values will remove the corresponding plots. For example, if the code
22 #' generated 3 plots, `dev.keep = c(1, 3)`, `-2`, and `c(T, F, T)` are
23 #' equivalent ways to remove the second plot. The special value `dev.keep =
24 #' 'last'` means to keep the last plot only.
25 #' @param message,warning,error If `TRUE`, record and store messages / warnings
26 #' / errors in the output. If `FALSE`, suppress them. If `NA`, do not process
27 #' them (messages will be emitted to the console, and errors will halt the
28 #' execution).
29 #' @param cache A list of options for caching. See the `path`, `id`, and `...`
30 #' arguments of [cache_exec()].
31 #' @param print A (typically S3) function that takes the value of an expression
32 #' in the code as input and returns output. The default is [record_print()].
33 #' If a non-function value (e.g., `NA`) is passed to this argument, [print()]
34 #' (or [show()] for S4 objects) will be used.
35 #' @param print.args A list of arguments for the `print` function. By default,
36 #' the whole list is not passed directly to the function, but only an element
37 #' in the list with a name identical to the first class name of the returned
38 #' value of the expression, e.g., `list(data.frame = list(digits = 3), matrix
39 #' = list())`. This makes it possible to apply different print arguments to
40 #' objects of different classes. If the whole list is intended to be passed to
41 #' the print function directly, wrap the list in [I()].
42 #' @param verbose `2` means to always print the value of each expression in the
43 #' code, no matter if the value is [invisible()] or not; `1` means to always
44 #' print the value of the last expression; `0` means no special handling
45 #' (i.e., print only when the value is visible).
46 #' @param envir An environment in which the code is evaluated.
47 #' @return `record()` returns a list of the class `xfun_record_results` that
48 #' contains elements with these possible classes: `record_source` (source
49 #' code), `record_output` (text output), `record_plot` (plot file paths),
50 #' `record_message` (messages), `record_warning` (warnings), and
51 #' `record_error` (errors, only when the argument `error = TRUE`).
52 #' @import grDevices
53 #' @export
54 #' @examples
55 #' code = c('# a warning test', '1:2 + 1:3', 'par(mar = c(4, 4, 1, .2))', 'barplot(5:1, col = 2:6, horiz = TRUE)', 'head(iris)', "sunflowerplot(iris[, 3:4], seg.col = 'purple')", "if (TRUE) {\n message('Hello, xfun::record()!')\n}", '# throw an error', "1 + 'a'")
56 #' res = xfun::record(code, dev.args = list(width = 9, height = 6.75), error = TRUE)
57 #' xfun::tree(res)
58 #' format(res)
59 #' # find and clean up plot files
60 #' plots = Filter(function(x) inherits(x, 'record_plot'), res)
61 #' file.remove(unlist(plots))
62 record = function(
63 code = NULL, dev = 'png', dev.path = 'xfun-record', dev.ext = dev_ext(dev),
64 dev.args = list(), dev.keep = TRUE, message = TRUE, warning = TRUE, error = NA,
65 cache = list(), print = record_print, print.args = list(),
66 verbose = getOption('xfun.record.verbose', 0), envir = parent.frame()
67 ) {
68 new_result = function(x = list()) structure(x, class = 'xfun_record_results')
69 res = new_result()
70 if (length(code) == 0) return(res)
71
72 # use cached results if cache exists
73 use_cache = FALSE
74 ret = cache_code(code, envir, use_cache <- TRUE, cache)
75 if (use_cache) return(ret)
76
77 code = split_lines(code)
78
79 add_result = function(x, type = NULL, pos = length(res), insert = TRUE) {
80 # default type is output
81 if (is.null(type) && !inherits(x, .record_classes)) type = 'output'
82 # insert a whole element or append to an existing element in res
83 if (!insert) x = c(res[[pos]], x)
84 el = if (is.null(type)) x else new_record(x, type)
85 N = length(res)
86 if (insert) {
87 if (N == pos) res[[N + 1]] <<- el else res <<- append(res, el, pos)
88 } else {
89 res[[pos]] <<- el
90 }
91 }
92
93 # dev.off() will set the current device to next instead of previous device,
94 # but we often want to restore to the previous instead
95 dev_cur = dev.cur()
96 dev_reset = function() if (dev_cur != 1 && dev_cur %in% dev.list()) dev.set(dev_cur)
97
98 # look for all possible ${dev.path}-%d.${dev.ext} files created by the device
99 get_plots = function() {
100 files = sprintf(dev.path, seq_along(list.files(dirname(dev.path))))
101 files[file_exists(files)]
102 }
103 # open a graphics device
104 dev_num = if (is.character(dev.path)) {
105 if (!is.function(dev)) dev = tryCatch(match.fun(dev), error = function(e) {
106 eval(parse(text = dev), envir = envir)
107 })
108 # normalize \ to / and remove the leading ./
109 if (is_windows()) dev.path = gsubf('\\', '/', dev.path)
110 dev.path = sub('^[.]/+', '', dev.path)
111 # add extension
112 dev.path = with_ext(paste0(dev.path, if (!grepl('/$', dev.path)) '-', '%d'), dev.ext)
113 dir_create(dirname(dev.path))
114 # clean up existing plots before opening the device
115 if (any(i <- !file.remove(old_plots <- get_plots()))) stop(
116 'Failed to delete existing plot file(s): ',
117 paste("'", old_plots[i], "'", collapse = ', ')
118 )
119 dev_open(dev, dev.path, dev.args)
120 }
121 dev_old = dev.list() # keep track of current devices
122 dev_off = function() {
123 if (length(dev_num) && dev_num %in% dev.list()) dev.off(dev_num)
124 dev_reset()
125 dev_num <<- NULL # prevent dev.off() again by accident
126 }
127 on.exit(dev_off(), add = TRUE)
128
129 # check if new plots are generated
130 handle_plot = local({
131 # don't record plots if no device was opened
132 if (length(dev_num) == 0) return(function(...) {})
133 old_files = character(); old_times = NULL # previous plot files and file mtimes
134 old_plot = recordPlot()
135 function(last = FALSE) {
136 # if dev.list() has changed, no longer record graphics, except for the last plot
137 if (!last) {
138 if (!(length(dev_num) && identical(dev.list(), dev_old))) return()
139 dev.set(dev_num)
140 }
141 files = get_plots()
142 # on Windows, an empty plot file is created upon opening a device
143 files = files[file.size(files) > 0]
144
145 if (!last) {
146 new_plot = recordPlot()
147 if (!identical(old_plot, new_plot)) {
148 # add a placeholder for new plots, which may not have been created by
149 # the device until the next new plot is drawn
150 add_result(character(), 'plot')
151 old_plot <<- new_plot
152 }
153 }
154
155 if (length(files) == 0) return()
156
157 # old files that have been modified should be removed from existing records
158 k = file.mtime(old_files) > old_times
159 if (any(k)) for (i in seq_along(res)) {
160 if (inherits(res[[i]], 'record_plot'))
161 res[[i]] <<- new_record(setdiff(res[[i]], old_files[k]), 'plot')
162 }
163 old_files = old_files[!k]
164
165 plots = setdiff(files, old_files)
166 old_files <<- files
167 old_times <<- file.mtime(files)
168 if ((n <- length(plots)) == 0) return()
169 # if an empty plot is recorded, remove it (e.g., yihui/litedown#96)
170 if (n == 1 && empty_plot(old_plot)) {
171 file.remove(plots); old_files <<- character(); old_times <<- NULL
172 return()
173 }
174
175 # indices of plots in results
176 i = which(vapply(res, inherits, logical(1), 'record_plot'))
177 N = length(i)
178 # the last plot should always be appended to the last plot block
179 if (last) {
180 # N = 0 means the code didn't produce any plots
181 if (N == 0) file.remove(plots) else add_result(plots, 'plot', i[N], FALSE)
182 return()
183 }
184
185 # for the newly generated plots, append the first one (which should be the
186 # last plot of a previous code chunk, since it will be created only when
187 # the next code chunk produces a new plot) to the previous plot block; the
188 # rest are for the current block
189 if (N > 1) {
190 add_result(plots[1], 'plot', i[N - 1], FALSE)
191 if (n > 1) add_result(plots[2:n], 'plot', i[N], FALSE)
192 } else if (N == 1) {
193 # if there exists only one plot block, add plots to that block
194 add_result(plots, 'plot', i[N], FALSE)
195 }
196 }
197 })
198
199 handle = if (is.na(error)) identity else try_silent
200 # split code into individual expressions
201 codes = handle(split_source(code, merge_comments = TRUE, line_number = TRUE))
202 # code may contain syntax errors
203 if (is_error(codes)) {
204 add_result(code, 'source'); add_result(attr2(codes, 'condition')$message, 'error')
205 return(new_result(res))
206 }
207
208 # trim error message and remove the uninformative part (yihui/litedown#109)
209 trim_error = function(e) {
210 x = sub('\\s+$', '', as.character(e))
211 sub(' in eval\\(expr, envir(, enclos)?\\):', ':', x)
212 }
213 handle_message = function(type, add = TRUE) {
214 err = type == 'error'
215 mf = if (!err) sub('^(.)', 'muffle\\U\\1', type, perl = TRUE)
216 function(e) {
217 if (is.na(add)) return()
218 if (isTRUE(add)) add_result(if (err) trim_error(e) else e$message, type)
219 if (!err) invokeRestart(mf)
220 }
221 }
222 handle_m = handle_message('message', message)
223 handle_w = handle_message('warning', warning)
224 handle_e = handle_message('error', error)
225
226 # don't use withCallingHandlers() if message/warning/error are all NA
227 handle_eval = function(expr) {
228 handle(if (is.na(message) && is.na(warning) && is.na(error)) expr else {
229 withCallingHandlers(
230 expr, message = handle_m, warning = handle_w, error = handle_e
231 )
232 })
233 }
234 # a simplified version of capture.output()
235 handle_output = function(expr) {
236 out = NULL
237 con = rawConnection(raw(0), 'w')
238 on.exit(close(con))
239 # capture try() messages
240 opts = if (is.null(getOption('try.outFile'))) options(try.outFile = con)
241 sink(con); on.exit({ sink(); close(con); options(opts) })
242 expr # lazy evaluation
243 on.exit() # if no error occurred, clear up previous on-exit calls
244 sink(); out = rawToChar(rawConnectionValue(con)); close(con); options(opts)
245 out = strsplit(out, '\n', fixed = TRUE)[[1]]
246 if (length(out)) add_result(out, 'output')
247 expr
248 }
249 # disable ANSI sequences in text output
250 opts = options(cli.num_colors = 1); on.exit(options(opts), add = TRUE)
251 n = length(codes)
252 for (i in seq_len(n)) {
253 add_result(code <- codes[[i]], 'source')
254 expr = parse_only(code)
255 if (length(expr) == 0) next
256 # evaluate the code and capture output
257 out = handle_output(handle_eval(withVisible(eval(expr, envir))))
258 # verbose = 1: always print the last value; verbose = 2: print all values
259 if (verbose == 2 || (verbose == 1 && i == n)) {
260 # make invisible values visible unless they are NULL (which is often not useful)
261 if (!is_error(out) && !out$visible && !is.null(out$value)) out$visible = TRUE
262 }
263 # print value (via record_print()) if visible
264 if (!is_error(out) && out$visible) {
265 val = out$value
266 # if val is data.table, check if it needs to be printed
267 if (inherits(val, 'data.table') && 'data.table' %in% loadedNamespaces() &&
268 !data.table::shouldPrint(val)) next
269 if (is.null(print)) print = record_print
270 if (!is.function(print)) print = record_print.default
271 p_args = print.args
272 # index print args by first class of out unless args are wrapped in I()
273 if (!inherits(p_args, 'AsIs')) p_args = p_args[[class(val)[1]]]
274 out = handle_eval(if (length(p_args) == 0) print(val) else do.call(
275 print, c(list(val), p_args), quote = inherits(val, c('name', 'call'))
276 ))
277 if (length(out) && !is_error(out)) {
278 if (is.list(out)) lapply(out, add_result) else add_result(out)
279 }
280 }
281 handle_plot()
282 }
283 # shut off the device to write out the last plot if there exists one
284 dev_off()
285 handle_plot(TRUE)
286
287 # filter plots
288 if (!isTRUE(dev.keep)) {
289 p = get_plots() # all plots
290 if (identical(dev.keep, 'last')) dev.keep = length(p)
291 d = setdiff(p, p[dev.keep]) # plots to be deleted
292 if (length(d)) {
293 for (i in seq_along(res)) {
294 if (!inherits(r <- res[[i]], 'record_plot') || all(is.na(k <- match(d, r)))) next
295 r2 = r[-k[!is.na(k)]] # remove plots matching d
296 attributes(r2) = attributes(r) # preserve class
297 res[[i]] = r2
298 }
299 file.remove(d)
300 }
301 }
302
303 # remove empty blocks
304 res = Filter(length, res)
305 res = merge_record(res)
306
307 new_result(res)
308 }
309
310 # merge neighbor elements of the same class
311 merge_record = function(x) {
312 n = length(x)
313 if (n <= 1) return(x)
314 k = NULL
315 for (i in 2:n) {
316 r1 = x[[i - 1]]; c1 = class(r1); r2 = x[[i]]; c2 = class(r2)
317 if (!identical(c1, c2)) next
318 # concatenate messages to a single string (consider message(appendLF = FALSE))
319 x[[i]] = if ('record_message' %in% c1) paste(c(r1, r2), collapse = '') else c(r1, r2)
320 attributes(x[[i]]) = attributes(r1)
321 k = c(k, i - 1)
322 }
323 if (length(k)) x = x[-k]
324 x
325 }
326
327 #' Print methods for `record()`
328 #'
329 #' An S3 generic function to be called to print visible values in code when the
330 #' code is recorded by [record()]. It is similar to [knitr::knit_print()]. By
331 #' default, it captures the normal [print()] output and returns the result as a
332 #' character vector. The `knitr_kable` method is for printing [knitr::kable()]
333 #' output. Users and package authors can define other S3 methods to extend this
334 #' function.
335 #' @param x For `record_print()`, the value to be printed. For `new_record()`, a
336 #' character vector to be included in the printed results.
337 #' @param ... Other arguments to be passed to `record_print()` methods.
338 #' @return A `record_print()` method should return a character vector or a list
339 #' of character vectors. The original classes of the vector will be discarded,
340 #' and the vector will be treated as console output by default (i.e.,
341 #' `new_record(class = "output")`). If it should be another type of output,
342 #' wrap the vector in [new_record()] and specify a class name.
343 #' @export
344 record_print = function(x, ...) {
345 UseMethod('record_print')
346 }
347
348 #' @rdname record_print
349 #' @export
350 record_print.default = function(x, ...) {
351 # the default print method is just print()/show()
352 capture.output(if (isS4(x)) methods::show(x, ...) else print(x, ...))
353 }
354
355 #' @rdname record_print
356 #' @export
357 record_print.record_asis = function(x, ...) {
358 x
359 }
360
361 #' @param class A class name. Possible values are `xfun:::.record_cls`.
362 #' @rdname record_print
363 #' @export
364 new_record = function(x, class) structure(x, class = paste0('record_', class))
365
366 # all possible classes for record() results at the moment
367 .record_cls = c('source', 'output', 'message', 'warning', 'error', 'plot', 'asis')
368 .record_classes = paste0('record_', .record_cls)
369
370 # default device arguments
371 dev_args = list(units = 'in', onefile = FALSE, width = 8, height = 8, res = 84)
372
373 dev_open = function(dev, file, args) {
374 m = names(formals(dev))
375 for (i in names(dev_args)) {
376 if (i %in% m && is.null(args[[i]])) args[[i]] = dev_args[[i]]
377 }
378 n = length(dev.list())
379 do.call(dev, c(list(file), args))
380 if (length(dev.list()) <= n) stop('Failed to open device for recording plots.')
381 dev.control('enable')
382 dev.cur()
383 }
384
385 # infer the filename extension from a device's first argument
386 dev_ext = function(dev) {
387 # the first argument could be a string or an expression
388 if (!is.character(name <- formals(dev)[[1]])) name = gsub('"', '', deparse(name))
389 file_ext(name)
390 }
391
392 # test if a recorded plot is empty
393 empty_plot = function(p) {
394 xs = lapply(p[[1]], function(x) x[[2]][[1]])
395 for (x in xs) {
396 if ('name' %in% names(x)) {
397 # base graphics
398 if (!x$name %in% empty_calls) return(FALSE)
399 } else if (is.call(x)) {
400 # grid graphics
401 if (!identical(as.character(x[[1]]), 'requireNamespace')) return(FALSE)
402 }
403 }
404 TRUE
405 }
406
407 empty_calls = c(
408 'C_clip', 'C_layout', 'C_par', 'C_plot_window', 'C_strHeight', 'C_strWidth',
409 'palette', 'palette2'
410 )
411
412 is_error = function(x) inherits(x, 'try-error')
413
414 #' @param to The output format (text, markdown, or html).
415 #' @param encode For HTML output, whether to base64 encode plots.
416 #' @param template For HTML output, whether to embed the formatted results in an
417 #' HTML template. Alternatively, this argument can take a file path, i.e.,
418 #' path to an HTML template that contains the variable `$body$`. If `TRUE`,
419 #' the default template in this package will be used
420 #' (`xfun:::pkg_file('resources', 'record.html')`).
421 #' @rdname record
422 #' @exportS3Method
423 #' @return The `format()` method returns a character vector of plain-text output
424 #' or HTML code for displaying the results.
425 format.xfun_record_results = function(
426 x, to = c('text', 'markdown', 'html'), encode = FALSE, template = FALSE, ...
427 ) {
428 alt = 'A plot recorded by xfun::record()'
429 if (to[1] != 'html') {
430 is_md = to[1] == 'markdown'
431 res = unlist(lapply(x, function(z) {
432 if (length(z) == 0) return()
433 cls_all = sub('^record_', '', class(z)); cls = cls_all[1]
434 if (cls != 'asis') {
435 if (is_md && cls == 'plot') {
436 z = sprintf('![%s](<%s>)', alt, z)
437 } else {
438 o = attr2(z, 'opts'); a = o$attr
439 z = gsub('^(\\s*\n)+|\n\\s*$', '', one_string(z)) # trim blank lines
440 if (cls != 'source') z = paste0(o$comment %||% '#> ', split_lines(z))
441 if (is_md) {
442 cls_all = if (any(c('message', 'warning', 'error') %in% cls_all)) {
443 c('plain', cls_all)
444 } else if (cls == 'source') {
445 replace(cls_all, cls_all == 'source', 'r')
446 } else {
447 if (length(a)) a = c(sub('^[.]', '', a), 'plain')
448 setdiff(c(a, cls_all), 'output')
449 }
450 z = fenced_block(z, sprintf('.%s', cls_all))
451 }
452 }
453 }
454 z = one_string(z)
455 if (!is_md) z = gsub('\n*$', '\n', z)
456 z
457 }))
458 return(raw_string(res, lang = if (is_md) '.md'))
459 }
460 res = unlist(lapply(x, function(z) {
461 cls = sub('^record_', '', class(z))
462 if (cls == 'asis') z else if (cls == 'plot') {
463 sprintf(
464 '<p class="%s"><img src="%s" alt="%s" /></p>',
465 cls, if (encode) vapply(z, base64_uri, '') else URLencode(z), alt
466 )
467 } else {
468 paste0(
469 sprintf(
470 '<pre class="%s"><code>',
471 if (cls == 'source') paste0('language-r" data-start="', attr2(z, 'lines')[1]) else cls
472 ),
473 html_escape(one_string(z)), '</code></pre>'
474 )
475 }
476 }))
477 if (isTRUE(template)) template = pkg_file('resources', 'record.html')
478 if (is.character(template)) {
479 res = sub('$body$', one_string(res), read_utf8(template), fixed = TRUE)
480 if (length(x) > 0) res = sub('$title$', make_title(x[[1]]), res, fixed = TRUE)
481 }
482 raw_string(res, lang = '.html')
483 }
484
485 # generate a title from the first line of a character vector
486 make_title = function(x) {
487 if (length(x) == 0) return('')
488 x = gsub('^#+\\s*', '', x[1]) # remove possible comment chars
489 x = gsub('\\s*[.]*$', '... | ', x) # add ... to the end
490 html_escape(x)
491 }
492
493 #' @param x An object returned by `record()`.
494 #' @param browse Whether to browse the results on an HTML page.
495 #' @param ... Currently ignored.
496 #' @rdname record
497 #' @exportS3Method
498 #' @return The `print()` method prints the results as plain text or HTML to the
499 #' console or displays the HTML page.
500 print.xfun_record_results = function(
501 x, browse = interactive(), to = if (browse) 'html' else 'text', template = TRUE, ...
502 ) {
503 res = format(x, to, encode = browse, template = template, ...)
504 if (browse && to == 'html') {
505 viewer = getOption('viewer', utils::browseURL)
506 f = tempfile('record-', fileext = '.html')
507 write_utf8(res, f)
508 viewer(f)
509 } else {
510 cat(res, sep = '\n')
511 }
512 invisible(x)
513 }