Debian Codegraph @

R/embed.R

raw
1
2 #' Capture and re-use dependencies within a `.R`, `.Rmd` or `.qmd`
3 #'
4 #' @description
5 #' Together, `embed()` and `use()` provide a lightweight way to specify and
6 #' restore package versions within a file. `use()` is a lightweight lockfile
7 #' specification that `embed()` can automatically generate and insert into a
8 #' script or document.
9 #'
10 #' Calling `embed()` inspects the dependencies of the specified document then
11 #' generates and inserts a call to `use()` that looks something like this:
12 #'
13 #' ```R
14 #' renv::use(
15 #' "[email protected]",
16 #' "[email protected]"
17 #' )
18 #' ```
19 #'
20 #' When you next run your R script or render your `.Rmd` or `.qmd`, `use()` will:
21 #'
22 #' 1. Create a temporary library path,
23 #'
24 #' 1. Install the requested packages and their recursive dependencies into that
25 #' library,
26 #'
27 #' 1. Activate the library, so it's used for the rest of the script.
28 #'
29 #' ## Manual usage
30 #'
31 #' You can also create calls to `use()` yourself, either specifying the
32 #' packages needed by hand, or by supplying the path to a lockfile,
33 #' `renv::use(lockfile = "/path/to/renv.lock")`.
34 #'
35 #' This can be useful in projects where you'd like to associate different
36 #' lockfiles with different documents, as in a blog where you want each
37 #' post to capture the dependencies at the time of writing. Once you've
38 #' finished writing each, the post, you can use
39 #' `renv::snapshot(lockfile = "/path/to/renv.lock")`
40 #' to "save" the state that was active while authoring that bost, and then use
41 #' `renv::use(lockfile = "/path/to/renv.lock")` in that document to ensure the
42 #' blog post always uses those dependencies onfuture renders.
43 #'
44 #' `renv::use()` is inspired in part by the [groundhog](https://groundhogr.com/)
45 #' package, which also allows one to specify a script's \R package requirements
46 #' within that same \R script.
47 #'
48 #' @inherit renv-params
49 #'
50 #' @param path
51 #' The path to an \R or R Markdown script. The default will use the current
52 #' document, if running within RStudio.
53 #'
54 #' ## Package Resolution
55 #'
56 #' When `embed()` generates a call to `use()`, it needs to determine the
57 #' package versions to record. The `lockfile` parameter controls where these
58 #' versions come from:
59 #'
60 #' 1. If `lockfile` is `NULL` (the default), and the project has an existing
61 #' `renv.lock` file, that project lockfile is used. Only packages present
62 #' in the lockfile will be included -- any dependencies not recorded in the
63 #' lockfile will be omitted.
64 #'
65 #' 2. If `lockfile` is a path to a lockfile, or a lockfile object, that
66 #' lockfile is used directly.
67 #'
68 #' 3. If `lockfile` is `FALSE`, or if no project lockfile exists, package
69 #' versions are inferred from the currently-installed packages in the
70 #' active library paths.
71 #'
72 #' 4. If `lockfile` is `NA`, package versions are inferred from the
73 #' latest versions available in the active package repositories.
74 #'
75 #' @param lockfile
76 #' The path to an renv lockfile. When `NULL` (the default), the project
77 #' lockfile will be read (if any); otherwise, a new lockfile will be generated
78 #' from the current library paths. Use `lockfile = FALSE` to use
79 #' currently-installed package versions, or `lockfile = NA` to use the
80 #' latest versions available in the active package repositories. See
81 #' **Package Resolution** for more details.
82 #'
83 #' @export
84 embed <- function(path = NULL,
85 ...,
86 lockfile = NULL,
87 project = NULL)
88 {
89 path <- path %||% renv_embed_path()
90
91 ext <- tolower(fileext(path))
92 method <- case(
93 ext == ".r" ~ renv_embed_r,
94 ext == ".rmd" ~ renv_embed_rmd,
95 ext == ".qmd" ~ renv_embed_rmd
96 )
97
98 if (is.null(method)) {
99 fmt <- "don't know how to embed lockfile into file %s"
100 stopf(fmt, renv_path_pretty(path))
101 }
102
103 method(
104 path = path,
105 lockfile = lockfile,
106 project = project,
107 ...
108 )
109
110 }
111
112 renv_embed_path <- function() {
113
114 tryCatch(
115 renv_embed_path_impl(),
116 error = function(e) NULL
117 )
118
119 }
120
121 renv_embed_path_impl <- function() {
122 rstudio <- as.environment("tools:rstudio")
123 rstudio$.rs.api.documentPath()
124 }
125
126 renv_embed_create_lockfile <- function(path = NULL,
127 lockfile = NULL,
128 project = NULL)
129 {
130 # figure out the package dependencies for this script
131 deps <- dependencies(path, quiet = TRUE)
132 packages <- sort(unique(deps[["Package"]]))
133 all <- renv_package_dependencies(packages)
134
135 # select the lockfile source
136 source <- renv_embed_lockfile_select(lockfile, project)
137
138 # notify user if some dependencies appear to be unavailable
139 # (skip when using repository versions, since we don't need
140 # packages to be installed in that case)
141 if (!identical(source, NA)) {
142 ok <- nzchar(all)
143 missing <- names(all)[!ok]
144 if (length(missing)) {
145 missing <- sort(unique(missing))
146 stop("required packages are not installed: ", paste(missing, collapse = ", "))
147 }
148 }
149 lockfile <- renv_embed_lockfile_resolve(path, names(all), source, project)
150
151 # keep only matched records
152 renv_lockfile_records(lockfile) <-
153 renv_lockfile_records(lockfile) %>%
154 keep(c("renv", names(all)))
155
156 # notify user if some dependencies are missing
157 ignored <- c("renv", renv_packages_base())
158 expected <- setdiff(names(all), ignored)
159 actual <- names(renv_lockfile_records(lockfile))
160 missing <- setdiff(expected, actual)
161 if (length(missing)) {
162
163 postamble <- if (identical(source, NA)) c(
164 "These packages are not available in the active package repositories."
165 ) else if (identical(source, FALSE)) c(
166 "Packages must first be installed before renv can snapshot them."
167 ) else c(
168 "Use `renv::snapshot()` to update the lockfile, or",
169 "use `renv::embed(lockfile = FALSE)` to use installed package versions instead."
170 )
171
172 bulletin(
173 preamble = "The following required packages are not available:",
174 values = sort(unique(missing)),
175 postamble = postamble
176 )
177
178 renv_condition_signal("renv.embed.missing_packages", missing)
179
180 }
181
182 invisible(lockfile)
183 }
184
185 renv_embed_create <- function(path = NULL,
186 lockfile = NULL,
187 project = NULL)
188 {
189 lockfile <- renv_embed_create_lockfile(path, lockfile, project)
190 renv_lockfile_compact(lockfile)
191 }
192
193 renv_embed_r <- function(path, ..., lockfile = NULL, project = NULL) {
194
195 # resolve project
196 project <- renv_project_resolve(project, default = NULL)
197
198 # read file contents
199 contents <- readLines(path, warn = FALSE, encoding = "UTF-8")
200
201 # generate embed
202 embed <- renv_embed_create(
203 path = path,
204 lockfile = lockfile,
205 project = project
206 )
207
208 # check for existing 'renv::use' statement
209 pattern <- "^\\s*(?:renv:{2,3})?use\\(\\s*$"
210 index <- grep(pattern, contents, perl = TRUE)
211
212 # if we don't have an index, just insert at start
213 if (empty(index)) {
214 contents <- c(embed, "", contents)
215 writeLines(contents, con = path)
216 return(TRUE)
217 }
218
219 # otherwise, try to replace an existing embedded lockfile
220 start <- index
221
222 # find the end of the block
223 n <- length(contents)
224 lines <- grep("^\\s*\\)\\s*$", contents, perl = TRUE)
225 end <- min(lines[lines > start], n + 1L)
226
227 # insert new lockfile
228 contents <- c(
229 head(contents, n = start - 1L),
230 embed,
231 tail(contents, n = n - end)
232 )
233
234 writeLines(contents, con = path)
235 return(TRUE)
236
237 }
238
239 renv_embed_create_rmd <- function(path = NULL,
240 lockfile = NULL,
241 project = NULL)
242 {
243 # create lockfile
244 lockfile <- renv_embed_create_lockfile(path, lockfile, project)
245
246 # create embed
247 embed <- renv_embed_create(
248 path = path,
249 lockfile = lockfile,
250 project = project
251 )
252
253 # return embed
254 c("```{r lockfile, include=FALSE}", embed, "```")
255
256 }
257
258
259 renv_embed_rmd <- function(path,
260 ...,
261 lockfile = NULL,
262 project = NULL)
263 {
264 # resolve project
265 project <- renv_project_resolve(project, default = NULL)
266
267 # read file contents
268 contents <- readLines(path, warn = FALSE, encoding = "UTF-8")
269
270 # generate embed
271 embed <- renv_embed_create_rmd(
272 path = path,
273 lockfile = lockfile,
274 project = project
275 )
276
277 # check for existing renv.lock in file
278 # if it exists, we'll want to replace at this location;
279 # otherwise, insert at end of document
280 header <- "^\\s*```{r lockfile"
281 footer <- "```"
282 start <- grep(header, contents, perl = TRUE)
283
284 # if we don't have an index, insert after YAML header (if any)
285 if (empty(start)) {
286 bounds <- which(trimws(contents) == "---")
287
288 all <- if (length(bounds) >= 2) {
289 index <- bounds[[2L]]
290 c(
291 head(contents, n = index),
292 "",
293 embed,
294 "",
295 tail(contents, n = length(contents) - index)
296 )
297 } else {
298 c(embed, "", contents)
299 }
300
301 writeLines(all, con = path)
302 return(TRUE)
303 }
304
305 # otherwise, try to replace an existing embedded lockfile
306 ends <- which(contents == footer)
307 end <- min(ends[ends > start])
308
309 # insert new lockfile
310 contents <- c(
311 head(contents, n = start - 1L),
312 embed,
313 tail(contents, n = length(contents) - end)
314 )
315
316 writeLines(contents, con = path)
317 return(TRUE)
318
319 }
320
321 renv_embed_lockfile_select <- function(lockfile, project) {
322
323 # if lockfile is explicitly FALSE, use installed packages
324 if (identical(lockfile, FALSE))
325 return(FALSE)
326
327 # if lockfile is NA, use available packages from repositories
328 if (identical(lockfile, NA))
329 return(NA)
330
331 # if lockfile is a character path or list, use it directly
332 if (is.character(lockfile) || is.list(lockfile))
333 return(lockfile)
334
335 # lockfile is NULL; check for a project lockfile
336 if (length(project)) {
337 path <- renv_lockfile_path(project)
338 if (file.exists(path))
339 return(path)
340 }
341
342 # no project lockfile; fall back to installed packages
343 FALSE
344
345 }
346
347 renv_embed_lockfile_resolve <- function(path, packages, lockfile, project) {
348
349 # if we have a lockfile path, read it
350 if (is.character(lockfile))
351 return(renv_lockfile_read(lockfile))
352
353 # if we have a lockfile object, use it as-is
354 if (is.list(lockfile))
355 return(lockfile)
356
357 # if NA, use available packages from repositories
358 if (identical(lockfile, NA))
359 return(renv_embed_lockfile_resolve_available(packages, project))
360
361 # otherwise, generate a lockfile from installed packages
362 project <- renv_project_resolve(project, default = NULL)
363 snapshot(
364 lockfile = NULL,
365 packages = packages,
366 project = project
367 )
368
369 }
370
371 renv_embed_lockfile_resolve_available <- function(packages, project) {
372
373 project <- renv_project_resolve(project, default = NULL)
374 lockfile <- renv_lockfile_init(project)
375
376 # look up the latest version for each package
377 ignored <- renv_packages_base()
378 packages <- setdiff(packages, ignored)
379
380 records <- map(packages, function(package) {
381 catch(renv_available_packages_latest(package))
382 })
383
384 names(records) <- packages
385 records <- filter(records, function(record) !inherits(record, "error"))
386 renv_lockfile_records(lockfile) <- records
387
388 lockfile
389
390 }