File: reprex_impl.R

package info (click to toggle)
r-cran-reprex 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 1,584 kB
  • sloc: sh: 13; makefile: 2
file content (199 lines) | stat: -rw-r--r-- 6,332 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
reprex_impl <- function(x_expr = NULL,
                        input  = NULL, outfile = NULL,
                        venue  = c("gh", "r", "rtf", "html", "slack", "so", "ds"),

                        render = TRUE,
                        new_session = TRUE,

                        advertise       = NULL,
                        session_info    = opt(FALSE),
                        style           = opt(FALSE),
                        comment         = opt("#>"),
                        tidyverse_quiet = opt(TRUE),
                        std_out_err     = opt(FALSE),
                        html_preview    = opt(TRUE)) {

  venue <- tolower(venue)
  venue <- match.arg(venue)
  venue <- normalize_venue(venue)

  advertise       <- set_advertise(advertise, venue)
  session_info    <- arg_option(session_info)
  style           <- arg_option(style)
  style           <- style_requires_styler(style)
  html_preview    <- arg_option(html_preview)
  html_preview    <- html_preview_requires_interactive(html_preview)
  comment         <- arg_option(comment)
  tidyverse_quiet <- arg_option(tidyverse_quiet)
  std_out_err     <- arg_option(std_out_err)

  if (!is.null(input)) stopifnot(is.character(input))
  if (!is.null(outfile)) stopifnot(is.character(outfile) || is.na(outfile))
  stopifnot(is_toggle(advertise), is_toggle(session_info), is_toggle(style))
  stopifnot(is_toggle(html_preview), is_toggle(render))
  stopifnot(is.character(comment))
  stopifnot(is_toggle(tidyverse_quiet), is_toggle(std_out_err))

  where <- if (is.null(x_expr)) locate_input(input) else "expr"
  src <- switch(
    where,
    expr      = stringify_expression(x_expr),
    clipboard = ingest_clipboard(),
    path      = read_lines(input),
    input     = escape_newlines(sub("\n$", "", enc2utf8(input))),
    NULL
  )
  src <- ensure_not_empty(src)
  src <- ensure_not_dogfood(src)
  src <- ensure_no_prompts(src)

  outfile_given <- !is.null(outfile)
  infile <- if (where == "path") input else NULL
  filebase <- make_filebase(outfile, infile)

  r_file <- r_file(filebase)
  if (would_clobber(r_file)) {
    return(invisible())
  }

  reprex_document_options <- list(
    venue = venue,
    advertise = advertise, session_info = session_info,
    style = style, html_preview = html_preview, comment = comment,
    tidyverse_quiet = tidyverse_quiet, std_out_err = std_out_err
  )
  src <- c(yamlify(reprex_document_options), "", src)
  write_lines(src, r_file)
  if (outfile_given) {
    reprex_path("Preparing reprex as {.code .R} file:", r_file)
  }

  if (!render) {
    return(invisible(read_lines(r_file)))
  }

  reprex_info("Rendering reprex...")
  reprex_file <- reprex_render_impl(r_file, new_session = new_session)
  # for reasons re: the RStudio "Knit" button, reprex_render_impl() may return
  # path to the html_preview, but reprex_file attribute will always be the
  # content the user requested and that belongs on clipboard and as the return
  # value
  reprex_file <- attr(reprex_file, "reprex_file", exact = TRUE)

  if (outfile_given) {
    reprex_path("Writing reprex file:", reprex_file)
  }

  out_lines <- read_lines(reprex_file)

  if (clipboard_available()) {
    if (venue == "rtf" && is_windows()) {
      write_clip_windows_rtf(reprex_file)
    } else {
      clipr::write_clip(out_lines)
    }
    reprex_success("Rendered reprex is on the clipboard.")
  } else if (is_interactive()) {
    clipr::dr_clipr()
    # TODO: come back and clean this up or put in a function
    reprex_danger("Unable to put result on the clipboard. How to get it:")
    cli::cli_ul()
    cli::cli_li("Capture what {.fun reprex} returns.")
    cli::cli_li("Consult the output file. Control via {.arg outfile} argument.")
    cli::cli_li("Path to {.arg outfile}:")
    cli::cli_ul()
    # TODO: when filepath is long, there's an unexplained leading newline
    cli::cli_li("{.file {reprex_file}}")
    cli::cli_end()
    cli::cli_end()
    if (yep("Open the output file for manual copy?")) {
      withr::defer(utils::file.edit(reprex_file))
    }
  }

  invisible(out_lines)
}

set_advertise <- function(advertise, venue) {
  default <- c(
    gh    = TRUE,
    ds    = TRUE,
    html  = TRUE,
    so    = TRUE,
    r     = FALSE,
    rtf   = FALSE,
    slack = FALSE
  )
  advertise %||%
    getOption("reprex.advertise") %||%
    default[[venue]]
}

style_requires_styler <- function(style) {
  if (!requireNamespace("styler", quietly = TRUE)) {
    reprex_danger("
      Install the {.pkg styler} package in order to use
      {.code style = TRUE}.")
    style <- FALSE
  }
  invisible(style)
}

html_preview_requires_interactive <- function(html_preview) {
  if (html_preview && !is_interactive()) {
    reprex_info(
      "Non-interactive session, setting {.code html_preview = FALSE}.")
    html_preview <- FALSE
  }
  invisible(html_preview)
}

# re-express reprex() args as yaml for the reprex_document() format ----
yamlify <- function(x) {
  x <- remove_defaults(x)
  if (length(x) < 1) {
    return(decorate_yaml("output: reprex::reprex_document"))
  }
  lines <- c(
    "output:",
    "  reprex::reprex_document:",
    paste0("    ", nv(x))
  )
  decorate_yaml(lines)
}

decorate_yaml <- function(x) roxygen_comment(x <- c("---", x, "---"))

remove_defaults <- function(x) {
  defaults <- list(
    venue           = "gh",
    # this is the only conditional default, i.e. that depends on venue
    advertise       = set_advertise(NULL, x[["venue"]]),
    session_info    = FALSE,
    style           = FALSE,
    html_preview    = TRUE,
    comment         = "#>",
    tidyverse_quiet = TRUE,
    std_out_err     = FALSE
  )

  compare_one <- function(nm) identical(x[[nm]], defaults[[nm]])
  is_default <- vapply(names(x), compare_one, logical(1))

  novel_names <- setdiff(names(x), names(defaults))
  if (length(novel_names) > 0) {
    reprex_danger("
      {?This/These} parameter{?s} {?is/are} not recognized for the
      {.fun reprex_document} format: {.code {novel_names}}.")
  }

  x[!is_default]
}

nv <- function(x) {
  is_character <- vapply(x, is.character, logical(1))
  # dQuote didn't gain the `q` argument until R 3.6
  withr::local_options(list(useFancyQuotes = FALSE))
  x[is_character] <- vapply(x[is_character], dQuote, character(1))
  glue::glue("{name}: {value}", name = names(x), value = x)
}