Skip to content

Instantly share code, notes, and snippets.

@curtisalexander
Last active November 26, 2017 12:43
Show Gist options
  • Save curtisalexander/61de671c6b04980935736dc2d07ed16c to your computer and use it in GitHub Desktop.
Save curtisalexander/61de671c6b04980935736dc2d07ed16c to your computer and use it in GitHub Desktop.
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