Debian Codegraph @

R/render_site.R

raw
1 #' Render multiple documents as a website
2 #'
3 #' Render all of the R Markdown documents within a directory as a website.
4 #'
5 #' The \code{render_site} function enables you to render a collection of
6 #' markdown documents within a directory as a website. There are two
7 #' requirements for a directory to be rendered as a website:
8 #' \enumerate{
9 #' \item{It must contain either an "index.Rmd" or "index.md" file.}
10 #' \item{It must contain a site configuration file ("_site.yml").}
11 #' }
12 #'
13 #' The most minimal valid website is an empty "index.Rmd" and an empty
14 #' "_site.yml". With this configuration a single empty webpage would be
15 #' generated via a call to \code{render_site}. If you add additional markdown
16 #' documents to the directory they will also be rendered. By default a site is
17 #' rendered in the following fashion:
18 #'
19 #' \enumerate{
20 #' \item{R Markdown (.Rmd) and plain markdown (.md) files in the root
21 #' directory are rendered. Note however that markdown files beginning with "_"
22 #' are not rendered (this is a convention to designate files that are included
23 #' by top level documents).}
24 #' \item{All output and supporting files are copied to a "_site" subdirectory
25 #' of the website directory (this is configurable, see discussion below).}
26 #' \item{The following files are \bold{not} copied to the "_site"
27 #' sub-directory:
28 #' \itemize{
29 #' \item{Files beginning with "." (hidden files).}
30 #' \item{Files beginning with "_"}
31 #' \item{Files known to contain R source code (e.g. ".R", ".s", ".Rmd"), R
32 #' data (e.g. ".RData", ".rds"), configuration data (e.g. ".Rproj",
33 #' "rsconnect") or package project management data (e.g.
34 #' "packrat", "renv").}
35 #' }
36 #' Note that you can override which files are included or excluded via
37 #' settings in "_site.yml" (described below).}
38 #' \item{Normally R Markdown renders documents as self-contained HTML.
39 #' However, \code{render_site} ensures that dependencies (e.g. CSS,
40 #' JavaScript, images, etc.) remain in external files. CSS/JavaScript
41 #' libraries are copied to a "site_libs" sub-directory and plots/images are
42 #' copied to "_files" sub-directories.}
43 #' }
44 #'
45 #' You can remove the files generated by \code{render_site} using the
46 #' \code{clean_site} function.
47 #'
48 #' @section Configuration:
49 #' A "_site.yml" file can be used to configure the behavior of site generation.
50 #' Here is an example configuration file:
51 #'
52 #' \preformatted{
53 #' name: my-website
54 #' output_dir: _site
55 #' include: ["demo.R"]
56 #' exclude: ["docs.txt", "*.csv"]
57 #' navbar:
58 #' title: "My Website"
59 #' left:
60 #' - text: "Home"
61 #' href: index.html
62 #' - text: "About"
63 #' href: about.html
64 #' output:
65 #' html_document:
66 #' toc: true
67 #' highlight: textmate
68 #' }
69 #'
70 #' The \code{name} field provides a suggested URL path for your website when it
71 #' is published (by default this is just the name of the directory containing
72 #' the site). The \code{output_dir} indicates which directory to copy site
73 #' content into ("_site" is the default if none is specified). Note that this
74 #' can be "." to keep all content within the root website directory alongside
75 #' the source code.
76 #'
77 #' The \code{include} and \code{exclude} fields enable you to override the
78 #' default behavior vis-a-vis what files are copied into the "_site" directory
79 #' (wildcards can be used as in the above example).
80 #'
81 #' The \code{navbar} field can be used to define a navigation bar for websites
82 #' based on the \code{\link{html_document}} format.
83 #'
84 #' Finally, the \code{output} field enables you to specify output options that
85 #' are common to all documents within the website (you can also still provide
86 #' local options within each document that override any common options).
87 #'
88 #' \code{new_session: true} causes each file to be rendered in a new R session.
89 #' This prevents the masking problem that arises when different files use
90 #' functions from different packages (namespaces) that share a common name, such
91 #' as \code{here::here} and \code{lubridate::here} or \code{dplyr::filter} and
92 #' \code{MASS::filter}. The default behaviour of \code{render_site} is to use a
93 #' common R session.
94 #'
95 #' \code{autospin: true} causes \code{.R} files to be spinned and rendered
96 #' (as well as \code{.Rmd} files). If \code{autospin} is set to false (the default),
97 #' \code{.R} files will not be spinned nor rendered. \code{autospin} can also
98 #' enumerate a list of .R files to be spinned and rendered.
99 #'
100 #' @section Custom Site Generation:
101 #' The behavior of the default site generation function
102 #' (\code{rmarkdown::default_site}) is described above. It is also possible to
103 #' define a custom site generator that has alternate behavior. A site generator
104 #' is an R function that is bound to by including it in the "site:" field of the
105 #' "index.Rmd" or "index.md" file. For example:
106 #'
107 #' \preformatted{
108 #' title: "My Book"
109 #' output: bookdown::gitbook
110 #' site: bookdown::bookdown_site
111 #' }
112 #'
113 #' A site generation function should return a list with the following elements:
114 #' \describe{
115 #' \item{\code{name}:}{The name for the website (e.g. the parent directory
116 #' name).}
117 #' \item{\code{output_dir}:}{The directory where the website output is written
118 #' to. This path should be relative to the site directory (e.g. "." or
119 #' "_site")}
120 #' \item{\code{render}:}{An R function that can be called to generate the
121 #' site. The function should accept the \code{input_file},
122 #' \code{output_format}, \code{envir}, and \code{quiet} arguments.}
123 #' \item{\code{clean}:}{An R function that returns relative paths to the files
124 #' generated by \code{render_site} (these files are the ones which will be
125 #' removed by the \code{clean_site} function.}
126 #' \item{\code{subdirs} \emph{(optional)}:}{A logical flag that indicates if
127 #' the generator supports nested source files in subdirectories of the project
128 #' (\code{TRUE}) or only at the project root (\code{FALSE}). (e.g.
129 #' \code{blogdown:::blogdown_site()})}
130 #' }
131 #'
132 #' Note that the \code{input_file} argument will be \code{NULL} when the entire
133 #' site is being generated. It will be set to a specific file name if a
134 #' front-end tool is attempting to preview it (e.g. RStudio IDE via the Knit
135 #' button).
136 #'
137 #' When \code{quiet = FALSE} the \code{render} function should also print a line
138 #' of output using the \code{\link{message}} function indicating which output
139 #' file should be previewed, for example:
140 #'
141 #' \preformatted{if (!quiet)
142 #' message("\nOutput created: ", output)
143 #' }
144 #'
145 #' Emitting this line enables front-ends like RStudio to determine which file
146 #' they should open to preview the website.
147 #'
148 #' See the source code of the \code{rmarkdown::default_site} function for a
149 #' example of a site generation function.
150 #'
151 #' @param input Website directory (or the name of a file within the directory).
152 #' @param output_format R Markdown format to convert to (defaults to "all").
153 #' @param envir The environment in which the code chunks are to be evaluated
154 #' during knitting (can use \code{\link{new.env}} to guarantee an empty new
155 #' environment).
156 #' @param quiet \code{TRUE} to suppress messages and other output.
157 #' @inheritParams render
158 #'
159 #' @return \code{render_site} returns the name of the site output file (relative
160 #' to the input directory). \code{clean_site} returns the names of the
161 #' generated files removed during cleaning. \code{site_config} returns the
162 #' contents of _site.yml as an R list. \code{default_site_generator} returns
163 #' the default site generator for R Markdown websites.
164 #' @export
165 render_site <- function(input = ".",
166 output_format = "all",
167 envir = parent.frame(),
168 quiet = FALSE,
169 encoding = "UTF-8") {
170
171 # capture original input
172 original_input <- input
173
174 # normalize to a directory
175 input <- input_as_dir(input)
176
177 # if it's a file then capture that and force output_format to be NULL
178 # (to only render a single format for incremental/previewing)
179 input_file <- NULL
180 if (!dir_exists(original_input)) {
181 input_file <- original_input
182 if (output_format == "all")
183 output_format <- NULL
184 }
185
186 # find the site generator
187 generator <- site_generator(input, output_format)
188 if (is.null(generator))
189 stop("No site generator found.")
190
191 # execute it
192 generator$render(input_file = input_file,
193 output_format = output_format,
194 envir = envir,
195 quiet = quiet)
196
197 # compute the name of the output file. if the input was a filename
198 # use that as a base (otherwise use index.html)
199 if (!dir_exists(original_input))
200 output <- file_with_ext(basename(original_input), "html")
201 else
202 output <- "index.html"
203 output <- file.path(input, generator$output_dir, output)
204 output <- normalized_relative_to(input, output)
205
206 # return it invisibly
207 invisible(output)
208 }
209
210 #' @rdname render_site
211 #' @param preview Whether to list the files to be removed rather than actually
212 #' removing them. Defaulting to TRUE to prevent removing without notice.
213 #' @export
214 clean_site <- function(input = ".", preview = TRUE, quiet = FALSE,
215 encoding = "UTF-8") {
216
217 # normalize to a directory
218 input <- input_as_dir(input)
219
220 # find the site generator
221 generator <- site_generator(input, output_format = NULL)
222 if (is.null(generator))
223 stop("No site generator found.")
224
225 # get the files to be cleaned
226 files <- generator$clean()
227
228
229 if (length(files) == 0) {
230 if (preview || !quiet) cat("Nothing to removed. All clean !\n")
231 return(invisible(NULL))
232 }
233
234 # if it's just a preview then return the files, otherwise
235 # actually remove the files
236 if (preview) {
237 cat("These files and folders can probably be removed:\n",
238 paste0("* ", xfun::mark_dirs(files)),
239 "\nUse rmarkdown::clean_site(preview = FALSE) to remove them.",
240 sep = "\n")
241 } else {
242 if (!quiet) {
243 cat("Removing files: \n",
244 paste0("* ", xfun::mark_dirs(files)),
245 sep = "\n")
246 }
247 unlink(file.path(input, files), recursive = TRUE)
248 }
249 }
250
251 #' @rdname render_site
252 #' @export
253 site_generator <- function(input = ".", output_format = NULL) {
254 has_rproj <- function(dir) {
255 length(list.files(dir, "[.]Rproj$")) != 0
256 }
257 # look for the closest index file with 'site' metadata
258 root <- tryCatch(
259 proj_root(input, "^index.[rR]?md$", "^\\s*site:.*::.*$", has_rproj),
260 error = function(e) NULL
261 )
262
263 # normalize input
264 input <- input_as_dir(input)
265
266 # if none found then look for a _site.yml file
267 if (is.null(root)) {
268 if (file.exists(site_config_file(input))) {
269 return (default_site(input))
270 } else {
271 return(NULL)
272 }
273 }
274
275 # determine the index file (will be index.Rmd or index.md)
276 index <- xfun::existing_files(
277 file.path(root, xfun::with_ext("index", c("Rmd", "rmd"))),
278 first = TRUE, error = FALSE
279 )
280 if (length(index) == 0) index <- file.path(root, "index.md")
281
282 # is this in a subdir of the site root? (only some generators support this)
283 in_subdir <- !same_path(input, root)
284
285 # read index.Rmd and extract the front matter
286 front_matter <- yaml_front_matter(index)
287
288 # create the site generator (passing the root dir)
289 create_site_generator <- eval(xfun::parse_only(front_matter$site))
290 if (!is.function(create_site_generator)) stop(
291 "Cannot find the site generator from the 'site' field in YAML frontmatter ",
292 "of '", index, "'."
293 )
294 generator <- create_site_generator(root)
295
296 # if it's in a subdir check to see if the generator supports nested files
297 if (in_subdir) {
298 if (isTRUE(generator$subdirs)) {
299 generator
300 } else {
301 NULL
302 }
303 } else {
304 generator
305 }
306 }
307
308
309 #' @rdname render_site
310 #' @export
311 site_config <- function(input = ".", encoding = "UTF-8") {
312
313 # normalize input
314 input <- input_as_dir(input)
315
316 # check for config file
317 config_file <- site_config_file(input)
318 if (file.exists(config_file)) {
319
320 # parse the yaml
321 config_lines <- read_utf8(config_file)
322 config <- yaml_load(config_lines)
323 if (!is.list(config))
324 config <- list()
325
326 # provide defaults if necessary
327 if (is.null(config$name))
328 config$name <- basename(normalize_path(input))
329 if (is.null(config$output_dir))
330 config$output_dir <- "_site"
331 if (is.null(config$new_session))
332 config$new_session <- FALSE
333
334 # return config
335 config
336
337 # no _site.yml
338 } else {
339 NULL
340 }
341 }
342
343 # default site implementation (can be overridden by custom site generators)
344
345 #' @rdname render_site
346 #' @param output_format_filter An optional function which is passed the
347 #' input file and the output format, and which returns a (potentially
348 #' modified) output format.
349 #' @param ... Currently unused.
350 #' @export
351 default_site_generator <- default_site <- function(input, output_format_filter = NULL, ...) {
352
353 # get the site config
354 config <- site_config(input)
355 if (is.null(config))
356 stop("No site configuration (_site.yml) file found.")
357
358 # helper function to get all input files. includes all .Rmd and
359 # .md files that don't start with "_" (note that we don't do this
360 # recursively because rmarkdown in general handles applying common
361 # options/elements across subdirectories poorly). Also excludes
362 # README.R?md as those files are intended for GitHub. If
363 # config$autospin is TRUE, we also spin and render .R files.
364 input_files <- function() {
365 pattern <- sprintf(
366 "^[^_].*\\.%s$", if (isTRUE(config$autospin)) {
367 "([Rr]|[Rr]?md)"
368 } else {
369 "[Rr]?md"
370 }
371 )
372 files <- list.files(input, pattern)
373 if (is.character(config$autospin)) files <- c(files, config$autospin)
374 files[!grepl("^README\\.R?md$", files)]
375 }
376
377 # define render function (use ... to gracefully handle future args)
378 render <- function(input_file,
379 output_format,
380 envir,
381 quiet,
382 ...) {
383
384 # track outputs
385 outputs <- c()
386
387 # see if this is an incremental render
388 incremental <- !is.null(input_file)
389
390 # files list is either a single file (for incremental) or all
391 # file within the input directory
392 if (incremental)
393 files <- input_file
394 else {
395 files <- file.path(input, input_files())
396 }
397 sapply(files, function(x) {
398 render_one <- if (isTRUE(config$new_session)) {
399 render_new_session
400 } else {
401 render_current_session
402 }
403
404 # log the file being rendered
405 if (!quiet) message("\nRendering: ", x)
406
407 # optionally customize the output format via filter
408 file_output_format <- output_format
409 if (is.function(output_format_filter)) {
410 file_output_format <- output_format_filter(x, output_format)
411 }
412
413 output <- render_one(input = x,
414 output_format = file_output_format,
415 output_options = list(lib_dir = "site_libs",
416 self_contained = FALSE),
417 envir = envir,
418 quiet = quiet)
419
420 # add to global list of outputs
421 outputs <<- c(outputs, output)
422
423 # check for files dir and add that as well
424 sidecar_files_dir <- knitr_files_dir(output)
425 files_dir_info <- file.info(sidecar_files_dir)
426 if (isTRUE(files_dir_info$isdir))
427 outputs <<- c(outputs, sidecar_files_dir)
428 })
429
430 # do we have a relative output directory? if so then remove,
431 # recreate, and copy outputs to it (we don't however remove
432 # it for incremental builds)
433 if (config$output_dir != '.') {
434
435 # remove and recreate output dir if necessary
436 output_dir <- file.path(input, config$output_dir)
437 if (file.exists(output_dir)) {
438 if (!incremental) {
439 unlink(output_dir, recursive = TRUE)
440 dir.create(output_dir)
441 }
442 } else {
443 dir.create(output_dir)
444 }
445
446 # move outputs
447 for (output in outputs) {
448
449 # don't move it if it's a _files dir that has a _cache dir
450 if (grepl("^.*_files$", output)) {
451 cache_dir <- gsub("_files$", "_cache", output)
452 if (dir_exists(cache_dir))
453 next;
454 }
455
456 output_dest <- file.path(output_dir, basename(output))
457 if (dir_exists(output_dest))
458 unlink(output_dest, recursive = TRUE)
459 file.rename(output, output_dest)
460 }
461
462 # copy lib dir a directory at a time (allows it to work with incremental)
463 lib_dir <- file.path(input, "site_libs")
464 output_lib_dir <- file.path(output_dir, "site_libs")
465 if (!file.exists(output_lib_dir))
466 dir.create(output_lib_dir)
467 libs <- list.files(lib_dir)
468 for (lib in libs)
469 file.copy(file.path(lib_dir, lib), output_lib_dir, recursive = TRUE)
470 unlink(lib_dir, recursive = TRUE)
471
472 # copy other files
473 copy_site_resources(input)
474 }
475
476 # Print output created for rstudio preview
477 if (!quiet) {
478 # determine output file
479 output_file <- ifelse(is.null(input_file),
480 "index.html",
481 file_with_ext(basename(input_file), "html"))
482 if (config$output_dir != ".")
483 output_file <- file.path(config$output_dir, output_file)
484 message("\nOutput created: ", output_file)
485 }
486 }
487
488 # define clean function
489 clean <- function() {
490
491 # build list of generated files
492 generated <- c()
493
494 # enumerate rendered markdown files
495 files <- input_files()
496
497 # get html files
498 html_files <- file_with_ext(files, "html")
499
500 # _files peers are always removed (they could be here due to
501 # output_dir == "." or due to a _cache existing for the page)
502 html_supporting <- paste0(knitr_files_dir(html_files), '/')
503 generated <- c(generated, html_supporting)
504
505 # _cache peers are always removed
506 html_cache <- paste0(knitr_root_cache_dir(html_files), '/')
507 generated <- c(generated, html_cache)
508
509 # for rendering in the current directory we need to eliminate
510 # output files for our inputs (including _files) and the lib dir
511 if (config$output_dir == ".") {
512
513 # .html peers
514 generated <- c(generated, html_files)
515
516 # site_libs dir
517 generated <- c(generated, "site_libs/")
518
519 # for an explicit output_dir just remove the directory
520 } else {
521 generated <- c(generated, paste0(config$output_dir, '/'))
522 }
523
524 # filter out by existence
525 generated[file.exists(file.path(input, generated))]
526 }
527
528 # return site generator
529 list(
530 name = config$name,
531 output_dir = config$output_dir,
532 render = render,
533 clean = clean
534 )
535 }
536
537 # we suppress messages during render so that "Output created" isn't emitted
538 # (which could result in RStudio previewing the wrong file)
539 render_current_session <- function(...) suppressMessages(rmarkdown::render(...))
540
541 render_new_session <- function(...) {
542 xfun::Rscript_call(
543 function(...) { suppressMessages(rmarkdown::render(...)) },
544 args = list(...)
545 )
546 }
547
548 # utility function to copy all files into the _site directory
549 copy_site_resources <- function(input) {
550
551 # get the site config
552 config <- site_config(input)
553
554 if (config$output_dir != ".") {
555
556 # get the list of files
557 files <- copyable_site_resources(input = input, config = config)
558
559 # perform the copy
560 output_dir <- file.path(input, config$output_dir)
561 file.copy(from = file.path(input, files),
562 to = output_dir,
563 recursive = TRUE)
564 }
565 }
566
567
568
569 #' Determine website resource files for a directory
570 #'
571 #' Determine which files within a given directory should be copied in
572 #' order to serve a website from the directory. Attempts to automatically
573 #' exclude source, data, hidden, and other files not required to serve
574 #' website content.
575 #'
576 #' @param site_dir Site directory to analyze
577 #' @param include Additional files to include (glob wildcards supported)
578 #' @param exclude Files to exclude (glob wildcards supported)
579 #' @param recursive \code{TRUE} to return a full recursive file listing;
580 #' \code{FALSE} to just provide top-level files and directories.
581 #'
582 #' @return Character vector of files and directories to copy
583 #'
584 #' @export
585 site_resources <- function(site_dir, include = NULL, exclude = NULL, recursive = FALSE) {
586
587 # get the original file list (we'll need it to apply includes)
588 all_files <- list.files(site_dir, all.files = TRUE)
589
590 # excludes:
591 # - known source/data extensions
592 # - anything that starts w/ '.' or '_'
593 # - rsconnect, renv and packrat directories
594 # - user excludes
595 extensions <- c("R", "r", "S", "s",
596 "Rmd", "rmd", "md", "Rmarkdown", "rmarkdown",
597 "Rproj", "rproj",
598 "RData", "rdata", "rds")
599 extensions_regex <- utils::glob2rx(paste0("*.", extensions))
600 excludes <- c("^rsconnect$", "^packrat$", "^renv$", "^\\..*$", "^_.*$", "^.*_cache$",
601 extensions_regex,
602 utils::glob2rx(exclude))
603 files <- all_files
604 for (exclude in excludes)
605 files <- files[!grepl(exclude, files)]
606
607 # allow back in anything specified as an explicit "include"
608 includes <- utils::glob2rx(include)
609 for (include in includes) {
610 include_files <- all_files[grepl(include, all_files)]
611 files <- unique(c(files, include_files))
612 }
613
614 # if this is recursive then we need to blow out the directories
615 if (recursive) {
616 recursive_files <- c()
617 for (file in files) {
618 file_path <- file.path(site_dir, file)
619 if (dir_exists(file_path)) {
620 dir_files <- file.path(list.files(file_path,
621 full.names = FALSE,
622 recursive = TRUE))
623 dir_files <- file.path(file, dir_files)
624 recursive_files <- c(recursive_files, dir_files)
625 } else {
626 recursive_files <- c(recursive_files, file)
627 }
628 }
629 recursive_files
630 } else {
631 files
632 }
633 }
634
635
636 # utility function to list the files that should be copied
637 #
638 # NOTE: '...' is kept for backwards compatibility with older versions of
639 # RStudio which called 'copyable_site_resources(encoding = "UTF-8")'
640 copyable_site_resources <- function(input, config = site_config(input), ...) {
641
642 include <- config$include
643
644 exclude <- config$exclude
645 if (config$output_dir != ".")
646 exclude <- c(exclude, config$output_dir)
647
648 site_resources(input, include, exclude)
649 }
650
651
652
653
654 # utility function to ensure that 'input' is a valid directory
655 # (converts from file to parent directory as necessary)
656 input_as_dir <- function(input) {
657
658 # ensure the input dir exists
659 if (!file.exists(input)) {
660 input <- normalize_path(input, must_work = FALSE)
661 if (!file.exists(input)) {
662 stop2("The specified directory '", input, "' does not exist.")
663 }
664 }
665
666 # convert from file to directory if necessary
667 if (!dir_exists(input))
668 input <- dirname(input)
669
670 # return it
671 input
672 }
673
674 # get the path to the site config file
675 site_config_file <- function(input) {
676 file.path(input, "_site.yml")
677 }
678
679 site_skeleton <- function(path, ...) {
680 dir.create(path, recursive = TRUE, showWarnings = FALSE)
681 file.copy(
682 list.files(pkg_file('rmd', 'site'), full.names = TRUE),
683 path, overwrite = TRUE
684 )
685 }