File: helper.R

package info (click to toggle)
r-cran-bookdown 0.42%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,752 kB
  • sloc: javascript: 11,343; makefile: 21; sh: 20
file content (85 lines) | stat: -rw-r--r-- 2,189 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# From rmarkdown helper.R

# Use to test pandoc availability or version lower than
skip_if_not_pandoc <- function(ver = NULL) {
  if (!rmarkdown::pandoc_available(ver)) {
    msg <- if (is.null(ver)) {
      "Pandoc is not available"
    } else {
      sprintf("Version of Pandoc is lower than %s.", ver)
    }
    skip(msg)
  }
}

# Use to test version greater than
skip_if_pandoc <- function(ver = NULL) {
  if (rmarkdown::pandoc_available(ver)) {
    msg <- if (is.null(ver)) {
      "Pandoc is available"
    } else {
      sprintf("Version of Pandoc is greater than %s.", ver)
    }
    skip(msg)
  }
}

local_rmd_file <- function(..., .env = parent.frame()) {
  path <- withr::local_tempfile(.local_envir = .env, fileext = ".Rmd")
  xfun::write_utf8(c(...), path)
  path
}

local_render <- function(input, ..., .env = parent.frame()) {
  skip_if_not_pandoc()
  output_file <- withr::local_tempfile(.local_envir = .env)
  rmarkdown::render(input, output_file = output_file, quiet = TRUE, ...)
}

local_render_book <- function(input, ..., .env = parent.frame()) {
  skip_if_not_pandoc()
  proj <- withr::local_tempdir(.local_envir = .env)
  file.copy(normalizePath(input), proj)
  withr::local_dir(proj)
  render_book(basename(input), quiet = TRUE, ...)
}

.render_and_read <- function(input, ...) {
  skip_if_not_pandoc()
  res <- local_render(input, ...)
  xfun::read_utf8(res)
}

local_book <- function(name = "book",
                       title = "Awesome Cookbook",
                       author = "Yoda",
                       description = NULL,
                       url = NULL,
                       verbose = FALSE,
                       env = parent.frame()) {

  path <- withr::local_tempdir(.local_envir = env)

  book_skeleton(
    name = name,
    title = title,
    author = author,
    path = path,
    description = description,
    url = url
  )

  # Add text to Introduction

  intro <- readLines(file.path(path, "01-Introduction.Rmd"))
  writeLines(
    c(intro, paste0(rep(0:9, 42), collapse = " ")),
    file.path(path, "01-Introduction.Rmd")
  )

  return(path)
}

.render_book_quiet <- function(...) {
  suppressMessages(render_book(..., quiet = TRUE))
}