File: utils.R

package info (click to toggle)
r-cran-reprex 0.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 1,424 kB
  • sloc: sh: 13; makefile: 2
file content (99 lines) | stat: -rw-r--r-- 2,345 bytes parent folder | download | duplicates (2)
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
is_toggle <- function(x) {
  length(x) == 1 && is.logical(x) && !is.na(x)
}

is_path <- function(x) {
  length(x) == 1 && is.character(x) && !grepl("\n$", x)
}

locate_input <- function(input) {
  if (is.null(input)) return("clipboard")
  if (is_path(input)) {
    "path"
  } else {
    "input"
  }
}

read_lines <- function(path) {
  if (is.null(path)) return(NULL)
  readLines(path)
}

trim_ws <- function(x) {
  sub("\\s*$", "", sub("^\\s*", "", x))
}

trim_common_leading_ws <- function(x) {
  m <- regexpr("^(\\s*)", x)
  n_chars <- nchar(x)
  n_spaces <- attr(m, which = "match.length")
  num <- min(n_spaces[n_chars > 0])
  substring(x, num + 1)
}

ingest_clipboard <- function() {
  if (clipboard_available()) {
    return(suppressWarnings(clipr::read_clip()))
  }
  message("No input provided and clipboard is not available.")
  character()
}

escape_regex <- function(x) {
  chars <- c("*", ".", "?", "^", "+", "$", "|", "(", ")", "[", "]", "{", "}", "\\")
  gsub(paste0("([\\", paste(chars, collapse = "\\"), "])"), "\\\\\\1", x, perl = TRUE)
}

escape_newlines <- function(x) {
  gsub("\n", "\\\\n", x, perl = TRUE)
}

ds_is_gh <- function(venue) {
  if (venue == "ds") {
    message(
      "FYI, the Discourse venue \"ds\" is currently an alias for the ",
      "default GitHub venue \"gh\".\nYou don't need to specify it."
    )
    venue <- "gh"
  }
  venue
}

pandoc2.0 <- function() rmarkdown::pandoc_available("2.0")

enfence <- function(lines,
                    tag = NULL,
                    fallback = "-- nothing to show --") {
  if (length(lines) == 0) {
    lines <- fallback
  }
  collapse(c(tag, "``` sh", lines, "```"))
}


inject_file <- function(path, inject_path, pre_process = enfence, ...) {
  lines <- readLines(path, encoding = "UTF-8")
  inject_lines <- readLines(inject_path, encoding = "UTF-8")
  inject_lines <- pre_process(inject_lines, ...)

  inject_locus <- grep(backtick(inject_path), lines, fixed = TRUE)
  lines <- c(
    lines[seq_len(inject_locus - 1)],
    inject_lines,
    lines[-seq_len(inject_locus)]
  )
  writeLines(lines, path)
  path
}

prose <- function(x) paste0("#' ", x)

collapse <- function(x, sep = "\n") {
  stopifnot(is.character(sep), length(sep) == 1)
  paste(x, collapse = sep)
}

backtick <- function(x) encodeString(x, quote = "`")

newline <- function(x) paste0(x, "\n")