Merge pull request #200 from mawds/commentgenerated
[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     ## find all the Rmd files, and generate the paths for their respective outputs
28     src_rmd <- list.files(pattern = "??-*.Rmd$", path = "_episodes_rmd", full.names = TRUE)
29     dest_md <- file.path("_episodes", gsub("Rmd$", "md", basename(src_rmd)))
30     
31     ## knit the Rmd into markdown
32     mapply(function(x, y) {
33         knitr::knit(x, output = y)
34     }, src_rmd, dest_md)
35     
36     # Read the generated md files and add comments advising not to edit them
37     vapply(dest_md, function(y) {
38       con <- file(y)
39       mdfile <- readLines(con)
40       if (mdfile[1] != "---")
41         stop("Input file does not have a valid header")
42       mdfile <- append(mdfile, "# Please do not edit this file directly; it is auto generated.", after = 1)
43       mdfile <- append(mdfile, paste("# Instead, please edit", 
44                                      basename(y), "in _episodes_rmd/"), after = 2)
45       writeLines(mdfile, con)
46       close(con)
47       return(paste("Warning added to YAML header of", y))
48     },
49     character(1))
50 }
51
52 generate_md_episodes()