Use renv (#462)
[rnaseq-cwl-training.git] / bin / generate_md_episodes.R
1 generate_md_episodes <- function() {
2
3   if (!requireNamespace("renv", quietly = TRUE)) {
4     install.packages("renv", repos = c(CRAN = "https://cloud.r-project.org/"))
5   }
6
7   if (!requireNamespace("rprojroot", quietly = TRUE)) {
8     install.packages("rprojroot", repos = c(CRAN = "https://cloud.r-project.org/"))
9   }
10
11   cfg  <- rprojroot::has_file_pattern("^_config.y*ml$")
12   root <- rprojroot::find_root(cfg)
13
14   required_pkgs <- unique(c(
15     ## Packages for episodes
16     renv::dependencies(file.path(root, "_episodes_rmd"), progress = FALSE, error = "ignore")$Package,
17     ## Pacakges for tools
18     renv::dependencies(file.path(root, "bin"), progress = FALSE, error = "ignore")$Package
19   ))
20
21   missing_pkgs <- setdiff(required_pkgs, rownames(installed.packages()))
22
23   if (length(missing_pkgs)) {
24     message("Installing missing required packages: ",
25             paste(missing_pkgs, collapse=", "))
26     install.packages(missing_pkgs)
27   }
28
29   if (require("knitr") && packageVersion("knitr") < '1.9.19')
30     stop("knitr must be version 1.9.20 or higher")
31
32   ## get the Rmd file to process from the command line, and generate the path
33   ## for their respective outputs
34   args  <- commandArgs(trailingOnly = TRUE)
35   if (!identical(length(args), 2L)) {
36     stop("input and output file must be passed to the script")
37   }
38
39   src_rmd <- args[1]
40   dest_md <- args[2]
41
42   ## knit the Rmd into markdown
43   knitr::knit(src_rmd, output = dest_md)
44
45   # Read the generated md files and add comments advising not to edit them
46   add_no_edit_comment <- function(y) {
47     con <- file(y)
48     mdfile <- readLines(con)
49     if (mdfile[1] != "---")
50       stop("Input file does not have a valid header")
51     mdfile <- append(
52       mdfile,
53       "# Please do not edit this file directly; it is auto generated.",
54       after = 1
55     )
56     mdfile <- append(
57       mdfile,
58       paste("# Instead, please edit", basename(y), "in _episodes_rmd/"),
59       after = 2
60     )
61     writeLines(mdfile, con)
62     close(con)
63     return(paste("Warning added to YAML header of", y))
64   }
65
66   vapply(dest_md, add_no_edit_comment, character(1))
67 }
68
69 generate_md_episodes()