Debian Codegraph @

R/html_resources.R

raw
1 #' Find External Resource References
2 #'
3 #' Given an R Markdown document or HTML file, attempt to determine the set of
4 #' additional files needed in order to render and display the document.
5 #'
6 #' This routine applies heuristics in order to scan a document for
7 #' possible resource references.
8 #'
9 #' In R Markdown documents, it looks for references to files implicitly
10 #' referenced in Markdown (e.g. \code{![alt](img.png)}), in the document's
11 #' YAML header, in raw HTML chunks, and as quoted strings in R code chunks
12 #' (e.g. \code{read.csv("data.csv")}).
13 #'
14 #' Resources specified explicitly in the YAML header for R Markdown
15 #' documents are also returned. To specify resources in YAML, use the
16 #' \code{resource_files} key:
17 #'
18 #' \preformatted{---
19 #' title: My Document
20 #' author: My Name
21 #' resource_files:
22 #' - data/mydata.csv
23 #' - images/figure.png
24 #' ---}
25 #'
26 #' Each item in the \code{resource_files} list can refer to:
27 #' \enumerate{
28 #' \item A single file, such as \code{images/figure.png}, or
29 #' \item A directory, such as \code{resources/data}, in which case all of the
30 #' directory's content will be recursively included, or
31 #' \item A wildcard pattern, such as \code{data/*.csv}, in which case all of
32 #' the files matching the pattern will be included. No recursion is done in
33 #' this case.
34 #' }
35 #'
36 #' In HTML files (and raw HTML chunks in R Markdown documents), this routine
37 #' searches for resources specified in common tag attributes, such as
38 #' \code{<img src="...">}, \code{<link href="...">}, etc.
39 #'
40 #' In all cases, only resources that exist on disk and are contained in the
41 #' document's directory (or a child thereof) are returned.
42 #' @param input_file path to the R Markdown document or HTML file to process
43 #' @inheritParams render
44 #' @return A data frame with the following columns:
45 #' \describe{
46 #' \item{path}{The relative path from the document to the resource}
47 #' \item{explicit}{Whether the resource was specified explicitly
48 #' (\code{TRUE}) or discovered implicitly (\code{FALSE})}
49 #' \item{web}{Whether the resource is needed to display a Web page rendered
50 #' from the document}
51 #' }
52 #' @export
53 find_external_resources <- function(input_file, encoding = 'UTF-8') {
54
55 # ensure we're working with valid input
56 ext <- tolower(xfun::file_ext(input_file))
57 if (!(ext %in% c("md", "rmd", "qmd", "html", "htm", "r", "css"))) {
58 stop("Resource discovery is only supported for R Markdown, Quarto files or HTML (and CSS) files.")
59 }
60
61 if (!file.exists(input_file)) {
62 stop("The input file file '", input_file, "' does not exist.")
63 }
64
65 # set up the frame we'll use to report results
66 discovered_resources <- data.frame(
67 path = character(0), explicit = logical(0), web = logical(0)
68 )
69
70 input_dir <- dirname(normalize_path(input_file))
71
72 # discover a single resource--tests a string to see if it corresponds to a
73 # resource on disk; if so, adds it to the list of known resources and returns
74 # TRUE
75 discover_single_resource <- function(path, explicit, web) {
76
77 if (!(is.character(path) && length(path) == 1 && path != "." && path != ".." &&
78 file.exists(file.path(input_dir, path))))
79 return(FALSE)
80
81 ext <- tolower(xfun::file_ext(file.path(input_dir, path)))
82
83 if (identical(ext, "r")) {
84 # if this is a .R script, look for resources it contains, too
85 discover_r_resources(file.path(input_dir, path), discover_single_resource)
86 } else if (identical(ext, "css")) {
87 # if it's a CSS file, look for files it references (e.g. fonts/images)
88 discover_css_resources(file.path(input_dir, path), discover_single_resource)
89 }
90 # if this is an implicitly discovered resource, it needs to refer to
91 # a file rather than a directory
92 if (!explicit && dir_exists(file.path(input_dir, path))) {
93 return(FALSE)
94 }
95
96 # this looks valid; remember it
97 discovered_resources <<- rbind(discovered_resources, data.frame(
98 path = path, explicit = explicit, web = web, stringsAsFactors = FALSE
99 ))
100 TRUE
101 }
102
103 # run the main resource discovery appropriate to the file type
104 if (ext %in% c("md", "rmd", "qmd")) {
105 # discover R Markdown doc resources--scans the document itself as described
106 # in comments above, renders as Markdown, and invokes HTML discovery
107 # on the result
108 discover_rmd_resources(input_file, discover_single_resource)
109 } else if (ext %in% c("htm", "html")) {
110 # discover HTML resources
111 discover_html_resources(input_file, discover_single_resource)
112
113 # if the HTML file represents a rendered R Markdown document, it may have a
114 # sidecar _files folder; include that if it's present
115 sidecar_files_dir <- knitr_files_dir(input_file)
116 files_dir_info <- file.info(sidecar_files_dir)
117 if (isTRUE(files_dir_info$isdir)) {
118 # we probably auto-discovered some resources from _files--exclude those
119 # since they'll be covered by the directory
120 files_dir_prefix <- file.path(basename(sidecar_files_dir), "")
121 files_dir_matches <- substr(
122 discovered_resources$path, 1, nchar(files_dir_prefix)
123 ) == files_dir_prefix
124 discovered_resources <- discovered_resources[!files_dir_matches, , drop = FALSE]
125
126 # add the directory itself
127 discovered_resources <- rbind(discovered_resources, data.frame(
128 path = files_dir_prefix, explicit = FALSE, web = TRUE,
129 stringsAsFactors = FALSE)
130 )
131 }
132 } else if (ext == "r") {
133 discover_r_resources(input_file, discover_single_resource)
134 } else if (ext == "css") {
135 discover_css_resources(input_file, discover_single_resource)
136 }
137
138 # clean row names (they're not meaningful)
139 rownames(discovered_resources) <- NULL
140
141 # convert paths from factors if necessary, and clean any redundant ./ leaders
142 discovered_resources$path <- as.character(discovered_resources$path)
143 has_prefix <- grepl("^\\./", discovered_resources$path)
144 discovered_resources$path[has_prefix] <- substring(discovered_resources$path[has_prefix], 3)
145
146 discovered_resources
147 }
148
149 # discovers resources in a single HTML file
150 discover_html_resources <- function(html_file, discover_single_resource) {
151 # resource accumulator
152 discover_resource <- function(node, att, val, idx) {
153 res_file <- utils::URLdecode(val)
154 discover_single_resource(res_file, FALSE, TRUE)
155 }
156
157 # create a single string with all of the lines in the document
158 html_lines <- file_string(html_file)
159
160 # parse the HTML and invoke our resource discovery callbacks
161 call_resource_attrs(html_lines, discover_resource)
162 }
163
164 # discovers resources in a single R Markdown document
165 discover_rmd_resources <- function(rmd_file, discover_single_resource) {
166
167 # create a UTF-8 encoded Markdown file to serve as the resource discovery
168 # source
169 md_file <- tempfile(fileext = ".md")
170 input_dir <- dirname(normalize_path(rmd_file))
171 output_dir <- dirname(md_file)
172 rmd_content <- read_utf8(rmd_file)
173 if (length(i <- grep('^---\\s*$', rmd_content)) >= 2 && i[1] == 1) {
174 rmd_content <- append(rmd_content, 'citeproc: false', i[2] - 1)
175 }
176 write_utf8(rmd_content, md_file)
177
178 # create a vector of temporary files; anything in here
179 # will be cleaned up on exit
180 temp_files <- md_file
181 on.exit(unlink(temp_files, recursive = TRUE), add = TRUE)
182
183 # discovers render-time resources; if any are found, adds them to the list of
184 # discovered resources and copies them alongside the input document.
185 discover_render_resource <- function(output_render_file) {
186 if (discover_single_resource(output_render_file, FALSE, FALSE)) {
187 # mirror original directory structure so we don't need to mutate input
188 # prior to render
189 output_target_file <- file.path(output_dir, output_render_file)
190 if (!file.exists(dirname(output_target_file))) {
191 dir.create(dirname(output_target_file), showWarnings = FALSE, recursive = TRUE)
192 }
193
194 # copy the original resource to the temporary render folder
195 file.copy(file.path(input_dir, output_render_file), output_target_file)
196
197 # clean up this file when we're done
198 temp_files <<- c(temp_files, output_target_file)
199 }
200 }
201
202 # parse the YAML front matter to discover resources named there
203 front_matter <- yaml_front_matter(md_file)
204
205 # Check for content referred to by output format calls to the includes
206 # function (for generating headers/footers/etc. at render time), and for
207 # references to files in pandoc arguments.
208 #
209 # These will be needed to produce even a vanilla Markdown variant of the input
210 # document, so copy them to the temporary folder in preparation for rendering
211 # (in addition to marking them as required resources).
212 output_formats <- front_matter[["output"]]
213 if (is.list(output_formats)) {
214 for (output_format in output_formats) {
215 if (is.list(output_format)) {
216 output_render_files <- unlist(output_format[c(
217 'includes', 'pandoc_args', 'logo', 'reference_doc', 'reference_docx', 'template'
218 )])
219 resolved_theme <- tryCatch(resolve_theme(output_format[["theme"]]), error = function(e) NULL)
220 # css needs to be copied for sass or bslib processing in formate rendering
221 needed <- if (is_bs_theme(resolved_theme)) TRUE else {
222 needs_sass(output_format[['css']])
223 }
224 output_render_files <- c(output_render_files, output_format[['css']][needed])
225
226 lapply(output_render_files, discover_render_resource)
227 }
228 }
229 }
230
231 # check for explicitly named resources
232 if (!is.null(front_matter$resource_files)) {
233 lapply(front_matter$resource_files, function(res) {
234 explicit_res <- if (is.character(res)) {
235 list(path = res, explicit = TRUE, web = is_web_file(res))
236 } else if (is.list(res) && length(names(res)) > 0) {
237 # list--happens when web flag is specified explicitly in YAML.
238 list(path = names(res)[[1]],
239 explicit = TRUE,
240 web = if (is.null(res$web)) is_web_file(res) else res$web)
241 }
242
243 # check the extracted filename to see if it exists
244 if (!is.null(explicit_res)) {
245 if (grepl("*", explicit_res$path, fixed = TRUE)) {
246 # if the resource file spec includes a wildcard, list the files
247 # that match the pattern
248 files <- list.files(
249 file.path(input_dir, dirname(explicit_res$path)),
250 utils::glob2rx(basename(explicit_res$path))
251 )
252 lapply(files, function(f) discover_single_resource(
253 file.path(dirname(explicit_res$path), f), TRUE, web = is_web_file(f)
254 ))
255 } else {
256 # no wildcard, see whether this resource refers to a directory or to
257 # an individual file
258 info <- file.info(file.path(input_dir, explicit_res$path))
259 if (is.na(info$isdir)) {
260 # implies that the file doesn't exist (should we warn here?)
261 NULL
262 } else if (isTRUE(info$isdir)) {
263 # if the resource file spec is a directory, include all the files in
264 # the directory, recursively
265 files <- list.files(
266 file.path(input_dir, explicit_res$path), recursive = TRUE
267 )
268 lapply(files, function(f) discover_single_resource(
269 file.path(explicit_res$path, f), TRUE, web = is_web_file(f)
270 ))
271 } else {
272 # isdir is false--this is an individual file; return it
273 discover_single_resource(explicit_res$path, explicit_res$explicit, explicit_res$web)
274 }
275 }
276 } else {
277 discover_single_resource(explicit_res$path, explicit_res$explicit, explicit_res$web)
278 }
279 })
280 }
281
282 # check for a 'preview' yaml metadata entry
283 if (!is.null(front_matter[["preview"]])) {
284 discover_single_resource(front_matter[["preview"]], explicit = FALSE, web = TRUE)
285 }
286
287 # check for bibliography and csl files at the top level
288 for (bibfile in c("bibliography", "csl")) {
289 lapply(front_matter[[bibfile]], discover_render_resource)
290 }
291
292 # check for parameter values that look like files.
293 if (!is.null(front_matter$params)) {
294 # This is the raw parameter information and has not had any YAML tag
295 # processing performed. See `knitr:::resolve_params`.
296 lapply(front_matter$params, function(param) {
297 if (is.list(param)) {
298 if (identical(param$input, "file")) {
299 if (!is.null(param$value)) {
300 # We treat param filenames as non-web resources.
301 discover_single_resource(param$value, TRUE, FALSE)
302 }
303 }
304 }
305 })
306 }
307
308 # check for knitr child documents in R Markdown documents
309 if (tolower(xfun::file_ext(rmd_file)) %in% c("qmd", "rmd")) {
310 chunk_lines <- gregexpr(knitr::all_patterns$md$chunk.begin, rmd_content, perl = TRUE)
311 for (idx in seq_along(chunk_lines)) {
312 chunk_line <- chunk_lines[idx][[1]]
313 if (is.na(chunk_line) || chunk_line < 0) next
314 chunk_start <- attr(chunk_line, "capture.start", exact = TRUE) + 1
315 chunk_text <- substr(
316 rmd_content[idx], chunk_start,
317 chunk_start + attr(chunk_line, "capture.length", exact = TRUE) - 2
318 )
319 for (child_expr in c("\\bchild\\s*=\\s*(?:c\\()?'([^']+)'\\)?", "\\bchild\\s*=\\s*(?:c\\()?\"([^\"]+)\"\\)?")) {
320 child_match <- gregexpr(child_expr, chunk_text, perl = TRUE)[[1]]
321 if (child_match > 0) {
322 child_start <- attr(child_match, "capture.start", exact = TRUE)
323 child_text <- substr(
324 chunk_text, child_start,
325 child_start + attr(child_match, "capture.length", exact = TRUE) - 1
326 )
327 discover_render_resource(child_text)
328 }
329 }
330 }
331 }
332
333 # render "raw" markdown to HTML
334 html_file <- tempfile(fileext = ".html")
335 on.exit(unlink(html_file), add = TRUE)
336
337 # check to see what format this document is going to render as; if it's a
338 # format that produces HTML, let it render as-is, but if it isn't, render as
339 # html_document to pick up dependencies
340 output_format <- output_format_from_yaml_front_matter(rmd_content)
341
342 output_format_function <- eval(xfun::parse_only(output_format$name))
343
344 override_output_format <- if (!is_pandoc_to_html(output_format_function()$pandoc)) "html_document"
345
346 html_file <- render(
347 md_file, override_output_format, html_file, quiet = TRUE,
348 output_options = list(
349 self_contained = FALSE,
350 pandoc_args = c("--metadata", "pagetitle=PREVIEW")
351 )
352 )
353
354 # clean up output file and its supporting files directory
355 temp_files <- c(temp_files, html_file, knitr_files_dir(md_file), knitr_files_dir(html_file))
356
357 # run the HTML resource discovery mechanism on the rendered output
358 discover_html_resources(html_file, discover_single_resource)
359
360 # if this is an R Markdown file, purl the file to extract just the R code
361 if (tolower(xfun::file_ext(rmd_file)) %in% c("qmd", "rmd")) {
362 r_file <- tempfile(fileext = ".R")
363 # suppress possible try() errors https://github.com/rstudio/rmarkdown/issues/1247
364 try_file <- tempfile()
365 opts <- options(try.outFile = try_file)
366 on.exit({
367 unlink(c(r_file, try_file)); options(opts)
368 }, add = TRUE)
369 knitr::purl(md_file, output = r_file, quiet = TRUE, documentation = 0)
370 temp_files <- c(temp_files, r_file)
371 discover_r_resources(r_file, discover_single_resource)
372 }
373 }
374
375 discover_r_resources <- function(r_file, discover_single_resource) {
376
377 # read the lines from the R file
378 r_lines <- read_utf8(r_file)
379
380 # clean comments from the R code (simply; consider: # inside strings)
381 r_lines <- sub("#.*$", "", r_lines)
382
383 # find quoted strings in the code and attempt to ascertain whether they are
384 # files on disk
385 r_lines <- one_string(r_lines)
386 quoted_strs <- Reduce(c, lapply(c("\"[^\"\n]*\"", "'[^'\n]*'"), function(pat) {
387 matches <- unlist(regmatches(r_lines, gregexpr(pat, r_lines)))
388 substr(matches, 2, nchar(matches) - 1)
389 }))
390
391 # consider any quoted string containing a valid relative path to a file that
392 # exists on disk to be a reference
393 for (quoted_str in quoted_strs) {
394 if (nchar(quoted_str) > 0)
395 discover_single_resource(quoted_str, FALSE, is_web_file(quoted_str))
396 }
397 }
398
399 # copies the external resources needed to render original_input into
400 # intermediates_dir; with skip_web, skips web resources. returns a character
401 # vector containing paths to all resources copied.
402 copy_render_intermediates <- function(original_input, intermediates_dir, skip_web) {
403
404 # start with an empty set of intermediates
405 intermediates <- c()
406
407 # extract all the resources used by the input file; note that this actually
408 # runs another (non-knitting) render, and that recursion is avoided because
409 # we explicitly render with self-contained = FALSE while discovering
410 # resources
411 resources <- find_external_resources(original_input)
412 dest_dir <- normalize_path(intermediates_dir)
413 source_dir <- dirname(normalize_path(original_input))
414
415 # process each returned reosurce
416 by(resources, seq_len(nrow(resources)), function(res) {
417 # skip web resources if requested
418 if (skip_web && res$web) return()
419 dest <- copy_file_with_dir(res$path, dest_dir, source_dir)
420 intermediates <<- c(intermediates, dest)
421 })
422
423 # return the list of files we generated
424 intermediates
425 }
426
427 # copy a file from a relative path to a destination dir, and preserve its
428 # original dir structure, e.g., if we copy foo/bar.txt to /tmp, the destination
429 # file should be /tmp/foo/bar.txt instead of /tmp/bar.txt
430 copy_file_with_dir <- function(path, dest, from = '.') {
431 dest <- file.path(dest, path)
432 path <- file.path(from, path)
433 if (!file.exists(path)) return()
434 if (!dir_exists(dirname(dest))) dir.create(dirname(dest), recursive = TRUE)
435 file.copy(path, dest)
436 dest
437 }
438
439 discover_css_resources <- function(css_file, discover_single_resource) {
440
441 css_lines <- read_utf8(css_file)
442
443 discover_resource <- function(node, att, val, idx) {
444 res_file <- utils::URLdecode(val)
445 discover_single_resource(res_file, FALSE, TRUE)
446 }
447
448 call_css_resource_attrs(one_string(css_lines), discover_resource)
449 }
450
451 # given a filename, return true if the file appears to be a web file
452 is_web_file <- function(filename) {
453 tolower(xfun::file_ext(filename)) %in% c(
454 "css", "gif", "htm", "html", "jpeg", "jpg", "js", "mp3", "mp4", "png", "wav"
455 )
456 }