only knit rmd files to md if they have changed
[rnaseq-cwl-training.git] / bin / generate_md_episodes.R
1 generate_md_episodes <- function() {
2
3     library("methods")
4     
5     if (require("knitr") && packageVersion("knitr") < '1.9.19')
6         stop("knitr must be version 1.9.20 or higher")
7
8     if (!require("stringr"))
9         stop("The package stringr is required for generating the lessons.")
10
11     if (require("checkpoint") && packageVersion("checkpoint") >=  '0.4.0') {
12         required_pkgs <-
13              checkpoint:::scanForPackages(project = "_episodes_rmd",
14                                           verbose=FALSE, use.knitr = TRUE)$pkgs
15     } else {
16         stop("The checkpoint package (>= 0.4.0) is required to build the lessons.")
17     }
18
19     missing_pkgs <- required_pkgs[!(required_pkgs %in% rownames(installed.packages()))]
20
21     if (length(missing_pkgs)) {
22         message("Installing missing required packages: ",
23                 paste(missing_pkgs, collapse=", "))
24         install.packages(missing_pkgs)
25     }
26
27     ## get the Rmd file to process from the command line, and generate the path for their respective outputs
28     args  <- commandArgs(trailingOnly = TRUE)
29     if (length(args) != 2){
30       stop("input and output file must be passed to the script")
31     }
32     
33     src_rmd <- args[1]
34     dest_md <- args[2]
35
36     ## knit the Rmd into markdown
37     knitr::knit(src_rmd, output = dest_md)
38
39     # Read the generated md files and add comments advising not to edit them
40     vapply(dest_md, function(y) {
41       con <- file(y)
42       mdfile <- readLines(con)
43       if (mdfile[1] != "---")
44         stop("Input file does not have a valid header")
45       mdfile <- append(mdfile, "# Please do not edit this file directly; it is auto generated.", after = 1)
46       mdfile <- append(mdfile, paste("# Instead, please edit", 
47                                      basename(y), "in _episodes_rmd/"), after = 2)
48       writeLines(mdfile, con)
49       close(con)
50       return(paste("Warning added to YAML header of", y))
51     },
52     character(1))
53 }
54
55 generate_md_episodes()