Skip to content
Snippets Groups Projects
add_report.R 2.49 KiB
Newer Older
#' Add a new report in a fairify project
#'
#' @param name Name of the report (sub-folder name in "reports")
#' @param template The report template chosen between the folders located in
#' the "templates" folder of the fairify project
#' @param lang Language used in the report as defined by the babel LaTeX package
#' @param path Path of the fairify project
#'
#' @return The path of the added report
#' @export
#'
#' @inherit create_reports examples
#'
add_report <- function(name,
                       template = "inrae",
                       lang = "english",
                       path = pkgload::pkg_path()) {
  if (!all(dir.exists(file.path(path, c("reports", "templates"))))) {
    stop("Report structure not found, call `create_reports` first!")
  }
  if (!dir.exists(file.path(path, "templates", template))) {
    stop("Template\"", template, "\" not found in ", file.path(path, "templates"))
  }
  destpath <- file.path(path, "reports", name)
  if (dir.exists(destpath))
    stop("The folder ",
         destpath,
         " exists already. Delete it first or choose another.")
  dirtmp <- tempfile()
  dir.create(dirtmp, recursive = TRUE)
  b <- file.copy(
    from = file.path(pkg_sys("bookdown_template")),
    recursive = TRUE,
    copy.date = TRUE
  )
  if (any(!b)) stop("The creation of the report failed")
  file.rename(
    file.path(dirtmp, "bookdown_template"),
    destpath
  )
  bookdown_config <- list(
    language = list(ui = list(
      chapter_name = paste0(stringr::str_to_title(i18n("chapter", lang)), " ")
    )),
    babel_lang = lang
  )
    yaml::as.yaml(bookdown_config),
    file = file.path(destpath, "_bookdown.yml"),
    append = TRUE
  )

  lapply(c("in_header", "before_body", "after_body"), function(x) {
    tex_content <- sprintf("\\input{../../templates/%s/%s}", template, x)
    if (x == "in_header") {
      tex_content <- c(
        sprintf("\\usepackage[%s]{babel}", lang),
        sprintf("\\selectlanguage{%s}", lang),
        tex_content
      )
      babel_lang_tex <- sprintf("templates/basic/babel_%s.tex", lang)
      if (file.exists(pkg_sys(babel_lang_tex))) {
        tex_content <- c(tex_content, sprintf("\\input{../../%s}", babel_lang_tex))
      }
    tex_content <- c(tex_content,
                     "\n",
                     "% Add your own settings below to append or overwrite template settings")
    writeLines(tex_content, file.path(destpath, sprintf("%s.tex", x)))
  })

  tinytex_install_babel_language_support(lang)
  return(destpath)
}