Skip to content

Instantly share code, notes, and snippets.

@curtisalexander
Last active November 14, 2017 21:18
Show Gist options
  • Save curtisalexander/d934449a093249d95802e45f513f5ddc to your computer and use it in GitHub Desktop.
Save curtisalexander/d934449a093249d95802e45f513f5ddc to your computer and use it in GitHub Desktop.
Run rmarkdown::render() 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-rmd.R --patt=<patt>
_watch-render-rmd.R -h | --help
Options:
--patt=<patt> File pattern
-h, --help Help
Examples:
_watch-render-rmd.R --patt=\"lesson_[[:digit:]]+.Rmd\"
_watch-render-rmd.R --patt=\".+\\.Rmd\"" -> doc
opts <- docopt::docopt(doc)
cwd <- getwd()
render <- function(added, deleted, modified) {
file_changed <- ""
write_and_bind_change <- function(f, txt) {
arg <- deparse(substitute(f))
writeLines(paste0("\nAt ", Sys.time(), " the file ", f, " was ", arg))
file_changed <<- f
}
if (length(added) > 0) {
write_and_bind_change(added)
}
if (length(deleted) > 0) {
write_and_bind_change(deleted)
}
if (length(modified) > 0) {
write_and_bind_change(modified)
}
writeLines(paste0("Re-rendering the document ", file_changed, " within ", cwd))
output <- rmarkdown::render(input = file_changed,
output_format = 'html_document',
encoding = 'UTF-8',
quiet = TRUE)
writeLines(paste0("At ", Sys.time(), " the document ", file_changed, " 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