inst/rstudio/KuskoHarvPred-tool/scrape-documentation.R

# clear the workspace
rm(list = ls(all = TRUE))

# load the stringr package: for character string manipulations
# primarily str_detect()
library(stringr)

# get original working directory
# should be the project path
wd = getwd()

# set the working directory to the location of the tool
new_wd = file.path(wd, "inst/rstudio/KuskoHarvPred-tool")
setwd(new_wd)

# read in the tool code
tool_code = readLines("index.Rmd")

# function to scrape specific chunk text from the rmd file
extract_chunk = function(x, label, prog = "r ") {
  start_pattern = paste0("```\\{", prog, label)
  end_pattern = "^```$"
  start_line = which(str_detect(x, start_pattern))
  end_lines = which(str_detect(x, end_pattern))
  end_line = min(end_lines[end_lines > start_line])
  x[start_line:end_line]
}

# prep the chunks to keep
chunks = c(
  extract_chunk(tool_code, "knitr-setup"),
  "\n",
  extract_chunk(tool_code, "css", prog = ""),
  "\n",
  extract_chunk(tool_code, "pkg-setup"),
  "\n",
  extract_chunk(tool_code, "data-prep"),
  "\n"
)

# prep the help blocks
first = which(str_detect(tool_code, "\\:\\:\\:\\{\\.blue"))
first = c(which(str_detect(tool_code, "\\:\\:\\:\\{\\.red")), first)
last = which(str_detect(tool_code, "\\:\\:\\:$"))

help_blocks = lapply(1:length(first), function(f) {
  l = min(which(last > first[f]))
  tool_code[first[f]:last[l]]
})

help = NULL
for (i in 1:length(help_blocks)) {help = c(help, help_blocks[[i]], "\n`r br()`\n")}

# prep the methods overview section
first = which(str_detect(tool_code, "### Methods Overview"))
last = which(str_detect(tool_code, "### AIC")) - 1
methods = tool_code[first:last]

# prep the yaml header
yaml = c(
  "---",
  'title: "**Kuskokwim Salmon Harvest Prediction Tool**"',
  'subtitle: "_Help Documentation_"',
  'output:',
  '  html_document',
  '---\n'
)

# prep the "more information" content
more_info = tool_code[which(str_detect(tool_code, "More Info\\. \\{\\.tabset\\}")): length(tool_code)]
more_info[1] = "## More Information {.tabset .tabset-pills}"

# build the full document
out = c(yaml, chunks, methods, "### Help Information\n", help)

# change all headers to be up by one level
out = str_replace_all(out, "###", "##")

# combine more information section
out = c(out, more_info)

# write the file
writeLines(out, "KuskoHarvPred-tool-documentation.Rmd")

# show the rmd file
# file.show("KuskoHarvPred-tool-documentation.Rmd")

# render to html
rmarkdown::render("KuskoHarvPred-tool-documentation.Rmd")

# open the file in a browser
file.show("KuskoHarvPred-tool-documentation.html")

# delete the rmd source file -- generated by code by scraping the tool code, can be deleted
unlink("KuskoHarvPred-tool-documentation.Rmd")

# set the working directory back to the project location
setwd(wd)
bstaton1/KuskoHarvPred documentation built on Aug. 15, 2024, 3:30 p.m.