Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Run rmarkdown::render_site() when files that match a pattern change within a directory
#!/usr/local/bin/Rscript --no-site-file --no-init-file --no-restore
# --vanilla ==> --no-site-file --no-init-file --no-restore --no-environ
# thus the above reads the .Renviron file(s)
## required packages ==
# install.packages(c("docopt",
# "testthat"))
## docopt.org ==
"Usage:
_watch-render-site.R --patt=<patt>
_watch-render-site.R -h | --help
Options:
--patt=<patt> File pattern
-h, --help Help
Example:
_watch-render-site.R --patt=\"lesson_[[:digit:]]+.Rmd\"
_watch-render-site.R --patt=\".+\\.Rmd\"" -> doc
opts <- docopt::docopt(doc)
cwd <- getwd()
render <- function(added, deleted, modified) {
write_change <- function(f, txt) {
arg <- deparse(substitute(f))
writeLines(paste0("\nAt ", format(Sys.time(), tz = "US/Central"), " the file ", f, " was ", arg))
}
if (length(added) > 0) {
write_change(added)
}
if (length(deleted) > 0) {
write_change(deleted)
}
if (length(modified) > 0) {
write_change(modified)
}
writeLines(paste0("Re-rendering the site within ", cwd))
output <- rmarkdown::render_site(input = cwd,
encoding = 'UTF-8',
quiet = TRUE)
writeLines(paste0("At ", format(Sys.time(), tz = "US/Central"), " the site completed rendering: ", cwd, "/", output))
writeLines(paste0("\n----------\n"))
writeLines(paste0("Watching the directory ", cwd, " for \n * additions\n * deletions\n * modifications"))
# return TRUE to keep watching; FALSE to stop watching
TRUE
}
writeLines(paste0("Watching the directory ", cwd, " for \n * additions\n * deletions\n * modifications"))
testthat::watch(path = cwd,
pattern = opts$patt,
callback = render)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment