Debian Codegraph @

R/dependencies.R

raw
1
2 #' Find R package dependencies in a project
3 #'
4 #' @description
5 #' `dependencies()` will scan files within your project, looking for \R files
6 #' and the packages used within those \R files. This is done primarily by
7 #' parsing the code and looking for calls of the form `library(package)`,
8 #' `require(package)`, `requireNamespace("package")`, and `package::method()`.
9 #' renv also supports package loading with
10 #' [box](https://cran.r-project.org/package=box) (`box::use(...)`) and
11 #' [pacman](https://cran.r-project.org/package=pacman) (`pacman::p_load(...)`).
12 #'
13 #' For \R package projects, `renv` will also detect dependencies expressed
14 #' in the `DESCRIPTION` file. For projects using Python, \R dependencies within
15 #' the \R code chunks of your project's `.ipynb` files will also be used.
16 #'
17 #' Note that the \code{\link[rmarkdown:rmarkdown-package]{rmarkdown}} package is
18 #' required in order to scan dependencies in R Markdown files.
19 #'
20 #' # Missing dependencies
21 #'
22 #' `dependencies()` uses static analysis to determine which packages are used
23 #' by your project. This means that it inspects, but doesn't run, the \R code
24 #' in your project. Static analysis generally works well, but is not
25 #' 100% reliable in detecting the packages required by your project. For
26 #' example, `renv` is unable to detect this kind of usage:
27 #'
28 #' ```{r eval=FALSE}
29 #' for (package in c("dplyr", "ggplot2")) {
30 #' library(package, character.only = TRUE)
31 #' }
32 #' ```
33 #'
34 #' It also can't generally tell if one of the packages you use, uses one of
35 #' its suggested packages. For example, the `tidyr::separate_wider_delim()`
36 #' function requires the `stringr` package, but `stringr` is only suggested,
37 #' not required, by `tidyr`.
38 #'
39 #' If you find that renv's dependency discovery misses one or more packages
40 #' that you actually use in your project, one escape hatch is to include a file
41 #' called `_dependencies.R` that includes straightforward library calls:
42 #'
43 #' ```
44 #' library(dplyr)
45 #' library(ggplot2)
46 #' library(stringr)
47 #' ```
48 #'
49 #' # Ignoring files
50 #'
51 #' By default, renv will read your project's `.gitignore`s (if present) to
52 #' determine whether certain files or folders should be included when traversing
53 #' directories. If preferred, you can also create a `.renvignore` file (with
54 #' entries of the same format as a standard `.gitignore` file) to tell renv
55 #' which files to ignore within a directory. If both `.renvignore` and
56 #' `.gitignore` exist within a folder, the `.renvignore` will be used in lieu of
57 #' the `.gitignore`.
58 #'
59 #' See <https://git-scm.com/docs/gitignore> for documentation on the
60 #' `.gitignore` format. Some simple examples here:
61 #'
62 #' ```
63 #' # ignore all R Markdown files
64 #' *.Rmd
65 #'
66 #' # ignore all data folders
67 #' data/
68 #'
69 #' # ignore only data folders from the root of the project
70 #' /data/
71 #' ```
72 #'
73 #' Using ignore files is important if your project contains a large number
74 #' of files; for example, if you have a `data/` directory containing many
75 #' text files.
76 #'
77 #'
78 #' ## Profile-specific Ignore Rules
79 #'
80 #' Profile-specific sections are also supported in `.renvignore` files.
81 #' These sections are marked with a comment header of the form `#| <code>`,
82 #' where `<code>` is \R code that indicates if this section of the `.renvignore`
83 #' should apply. The `profile` variable is set to the same value as the current
84 #' profile, or `"default"` if the default profile (no profile) is selected.
85 #' See `vignette("profiles", package = "renv")` for more information on profiles.
86 #'
87 #' ```
88 #' # ignore all directories by default
89 #' */
90 #'
91 #' #| profile == "default"
92 #' !default
93 #'
94 #' #| profile == "extra"
95 #' !extra
96 #' ```
97 #'
98 #' Note that the first section in a `.renvignore` file implicitly applies to
99 #' all profiles.
100 #'
101 #'
102 #' # Errors
103 #'
104 #' renv's attempts to enumerate package dependencies in your project can fail
105 #' -- most commonly, because of failures when attempting to parse your \R code.
106 #' You can use the `errors` argument to suppress these problems, but a
107 #' more robust solution is tell renv not to look at the problematic code.
108 #' As well as using `.renvignore`, as described above, you can also suppress errors
109 #' discovered within individual `.Rmd` chunks by including `renv.ignore=TRUE`
110 #' in the chunk header. For example:
111 #'
112 #' ```{r chunk-label, renv.ignore=TRUE}
113 #' # code in this chunk will be ignored by renv
114 #' ```
115 #'
116 #' Similarly, if you'd like renv to parse a chunk that is otherwise ignored
117 #' (e.g. because it has `eval=FALSE` as a chunk header), you can set:
118 #'
119 #' ```{r chunk-label, eval=FALSE, renv.ignore=FALSE}
120 #' # code in this chunk will _not_ be ignored
121 #' ```
122 #'
123 #' # Development dependencies
124 #'
125 #' renv has some support for distinguishing between development and run-time
126 #' dependencies. For example, your Shiny app might rely on
127 #' [ggplot2](https://ggplot2.tidyverse.org) (a run-time dependency) but while
128 #' you use [usethis](https://usethis.r-lib.org) during development, your app
129 #' doesn't need it to run (i.e. it's only a development dependency).
130 #'
131 #' You can record development dependencies by listing them in the `Suggests`
132 #' field of your project's `DESCRIPTION` file. Development dependencies will be installed by
133 #' [renv::install()] (when called without arguments) but will not be tracked in
134 #' the project snapshot. If you need greater control, you can also try project
135 #' profiles as discussed in `vignette("profiles")`.
136 #'
137 #' @inheritParams renv-params
138 #'
139 #' @param path The path to a `.R`, `.Rmd`, `.qmd`, `DESCRIPTION`, a directory
140 #' containing such files, or an R function. The default uses all files
141 #' found within the current working directory and its children.
142 #'
143 #' @param root The root directory to be used for dependency discovery.
144 #' Defaults to the active project directory. You may need to set this
145 #' explicitly to ensure that your project's `.renvignore`s (if any) are
146 #' properly handled.
147 #'
148 #' @param quiet Boolean; be quiet while checking for dependencies?
149 #' Setting `quiet = TRUE` is equivalent to setting `progress = FALSE`
150 #' and `errors = "ignored"`, and overrides those options when not `NULL`.
151 #'
152 #' @param progress Boolean; report progress output while enumerating
153 #' dependencies?
154 #'
155 #' @param errors How should errors that occur during dependency enumeration be
156 #' handled?
157 #'
158 #' * `"reported"` (the default): errors are reported to the user, but
159 #' otherwise ignored.
160 #' * `"fatal"`: errors are fatal and stop execution.
161 #' * `"ignored"`: errors are ignored and not reported to the user.
162 #'
163 #' @param dev Boolean; include development dependencies? These packages are
164 #' typically required when developing the project, but not when running it
165 #' (i.e. you want them installed when humans are working on the project but
166 #' not when computers are deploying it).
167 #'
168 #' Development dependencies include packages listed in the `Suggests` field
169 #' of a `DESCRIPTION` found in the project root, and roxygen2 or devtools if
170 #' their use is implied by other project metadata. They also include packages
171 #' used in `~/.Rprofile` if `config$user.profile()` is `TRUE`.
172 #'
173 #' @return An \R `data.frame` of discovered dependencies, mapping inferred
174 #' package names to the files in which they were discovered. Note that the
175 #' `Package` field might name a package remote, rather than just a plain
176 #' package name.
177 #'
178 #' @export
179 #'
180 #' @examples
181 #' \dontrun{
182 #'
183 #' # find R package dependencies in the current directory
184 #' renv::dependencies()
185 #'
186 #' }
187 dependencies <- function(
188 path = getwd(),
189 root = NULL,
190 ...,
191 quiet = NULL,
192 progress = TRUE,
193 errors = c("reported", "fatal", "ignored"),
194 dev = FALSE)
195 {
196 renv_scope_error_handler()
197
198 # special case: if 'path' is a function, parse its body for dependencies
199 if (is.function(path))
200 return(renv_dependencies_discover_r(expr = body(path)))
201
202 renv_dependencies_impl(
203 path = path,
204 root = root,
205 quiet = quiet,
206 progress = progress,
207 errors = errors,
208 dev = dev,
209 ...
210 )
211 }
212
213 renv_dependencies_impl <- function(
214 path = getwd(),
215 ...,
216 root = NULL,
217 field = NULL,
218 quiet = NULL,
219 progress = FALSE,
220 errors = c("reported", "fatal", "ignored"),
221 dev = FALSE)
222 {
223 renv_dots_check(...)
224
225 path <- renv_path_normalize(path, mustWork = TRUE)
226 root <- root %||% renv_dependencies_root(path)
227
228 # handle 'quiet' parameter
229 if (quiet %||% FALSE) {
230 progress <- FALSE
231 errors <- "ignored"
232 }
233
234 # ignore errors when testing, unless explicitly asked for
235 if (renv_tests_running() && missing(errors))
236 errors <- "ignored"
237
238 # resolve errors
239 errors <- match.arg(errors)
240
241 # the path to the user .Rprofile is used when discovering dependencies,
242 # so resolve that eagerly now
243 renv_scope_binding(
244 envir = the$paths,
245 symbol = "r_profile_user",
246 replacement = Sys.getenv("R_PROFILE_USER", unset = path.expand("~/.Rprofile"))
247 )
248
249 before <- Sys.time()
250 renv_dependencies_scope(root = root)
251 files <- renv_dependencies_find(path, root)
252 deps <- renv_dependencies_discover(files, progress, errors)
253 after <- Sys.time()
254 elapsed <- difftime(after, before, units = "secs")
255
256 renv_condition_signal("renv.dependencies.elapsed_time", elapsed)
257 renv_dependencies_report(errors)
258
259 if (empty(deps) || nrow(deps) == 0L) {
260 result <- renv_dependencies_list_empty()
261 return(take(result, field))
262 }
263
264 # drop other NAs, just in case -- this really is an issue in the underlying
265 # dependency computation code somewhere, but we still want to insulate users
266 # from unexpected errors
267 #
268 # https://github.com/rstudio/renv/issues/2110
269 keep <- !is.na(deps$Package) & deps$Dev %in% c(dev, FALSE)
270 take(rows(deps, keep), field)
271 }
272
273 renv_dependencies_root <- function(path = getwd()) {
274
275 path <- renv_path_normalize(path, mustWork = TRUE)
276
277 project <- renv_project_get(default = NULL)
278 if (!is.null(project) && all(renv_path_within(path, project)))
279 return(project)
280
281 roots <- uapply(path, renv_dependencies_root_impl)
282 if (empty(roots))
283 return(NULL)
284
285 uniroot <- unique(roots)
286 if (length(uniroot) > 1)
287 return(NULL)
288
289 uniroot
290
291 }
292
293 renv_dependencies_root_impl <- function(path) {
294
295 renv_file_find(path, function(parent) {
296 anchors <- c("DESCRIPTION", ".git", ".Rproj.user", "renv.lock", "renv")
297 for (anchor in anchors)
298 if (file.exists(file.path(parent, anchor)))
299 return(parent)
300 })
301
302 }
303
304 renv_dependencies_callback <- function(path) {
305
306 cbname <- list(
307 ".lintr" = function(path) renv_dependencies_discover_lintr(path),
308 ".Rprofile" = function(path) renv_dependencies_discover_r(path),
309 "DESCRIPTION" = function(path) renv_dependencies_discover_description(path),
310 "NAMESPACE" = function(path) renv_dependencies_discover_namespace(path),
311 "_bookdown.yml" = function(path) renv_dependencies_discover_bookdown(path),
312 "_pkgdown.yml" = function(path) renv_dependencies_discover_pkgdown(path),
313 "_quarto.yml" = function(path) renv_dependencies_discover_quarto(path),
314 "_server.yml" = function(path) renv_dependencies_discover_plumber_server(path),
315 "_server.yaml" = function(path) renv_dependencies_discover_plumber_server(path),
316 "renv.lock" = function(path) renv_dependencies_discover_renv_lock(path),
317 "rsconnect" = function(path) renv_dependencies_discover_rsconnect(path)
318 )
319
320 cbext <- list(
321 ".rproj" = function(path) renv_dependencies_discover_rproj(path),
322 ".r" = function(path) renv_dependencies_discover_r(path),
323 ".qmd" = function(path) renv_dependencies_discover_multimode(path, "qmd"),
324 ".rmd" = function(path) renv_dependencies_discover_multimode(path, "rmd"),
325 ".rmarkdown" = function(path) renv_dependencies_discover_multimode(path, "rmd"),
326 ".rnw" = function(path) renv_dependencies_discover_multimode(path, "rnw"),
327 ".ipynb" = function(path) renv_dependencies_discover_ipynb(path)
328 )
329
330 name <- basename(path)
331 ext <- tolower(fileext(path))
332
333 callback <- cbname[[name]] %||% cbext[[ext]]
334 if (!is.null(callback))
335 return(callback)
336
337 # for files without an extension, check if those might be executable by R
338 if (!nzchar(ext)) {
339 shebang <- renv_file_shebang(path)
340 if (grepl("\\b(?:R|r|Rscript)\\b", shebang))
341 return(function(path) renv_dependencies_discover_r(path))
342 }
343
344 }
345
346 renv_dependencies_find_extra <- function(root) {
347
348 # if we don't have a root, we don't have a project
349 if (is.null(root))
350 return(NULL)
351
352 # only run for root-level dependency checks
353 project <- renv_project_resolve()
354 if (!renv_path_same(root, project))
355 return(NULL)
356
357 # only run if we have a custom profile
358 profile <- renv_profile_get()
359 if (is.null(profile))
360 return(NULL)
361
362 # look for dependencies in the associated 'renv' folder
363 path <- renv_paths_renv(project = project)
364 renv_dependencies_find_impl(path, root, 0L)
365
366 }
367
368 renv_dependencies_find <- function(path = getwd(), root = getwd()) {
369 files <- lapply(path, renv_dependencies_find_impl, root = root, depth = 0)
370 extra <- renv_dependencies_find_extra(root)
371
372 if (config$user.profile()) {
373 profile <- the$paths$r_profile_user
374 if (file.exists(profile)) {
375 extra <- c(extra, profile)
376 }
377 }
378
379 unlist(c(files, extra), recursive = TRUE, use.names = FALSE)
380 }
381
382 renv_dependencies_find_impl <- function(path, root, depth) {
383
384 # check file type
385 info <- renv_file_info(path)
386
387 # the file might have been removed after listing -- if so, just ignore it
388 if (is.na(info$isdir))
389 return(NULL)
390
391 # if this is a directory, recurse
392 if (info$isdir)
393 return(renv_dependencies_find_dir(path, root, depth))
394
395 path
396 }
397
398 renv_dependencies_find_dir <- function(path, root, depth) {
399
400 # check if this path should be ignored
401 excluded <- renv_renvignore_exec(path, root, path)
402 if (excluded)
403 return(character())
404
405 # check if we've already scanned this directory
406 # (necessary to guard against recursive symlinks)
407 if (!renv_platform_windows()) {
408 norm <- renv_path_normalize(path)
409 state <- renv_dependencies_state()
410 if (visited(norm, state$scanned))
411 return(character())
412 }
413
414 # list children
415 children <- renv_dependencies_find_dir_children(path, root, depth)
416
417 # notify about number of children
418 renv_condition_signal("renv.dependencies.count", list(path = path, count = length(children)))
419
420 # find recursive dependencies
421 depth <- depth + 1
422 paths <- map(children, renv_dependencies_find_impl, root = root, depth = depth)
423
424 # explicitly include rsconnect folder
425 # (so we can infer a dependency on rsconnect when appropriate)
426 rsconnect <- file.path(path, "rsconnect")
427 if (file.exists(rsconnect))
428 paths <- c(rsconnect, paths)
429
430 paths
431
432 }
433
434 # return the set of files / subdirectories within a directory that should be
435 # crawled for dependencies
436 renv_dependencies_find_dir_children <- function(path, root, depth) {
437
438 # list files in the folder
439 children <- renv_file_list(path, full.names = TRUE)
440
441 # skip if this contains too many files
442 # https://github.com/rstudio/renv/issues/1186
443 count <- length(children)
444 if (count >= config$dependencies.limit()) {
445 relpath <- renv_path_relative(path, dirname(root))
446 renv_dependencies_find_dir_children_overload(relpath, count)
447 }
448
449 # remove files which are broken symlinks
450 children <- children[file.exists(children)]
451
452 # remove hard-coded ignores
453 # (only keep DESCRIPTION files at the top level)
454 ignored <- c("packrat", "renv", "revdep", "vendor", if (depth) c("DESCRIPTION", "NAMESPACE"))
455 children <- children[!basename(children) %in% ignored]
456
457 # compute exclusions
458 excluded <- renv_renvignore_exec(path, root, children)
459
460 # keep only non-excluded children
461 children[!excluded]
462
463 }
464
465 renv_dependencies_find_dir_children_overload <- function(path, count) {
466
467 # check for missing state (e.g. if internal method called directly)
468 state <- renv_dependencies_state()
469 if (is.null(state))
470 return()
471
472 fmt <- "directory contains %s; consider ignoring this directory"
473 msg <- sprintf(fmt, nplural("file", count))
474 error <- simpleError(message = msg)
475
476 path <- path %||% state$path
477 problem <- list(file = path, error = error)
478 state$problems$push(problem)
479
480 }
481
482 renv_dependencies_discover <- function(paths, progress, errors) {
483
484 if (!renv_dependencies_discover_preflight(paths, errors))
485 return(invisible(list()))
486
487 # short path if we're not showing progress
488 if (identical(progress, FALSE))
489 return(bapply(paths, renv_dependencies_discover_impl))
490
491 # otherwise, run with progress reporting
492
493 # nocov start
494 printf("Finding R package dependencies ... ")
495 callback <- renv_progress_callback(renv_dependencies_discover_impl, length(paths))
496 deps <- lapply(paths, callback)
497 writef("Done!")
498
499 bind(deps)
500 # nocov end
501
502 }
503
504 renv_dependencies_discover_impl <- function(path) {
505
506 callback <- renv_dependencies_callback(path)
507 if (is.null(callback)) {
508 return(NULL)
509 }
510
511 status <- catch(filebacked("dependencies", path, callback))
512 if (inherits(status, "error")) {
513 signalCondition(warnify(status))
514 NULL
515 }
516
517 status
518
519 }
520
521 renv_dependencies_discover_preflight <- function(paths, errors) {
522
523 if (identical(errors, "ignored"))
524 return(TRUE)
525
526 if (length(paths) < config$dependencies.limit())
527 return(TRUE)
528
529 lines <- c(
530 "A large number of files (%i in total) have been discovered.",
531 "It may take renv a long time to scan these files for dependencies.",
532 "Consider using .renvignore to ignore irrelevant files.",
533 "See `?renv::dependencies` for more information.",
534 "Set `options(renv.config.dependencies.limit = Inf)` to disable this warning.",
535 ""
536 )
537 writef(lines, length(paths))
538
539 if (identical(errors, "reported"))
540 return(TRUE)
541
542 cancel_if(interactive() && !proceed())
543
544 TRUE
545
546 }
547
548 renv_dependencies_discover_renv_lock <- function(path) {
549 renv_dependencies_list(path, "renv")
550 }
551
552 renv_dependencies_discover_description_fields <- function(path, project = NULL) {
553
554 # most callers don't pass in project so we need to get it from global state
555 project <- project %||%
556 renv_dependencies_state(key = "root") %||%
557 renv_restore_state(key = "root") %||%
558 renv_project_resolve()
559
560 # by default, respect fields defined in settings
561 fields <- settings$package.dependency.fields(project = project)
562
563 # if this appears to be the DESCRIPTION associated with the active project,
564 # and an explicit set of dependencies was provided in install, then use those
565 if (renv_path_same(file.path(project, "DESCRIPTION"), path)) {
566 default <- the$install_dependency_fields %||% c(fields, "Suggests")
567 profile <- sprintf("Config/renv/profiles/%s/dependencies", renv_profile_get())
568 fields <- c(default, profile)
569 }
570
571 fields
572
573 }
574
575 renv_dependencies_discover_description <- function(path,
576 fields = NULL,
577 subdir = NULL,
578 project = NULL)
579 {
580 dcf <- catch(renv_description_read(path = path, subdir = subdir))
581 if (inherits(dcf, "error"))
582 return(renv_dependencies_error(path, error = dcf))
583
584 # resolve the dependency fields to be used
585 fields <- fields %||% renv_dependencies_discover_description_fields(path, project)
586
587 # make sure dependency fields are expanded
588 fields <- renv_dependencies_fields(fields)
589
590 data <- map(
591 fields,
592 renv_dependencies_discover_description_impl,
593 dcf = dcf,
594 path = path
595 )
596
597 names(data) <- fields
598
599 # if this is a bioconductor package, add their implicit dependencies
600 # guard against packages which have an empty biocViews field
601 # https://github.com/rstudio/renv/issues/2149
602 if (nzchar(dcf[["biocViews"]] %||% "")) {
603 data[[length(data) + 1L]] <- renv_dependencies_list(
604 source = path,
605 packages = c(renv_bioconductor_manager(), "BiocVersion")
606 )
607 names(data)[[length(data)]] <- "Bioconductor"
608 }
609
610 bind(data, index = "Type")
611 }
612
613 renv_dependencies_discover_namespace <- function(path) {
614
615 tryCatch(
616 renv_dependencies_discover_namespace_impl(path),
617 error = warnify
618 )
619
620 }
621
622 renv_dependencies_discover_namespace_impl <- function(path) {
623
624 # parseNamespaceFile() expects to be called on an installed package,
625 # so we have to pretend our best here
626 library <- dirname(dirname(path))
627 package <- basename(dirname(path))
628 info <- parseNamespaceFile(
629 package = package,
630 package.lib = library,
631 mustExist = TRUE
632 )
633
634 # read package names from imports
635 packages <- map_chr(info$imports, `[[`, 1L)
636
637 renv_dependencies_list(
638 source = path,
639 packages = sort(unique(packages))
640 )
641
642 }
643
644 renv_dependencies_discover_description_impl <- function(dcf, field, path) {
645
646 # read field
647 contents <- dcf[[field]]
648 if (!is.character(contents))
649 return(list())
650
651 # split on commas
652 parts <- strsplit(dcf[[field]], "\\s*,\\s*")[[1]]
653
654 # drop any empty fields
655 x <- parts[nzchar(parts)]
656
657 # match to split on remote, version
658 pattern <- paste0(
659 "([^,\\([:space:]]+)", # remote name
660 "(?:\\s*\\(([><=]+)\\s*([0-9.-]+)\\))?" # optional version specification
661 )
662
663 m <- regexec(pattern, x)
664 matches <- regmatches(x, m)
665 if (empty(matches))
666 return(list())
667
668 # drop R (https://github.com/rstudio/renv/issues/1806)
669 matches <- filter(matches, function(match) {
670 !identical(match[[2L]], "R")
671 })
672
673 if (empty(matches))
674 return(list())
675
676 # create dependency list
677 renv_dependencies_list(
678 path,
679 extract_chr(matches, 2L),
680 extract_chr(matches, 3L),
681 extract_chr(matches, 4L),
682 dev = field == "Suggests"
683 )
684
685 }
686
687 renv_dependencies_discover_bookdown <- function(path) {
688 # TODO: other dependencies to parse from bookdown?
689 renv_dependencies_list(path, "bookdown")
690 }
691
692 renv_dependencies_discover_pkgdown <- function(path) {
693 # TODO: other dependencies to parse from pkgdown?
694 renv_dependencies_list(path, "pkgdown")
695 }
696
697 renv_dependencies_discover_quarto <- function(path) {
698 # TODO: other dependencies to parse from quarto?
699 #
700 # NOTE: we previously inferred a dependency on the R 'quarto' package here,
701 # but quarto is normally invoked directly (rather than via the package) and
702 # so such a dependency is not strictly necessary.
703 #
704 # https://github.com/rstudio/renv/issues/995
705 renv_dependencies_list_empty()
706 }
707
708 renv_dependencies_discover_plumber_server <- function(path) {
709 # require yaml package for parsing YAML
710 if (!renv_dependencies_require("yaml", basename(path)))
711 return(renv_dependencies_list_empty())
712
713 # read and parse yaml file
714 contents <- catch(yaml::read_yaml(path))
715 if (inherits(contents, "error"))
716 return(renv_dependencies_error(path, error = contents))
717
718 # check if engine field exists and has a value
719 engine <- contents$engine
720 if (!pstring(engine) || !nzchar(engine))
721 return(renv_dependencies_list_empty())
722
723 # return the engine as a dependency
724 renv_dependencies_list(path, engine)
725 }
726
727 renv_dependencies_discover_rsconnect <- function(path) {
728 renv_dependencies_list(path, "rsconnect")
729 }
730
731 renv_dependencies_discover_multimode <- function(path, mode) {
732
733 # TODO: find in-line R code?
734 deps <- stack()
735
736 if (mode %in% c("rmd", "qmd"))
737 deps$push(renv_dependencies_discover_rmd_yaml_header(path, mode))
738
739 deps$push(renv_dependencies_discover_chunks(path, mode))
740
741 bind(Filter(NROW, deps$data()))
742
743 }
744
745 renv_dependencies_discover_rmd_yaml_header <- function(path, mode) {
746
747 deps <- stack(mode = "character")
748
749 # R Markdown documents always depend on rmarkdown
750 if (identical(mode, "rmd"))
751 deps$push("rmarkdown")
752
753 # try and read the document's YAML header
754 contents <- renv_file_read(path)
755 pattern <- "(?:^|\n)\\s*---\\s*(?:$|\n)"
756 matches <- gregexpr(pattern, contents, perl = TRUE)[[1L]]
757
758 # check that we have something that looks like a YAML header
759 ok <- length(matches) > 1L && matches[[1L]] == 1L
760 if (!ok)
761 return(renv_dependencies_list(path, packages = deps$data()))
762
763 # require yaml package for parsing YAML header
764 name <- case(
765 mode == "rmd" ~ "R Markdown",
766 mode == "qmd" ~ "Quarto Markdown"
767 )
768
769 # validate that we actually have the yaml package available
770 if (!renv_dependencies_require("yaml", name)) {
771 packages <- deps$data()
772 return(renv_dependencies_list(path, packages))
773 }
774
775 # extract YAML text
776 yamltext <- substring(contents, matches[[1L]] + 4L, matches[[2L]] - 1L)
777 yaml <- catch(renv_yaml_load(yamltext))
778 if (inherits(yaml, "error"))
779 return(renv_dependencies_error(path, error = yaml, packages = "rmarkdown"))
780
781 # https://github.com/rstudio/renv/issues/2117
782 if (!is.list(yaml)) {
783 msg <- "document contains an unexpected or malformed YAML header"
784 return(renv_dependencies_error(path, error = msg, packages = "rmarkdown"))
785 }
786
787 # check for Shiny runtime
788 runtime <- yaml[["runtime"]] %||% ""
789 if (pstring(runtime) && grepl("shiny", runtime, fixed = TRUE))
790 deps$push("shiny")
791
792 server <- yaml[["server"]] %||% ""
793 if (identical(server, "shiny"))
794 deps$push("shiny")
795
796 if (is.list(server) && identical(server[["type"]], "shiny"))
797 deps$push("shiny")
798
799 pattern <- renv_regexps_package_name()
800
801 # check recursively for package usages of the form 'package::method'
802 recurse(yaml, function(node) {
803 # look for keys of the form 'package::method'
804 values <- c(names(node), if (pstring(node)) node)
805 for (value in values) {
806 call <- tryCatch(parse(text = value)[[1]], error = function(err) NULL)
807 if (renv_call_matches(call, names = c("::", ":::"), nargs = 2L)) {
808 deps$push(as.character(call[[2L]]))
809 }
810 }
811
812 })
813
814 # check for dependency on bslib
815 theme <- catchall(yaml[[c("output", "html_document", "theme")]])
816 if (!inherits(theme, "error") && is.list(theme))
817 deps$push("bslib")
818
819 # check for parameterized documents
820 status <- catch(renv_dependencies_discover_rmd_yaml_header_params(yaml, deps))
821 if (inherits(status, "error"))
822 renv_dependencies_error_push(path, status)
823
824 # get list of dependencies
825 packages <- deps$data()
826 renv_dependencies_list(path, packages)
827
828 }
829
830 renv_dependencies_discover_rmd_yaml_header_params <- function(yaml, deps) {
831
832 # check for declared params
833 params <- yaml[["params"]]
834 if (!is.list(params))
835 return()
836
837 # infer dependency on shiny
838 deps$push("shiny")
839
840 # iterate through params, parsing dependencies from R code
841 for (param in params) {
842
843 # check for r types
844 type <- attr(param, "type", exact = TRUE)
845 if (!identical(type, "r"))
846 next
847
848 # attempt to parse dependencies
849 rdeps <- catch(renv_dependencies_discover_r(text = param))
850 if (inherits(rdeps, "error"))
851 next
852
853 # add each dependency
854 for (package in sort(unique(rdeps$Package)))
855 deps$push(package)
856
857 }
858
859 }
860
861 renv_dependencies_discover_chunks_ignore <- function(chunk) {
862
863 # if renv.ignore is set, respect it
864 ignore <- chunk$params[["renv.ignore"]]
865 if (!is.null(ignore))
866 return(truthy(ignore))
867
868 # skip non-R chunks
869 engine <- chunk$params[["engine"]]
870 ok <- is.character(engine) && tolower(engine) %in% c("r", "rscript")
871 if (!ok)
872 return(TRUE)
873
874 # skip un-evaluated chunks
875 if (!truthy(chunk$params[["eval"]], default = TRUE))
876 return(TRUE)
877
878 # skip learnr exercises
879 if (truthy(chunk$params[["exercise"]], default = FALSE))
880 return(TRUE)
881
882 # skip chunks whose labels end in '-display'
883 label <- chunk$params[["label"]]
884 if (is.character(label) &&
885 length(label) == 1L &&
886 grepl("-display$", label))
887 {
888 return(TRUE)
889 }
890
891 # ok, don't ignore this chunk
892 FALSE
893
894 }
895
896 renv_dependencies_discover_chunks <- function(path, mode) {
897
898 # figure out the appropriate begin, end patterns
899 type <- tolower(file_ext(path))
900 if (type %in% c("rmd", "qmd", "rmarkdown"))
901 type <- "md"
902
903 allpatterns <- renv_knitr_patterns()
904 patterns <- allpatterns[[type]]
905 if (is.null(patterns)) {
906 condition <- simpleCondition("not a recognized multi-mode R document")
907 return(renv_dependencies_error(path, error = condition))
908 }
909
910 # parse the chunks within
911 # NOTE: we need to proceed line-by-line since the chunk end pattern might
912 # end chunks not started by the chunk begin pattern (sad face)
913 encoding <- if (type == "md") "UTF-8" else "unknown"
914 contents <- readLines(path, warn = FALSE, encoding = encoding)
915 ranges <- renv_dependencies_discover_chunks_ranges(path, contents, patterns)
916
917 # extract chunk code from the used ranges
918 chunks <- .mapply(function(lhs, rhs) {
919
920 # parse params in header
921 header <- contents[[lhs]]
922 params <- renv_knitr_options_header(header, type)
923
924 # extract chunk contents (preserve newlines for nicer error reporting)
925 range <- seq.int(lhs + 1, length.out = rhs - lhs - 1)
926 code <- rep.int("", length(contents))
927 code[range] <- contents[range]
928
929 # also parse chunk options
930 params <- overlay(params, renv_knitr_options_chunk(code))
931
932 # return list of outputs
933 list(params = params, code = code)
934
935 }, ranges, NULL)
936
937 # iterate over chunks, and attempt to parse dependencies from each
938 cdeps <- bapply(chunks, function(chunk) {
939
940 # check whether this chunk should be ignored
941 if (renv_dependencies_discover_chunks_ignore(chunk))
942 return(character())
943
944 # remove reused chunk placeholders
945 pattern <- "<<[^>]+>>"
946 code <- gsub(pattern, "", chunk$code)
947
948 # okay, now we can discover deps
949 deps <- catch(renv_dependencies_discover_r(path = path, text = code))
950 if (inherits(deps, "error"))
951 return(renv_dependencies_error(path, error = deps))
952
953 deps
954
955 })
956
957 # check for dependencies in inline chunks as well
958 ideps <- renv_dependencies_discover_chunks_inline(path, contents)
959
960 # if this is a .qmd, infer a dependency on rmarkdown if we have any R chunks
961 qdeps <- NULL
962 if (mode %in% "qmd") {
963 for (chunk in chunks) {
964 engine <- chunk$params[["engine"]]
965 if (is.character(engine) && tolower(engine) %in% c("r", "rscript")) {
966 qdeps <- renv_dependencies_list(path, "rmarkdown")
967 break
968 }
969 }
970 }
971
972 # paste them all together
973 deps <- bind(list(cdeps, ideps, qdeps))
974 if (is.null(deps))
975 return(deps)
976
977 deps$Source <- path
978 deps
979
980 }
981
982 renv_dependencies_discover_chunks_inline <- function(path, contents) {
983
984 pasted <- paste(contents, collapse = "\n")
985 matches <- gregexpr("`r ([^`]+)`", pasted, perl = TRUE)
986 if (identical(c(matches[[1L]]), -1L))
987 return(list())
988
989 text <- unlist(regmatches(pasted, matches), use.names = FALSE, recursive = FALSE)
990 code <- substring(text, 4L, nchar(text) - 1L)
991 deps <- renv_dependencies_discover_r(path = path, text = code)
992 if (inherits(deps, "error"))
993 return(renv_dependencies_error(path, error = deps))
994
995 deps
996
997 }
998
999 renv_dependencies_discover_chunks_ranges <- function(path, contents, patterns) {
1000
1001 output <- list()
1002
1003 chunk <- FALSE
1004 start <- 1; end <- 1
1005 for (i in seq_along(contents)) {
1006
1007 line <- contents[[i]]
1008
1009 if (chunk == FALSE && grepl(patterns$chunk.begin, line)) {
1010 chunk <- TRUE
1011 start <- i
1012 next
1013 }
1014
1015 if (chunk == TRUE && grepl(patterns$chunk.begin, line)) {
1016 end <- i
1017 output[[length(output) + 1]] <- list(lhs = start, rhs = end)
1018 start <- i
1019 next
1020 }
1021
1022 if (chunk == TRUE && grepl(patterns$chunk.end, line)) {
1023 chunk <- FALSE
1024 end <- i
1025 output[[length(output) + 1]] <- list(lhs = start, rhs = end)
1026 next
1027 }
1028
1029 }
1030
1031 if (chunk) {
1032 message <- sprintf("chunk starting on line %i is not closed", start)
1033 error <- simpleError(message)
1034 renv_dependencies_error(path, error = error)
1035 }
1036
1037 bind(output)
1038
1039 }
1040
1041 renv_dependencies_discover_ipynb <- function(path) {
1042
1043 json <- catch(renv_json_read(path))
1044 if (inherits(json, "error")) {
1045 info <- renv_file_info(path)
1046 if (!is.na(info$size) && info$size > 1)
1047 renv_dependencies_error(path, error = json)
1048 }
1049
1050 if (!identical(json$metadata$kernelspec$language, "R"))
1051 return()
1052
1053 deps <- stack()
1054 if (identical(json$metadata$kernelspec$name, "ir"))
1055 deps$push(renv_dependencies_list(path, "IRkernel"))
1056
1057 for (cell in json$cells) {
1058 if (cell$cell_type != "code")
1059 next
1060
1061 code <- paste0(cell$source, collapse = "")
1062 deps$push(renv_dependencies_discover_r(path, text = code))
1063 }
1064
1065 bind(deps$data())
1066
1067 }
1068
1069 renv_dependencies_discover_rproj <- function(path) {
1070
1071 props <- renv_properties_read(path)
1072
1073 deps <- stack()
1074 if (identical(props$PackageUseDevtools, "Yes")) {
1075 deps$push("devtools")
1076 deps$push("roxygen2")
1077 }
1078
1079 renv_dependencies_list(path, deps$data(), dev = TRUE)
1080
1081 }
1082
1083 renv_dependencies_discover_lintr <- function(path) {
1084 renv_dependencies_list(path, "lintr", dev = TRUE)
1085 }
1086
1087 renv_dependencies_discover_r <- function(path = NULL,
1088 text = NULL,
1089 expr = NULL,
1090 envir = NULL,
1091 dev = NULL)
1092 {
1093 expr <- case(
1094 is.function(expr) ~ body(expr),
1095 is.language(expr) ~ expr,
1096 is.character(expr) ~ catch(renv_parse_text(expr)),
1097 is.character(text) ~ catch(renv_parse_text(text)),
1098 is.character(path) ~ catch(renv_parse_file(path)),
1099 ~ stop("internal error")
1100 )
1101
1102 if (inherits(expr, "error"))
1103 return(renv_dependencies_error(path, error = expr))
1104
1105 # resolve dev
1106 dev <- dev %||% path == the$paths$r_profile_user
1107
1108 # update current path
1109 state <- renv_dependencies_state()
1110 if (!is.null(state))
1111 renv_scope_binding(state, "path", path)
1112
1113 methods <- c(
1114 renv_dependencies_discover_r_methods,
1115 renv_dependencies_discover_r_xfun,
1116 renv_dependencies_discover_r_library_require,
1117 renv_dependencies_discover_r_require_namespace,
1118 renv_dependencies_discover_r_colon,
1119 renv_dependencies_discover_r_citation,
1120 renv_dependencies_discover_r_system_file,
1121 renv_dependencies_discover_r_data,
1122 renv_dependencies_discover_r_pacman,
1123 renv_dependencies_discover_r_modules,
1124 renv_dependencies_discover_r_import,
1125 renv_dependencies_discover_r_use,
1126 renv_dependencies_discover_r_targets,
1127 renv_dependencies_discover_r_glue,
1128 renv_dependencies_discover_r_ggplot2,
1129 renv_dependencies_discover_r_parsnip,
1130 renv_dependencies_discover_r_testthat,
1131 renv_dependencies_discover_r_knitr,
1132 renv_dependencies_discover_r_database
1133 )
1134
1135 envir <- envir %||% new.env(parent = emptyenv())
1136 callback <- if (renv_ext_enabled()) {
1137
1138 function(node) {
1139 node <- renv_call_normalize(node)
1140 for (method in methods)
1141 method(node, envir)
1142 invisible(node)
1143 }
1144
1145 } else {
1146
1147 function(node) {
1148
1149 node <- renv_call_normalize(node)
1150 for (method in methods)
1151 method(node, envir)
1152
1153 assign("object", node, envir = parent.frame())
1154 invisible(node)
1155
1156 }
1157
1158 }
1159
1160 renv_dependencies_recurse(expr, callback)
1161 packages <- ls(envir = envir, all.names = TRUE)
1162
1163 # also try to detect knitr::spin() dependencies -- this needs to
1164 # happen outside of the regular dependency discovery machinery
1165 # as it will rely on checking comments in the document
1166 #
1167 # https://github.com/rstudio/renv/issues/2023
1168 if (is.character(text) || is.character(path)) {
1169 text <- text %||% readLines(path, n = 1L, warn = FALSE)
1170 if (length(text) && grepl("^\\s*#'\\s*[-]{3}\\s*$", text[[1L]], perl = TRUE))
1171 packages <- union(c("knitr", "rmarkdown"), packages)
1172 }
1173
1174 renv_dependencies_list(path, packages, dev = dev)
1175 }
1176
1177 renv_dependencies_discover_r_methods <- function(node, envir) {
1178
1179 node <- renv_call_expect(node, "methods", c("setClass", "setGeneric"))
1180 if (is.null(node))
1181 return(FALSE)
1182
1183 envir[["methods"]] <- TRUE
1184 TRUE
1185
1186 }
1187
1188 renv_dependencies_discover_r_xfun <- function(node, envir) {
1189
1190 node <- renv_call_expect(node, "xfun", c("pkg_attach", "pkg_attach2"))
1191 if (is.null(node))
1192 return(FALSE)
1193
1194 # attempt to match the call
1195 prototype <- function(..., install = FALSE, message = TRUE) {}
1196 matched <- catch(match.call(prototype, node, expand.dots = FALSE))
1197 if (inherits(matched, "error"))
1198 return(FALSE)
1199
1200 # extract character vectors from `...`
1201 strings <- stack()
1202 recurse(matched[["..."]], function(node) {
1203 if (is.character(node))
1204 strings$push(node)
1205 })
1206
1207 # mark packages as known
1208 packages <- strings$data()
1209 if (empty(packages))
1210 return(FALSE)
1211
1212 for (package in packages)
1213 envir[[package]] <- TRUE
1214
1215 TRUE
1216 }
1217
1218 renv_dependencies_discover_r_library_require <- function(node, envir) {
1219
1220 node <- renv_call_expect(node, "base", c("library", "require"))
1221 if (is.null(node))
1222 return(FALSE)
1223
1224 # attempt to match the call
1225 matched <- catch(match.call(base::library, node))
1226 if (inherits(matched, "error"))
1227 return(FALSE)
1228
1229 # if the 'package' argument is a character vector of length one, we're done
1230 if (is.character(matched$package) &&
1231 length(matched$package) == 1)
1232 {
1233 envir[[matched$package]] <- TRUE
1234 return(TRUE)
1235 }
1236
1237 # if it's a symbol, double check character.only argument
1238 if (is.symbol(matched$package) &&
1239 identical(matched$character.only %||% FALSE, FALSE))
1240 {
1241 envir[[as.character(matched$package)]] <- TRUE
1242 return(TRUE)
1243 }
1244
1245 FALSE
1246
1247 }
1248
1249 renv_dependencies_discover_r_require_namespace <- function(node, envir) {
1250
1251 node <- renv_call_expect(node, "base", c("requireNamespace", "loadNamespace"))
1252 if (is.null(node))
1253 return(FALSE)
1254
1255 f <- get(as.character(node[[1]]), envir = .BaseNamespaceEnv, inherits = FALSE)
1256 matched <- catch(match.call(f, node))
1257 if (inherits(matched, "error"))
1258 return(FALSE)
1259
1260 package <- matched$package
1261 if (is.character(package) && length(package == 1)) {
1262 envir[[package]] <- TRUE
1263 return(TRUE)
1264 }
1265
1266 FALSE
1267
1268
1269 }
1270
1271 renv_dependencies_discover_r_colon <- function(node, envir) {
1272
1273 ok <- renv_call_matches(node, names = c("::", ":::"), nargs = 2L)
1274 if (!ok)
1275 return(FALSE)
1276
1277 package <- node[[2L]]
1278 if (is.symbol(package))
1279 package <- as.character(package)
1280
1281 if (!is.character(package) || length(package) != 1L)
1282 return(FALSE)
1283
1284 envir[[package]] <- TRUE
1285 TRUE
1286
1287 }
1288
1289 renv_dependencies_discover_r_citation <- function(node, envir) {
1290
1291 node <- renv_call_expect(node, "utils", "citation")
1292 if (is.null(node))
1293 return(FALSE)
1294
1295 matched <- catch(match.call(utils::citation, node))
1296 if (inherits(matched, "error"))
1297 return(FALSE)
1298
1299 package <- matched[["package"]]
1300 if (!is.character(package) || length(package) != 1L)
1301 return(FALSE)
1302
1303 envir[[package]] <- TRUE
1304 TRUE
1305
1306 }
1307
1308 renv_dependencies_discover_r_system_file <- function(node, envir) {
1309
1310 node <- renv_call_expect(node, "base", "system.file")
1311 if (is.null(node))
1312 return(FALSE)
1313
1314 matched <- catch(match.call(base::system.file, node))
1315 if (inherits(matched, "error"))
1316 return(FALSE)
1317
1318 package <- matched[["package"]]
1319 if (!is.character(package) || length(package) != 1L)
1320 return(FALSE)
1321
1322 envir[[package]] <- TRUE
1323 TRUE
1324
1325 }
1326
1327 renv_dependencies_discover_r_data <- function(node, envir) {
1328
1329 node <- renv_call_expect(node, "utils", "data")
1330 if (is.null(node))
1331 return(FALSE)
1332
1333 matched <- catch(match.call(utils::data, node))
1334 if (inherits(matched, "error"))
1335 return(FALSE)
1336
1337 package <- matched[["package"]]
1338 if (!is.character(package) || length(package) != 1L)
1339 return(FALSE)
1340
1341 envir[[package]] <- TRUE
1342 TRUE
1343
1344 }
1345
1346 renv_dependencies_discover_r_pacman <- function(node, envir) {
1347
1348 node <- renv_call_expect(node, "pacman", "p_load")
1349 if (is.null(node) || length(node) < 2)
1350 return(FALSE)
1351
1352 # check for character.only
1353 chonly <- node[["character.only"]] %||% FALSE
1354
1355 # consider all unnamed arguments
1356 parts <- as.list(node[-1L])
1357
1358 # consider packages passed to 'char' parameter
1359 char <- node[["char"]]
1360
1361 # detect vector of packages passed as vector
1362 if (renv_call_matches(char, "c"))
1363 parts <- c(parts, as.list(char[-1L]))
1364
1365 # detect plain old package name
1366 if (is.character(char))
1367 parts <- c(parts, as.list(char))
1368
1369 # ensure names
1370 names(parts) <- names(parts) %||% rep.int("", length(parts))
1371 unnamed <- parts[!nzchar(names(parts))]
1372
1373 # extract symbols / characters
1374 for (arg in unnamed) {
1375
1376 # skip symbols if necessary
1377 if (chonly && is.symbol(arg))
1378 next
1379
1380 # check for character or symbol
1381 ok <-
1382 length(arg) == 1 &&
1383 is.character(arg) ||
1384 is.symbol(arg)
1385
1386 if (!ok)
1387 next
1388
1389 # add it
1390 envir[[as.character(arg)]] <- TRUE
1391
1392 }
1393
1394 TRUE
1395
1396 }
1397
1398 renv_dependencies_discover_r_modules <- function(node, envir) {
1399
1400 # check for an explicit call to 'modules::import()'
1401 if (identical(node[[1L]], quote(modules::import))) {
1402 renv_dependencies_discover_r_modules_impl(node, envir)
1403 }
1404
1405 # check for 'import' usages with a module block
1406 node <- renv_call_expect(node, "modules", "module")
1407 if (length(node) >= 2L &&
1408 identical(node[[1L]], quote(module)) &&
1409 is.call(node[[2L]]) &&
1410 identical(node[[2L]][[1L]], as.symbol("{")))
1411 {
1412 renv_dependencies_recurse(node[[2L]], function(node) {
1413 renv_dependencies_discover_r_modules_impl(node, envir)
1414 })
1415 }
1416
1417 }
1418
1419 renv_dependencies_discover_r_modules_impl <- function(node, envir) {
1420
1421 node <- renv_call_expect(node, "modules", c("import"))
1422 if (is.null(node))
1423 return(FALSE)
1424
1425 # attempt to match the call
1426 prototype <- function(from, ..., attach = TRUE, where = parent.frame()) {}
1427 matched <- catch(match.call(prototype, node, expand.dots = FALSE))
1428 if (inherits(matched, "error"))
1429 return(FALSE)
1430
1431 # extract character vector or symbol from `from`
1432 package <- matched[["from"]]
1433 if (empty(package))
1434 return(FALSE)
1435
1436 # package could be symbols or character so call as.character
1437 # to be safe then mark packages as known
1438 envir[[as.character(package)]] <- TRUE
1439 TRUE
1440
1441 }
1442
1443 renv_dependencies_discover_r_import <- function(node, envir) {
1444
1445 # require that usages are colon-prefixed
1446 colon <- renv_call_matches(node[[1L]], names = c("::", ":::"), nargs = 2L)
1447 if (!colon)
1448 return(FALSE)
1449
1450 node <- renv_call_expect(node, "import", c("from", "here", "into"))
1451 if (is.null(node))
1452 return(FALSE)
1453
1454 # attempt to match the call
1455 name <- as.character(node[[1L]])
1456 matched <- if (name == "from") {
1457 catch(match.call(function(.from, ...) {}, node, expand.dots = FALSE))
1458 } else {
1459 catch(match.call(function(..., .from) {}, node, expand.dots = FALSE))
1460 }
1461
1462 if (inherits(matched, "error"))
1463 return(FALSE)
1464
1465 # the '.from' argument is the package name
1466 # either a character vector of length one or a symbol
1467 from <- matched$.from
1468 if (is.symbol(from)) {
1469 co <- node[[".character_only"]]
1470 if (!identical(co, TRUE))
1471 from <- as.character(from)
1472 }
1473
1474 ok <- is.character(from) && length(from) == 1L
1475 if (!ok)
1476 return(FALSE)
1477
1478 # '.from' can also be an R script; if it appears to be a path, then ignore it
1479 # this is unfortunately problematic for some packages like 'treesitter.r'
1480 #
1481 # https://github.com/rstudio/renv/issues/1743
1482 # https://github.com/rstudio/renv/issues/2212
1483 if (grepl("\\.[rR]$", from, perl = TRUE))
1484 return(FALSE)
1485
1486 envir[[from]] <- TRUE
1487 TRUE
1488
1489 }
1490
1491 renv_dependencies_discover_r_use <- function(node, envir) {
1492
1493 # There are multiple possible packages providing a function called 'use'.
1494 # renv will currently assume that any invocation of 'use' without a
1495 # package prefix is one that belongs to 'base'.
1496 if (is.call(node) && identical(node[[1L]], as.symbol("use")))
1497 return(renv_dependencies_discover_r_use_base(node, envir))
1498
1499 # `base::use()`
1500 m <- renv_call_expect(node, "base", "use")
1501 if (length(m))
1502 return(renv_dependencies_discover_r_use_base(m, envir))
1503
1504 # `renv::use()`
1505 m <- renv_call_expect(node, "renv", "use")
1506 if (length(m)) {
1507 pkgs <- setdiff(names(m), names(formals(renv::use)))
1508 for (pkg in pkgs)
1509 if (nzchar(pkg))
1510 envir[[pkg]] <- TRUE
1511 return(TRUE)
1512 }
1513
1514 # `box::use()`
1515 m <- renv_call_expect(node, "box", "use")
1516 if (length(m)) {
1517 for (i in seq.int(2L, length.out = length(m) - 1L))
1518 renv_dependencies_discover_r_use_box(m[[i]], envir)
1519 return(TRUE)
1520 }
1521
1522 # no implementation matched
1523 FALSE
1524
1525 }
1526
1527 renv_dependencies_discover_r_use_base <- function(node, envir) {
1528
1529 # attempt to match the call
1530 matched <- tryCatch(
1531 match.call(function(package, include.only) {}, node),
1532 error = identity
1533 )
1534
1535 if (inherits(matched, "error"))
1536 return(FALSE)
1537
1538 # check for a character argument
1539 package <- matched[["package"]]
1540 if (!is.character(package))
1541 return(FALSE)
1542
1543 # add to dependency set
1544 envir[[package]] <- TRUE
1545 TRUE
1546
1547 }
1548
1549 renv_dependencies_discover_r_use_box <- function(node, envir) {
1550
1551 # if the call uses /, it's a path, not a package
1552 if (renv_call_matches(node, "/"))
1553 return(FALSE)
1554
1555 # if the node is just a symbol, then it's the name of a package
1556 # otherwise, if it's a call to `[`, the first argument is the package name
1557 name <- if (is.symbol(node) && !identical(node, quote(expr = ))) {
1558 as.character(node)
1559 } else if (
1560 renv_call_matches(node, "[") &&
1561 length(node) > 1L &&
1562 is.symbol(node[[2L]])) {
1563 as.character(node[[2L]])
1564 }
1565
1566 # the names `.` and `..` are special place holders and don't refer to packages
1567 if (is.null(name) || name == "." || name == "..")
1568 return(FALSE)
1569
1570 envir[[name]] <- TRUE
1571 TRUE
1572
1573 }
1574
1575 renv_dependencies_discover_r_targets <- function(node, envir) {
1576
1577 node <- renv_call_expect(node, "targets", "tar_option_set")
1578 if (is.null(node))
1579 return(FALSE)
1580
1581 envir[["targets"]] <- TRUE
1582
1583 packages <- tryCatch(
1584 renv_dependencies_eval(node$packages),
1585 error = identity
1586 )
1587
1588 # TODO: evaluation can fail for a multitude of reasons;
1589 # are any of these worth signalling to the user?
1590 if (inherits(packages, "error"))
1591 return(TRUE)
1592
1593 if (is.character(packages))
1594 for (package in packages)
1595 envir[[package]] <- TRUE
1596
1597 TRUE
1598
1599 }
1600
1601 renv_dependencies_discover_r_glue <- function(node, envir) {
1602
1603 node <- renv_call_expect(node, "glue", "glue")
1604 if (is.null(node))
1605 return(FALSE)
1606
1607 # analyze all unnamed strings in the call
1608 args <- as.list(node)[-1L]
1609 nm <- names(args) %||% rep.int("", length(args))
1610 strings <- args[!nzchar(nm) & map_lgl(args, is.character)]
1611
1612 # start iterating through the strings, looking for code chunks
1613 for (string in strings)
1614 renv_dependencies_discover_r_glue_impl(string, node, envir)
1615
1616 TRUE
1617
1618 }
1619
1620 renv_dependencies_discover_r_ggplot2 <- function(node, envir) {
1621
1622 node <- renv_call_expect(node, "ggplot2", "ggsave")
1623 if (is.null(node))
1624 return(FALSE)
1625
1626 # check for attempts to save to '.svg', and assume svglite is
1627 # required in this scenario.
1628 matched <- catch(match.call(function(filename, ...) {}, node))
1629 if (inherits(matched, "error"))
1630 return(FALSE)
1631
1632 filename <- matched$filename
1633 if (!is.character(filename))
1634 return(FALSE)
1635
1636 if (!endsWith(filename, ".svg"))
1637 return(FALSE)
1638
1639 envir[["svglite"]] <- TRUE
1640 TRUE
1641
1642 }
1643
1644 renv_dependencies_discover_r_testthat <- function(node, envir) {
1645
1646 # check for construction of JunitReporter
1647 if (identical(node, quote(JunitReporter$new))) {
1648 envir[["xml2"]] <- TRUE
1649 return(TRUE)
1650 }
1651
1652 # check for an R6 class inheriting from a JunitReporter
1653 class <- renv_call_expect(node, "R6", "R6Class")
1654 if (!is.null(class) && identical(class$inherit, quote(JunitReporter))) {
1655 envir[["xml2"]] <- TRUE
1656 return(TRUE)
1657 }
1658
1659 # check for calls to various test runners, which accept a reporter
1660 node <- renv_call_expect(node, "testthat", c("test_package", "test_dir", "test_file"))
1661 if (is.null(node))
1662 return(FALSE)
1663
1664 candidates <- list(
1665 "Junit",
1666 "junit",
1667 quote(JunitReporter),
1668 quote(testthat::JunitReporter)
1669 )
1670
1671 reporter <- node$reporter
1672 if (!is.null(reporter)) {
1673 for (candidate in candidates) {
1674 if (identical(candidate, reporter)) {
1675 envir[["xml2"]] <- TRUE
1676 return(TRUE)
1677 }
1678 }
1679 }
1680
1681 FALSE
1682
1683 }
1684
1685 renv_dependencies_discover_r_knitr <- function(node, envir) {
1686
1687 matched <- is.call(node) && (
1688 identical(node[[1L]], quote(knitr::opts_chunk$set)) ||
1689 identical(node[[1L]], quote(opts_chunk$set))
1690 )
1691
1692 if (!matched)
1693 return(FALSE)
1694
1695 args <- as.list(node)
1696 if (identical(args[["dev"]], "ragg_png")) {
1697 envir[["ragg"]] <- TRUE
1698 return(TRUE)
1699 }
1700
1701 FALSE
1702
1703 }
1704
1705 renv_dependencies_discover_r_glue_impl <- function(string, node, envir) {
1706
1707 # get open, close delimiters
1708 ropen <- charToRaw(node$.open %||% "{")
1709 rclose <- charToRaw(node$.close %||% "}")
1710 rcomment <- charToRaw(node$.comment %||% "#")
1711
1712 # constants
1713 rcomment <- charToRaw("#")
1714 rbackslash <- charToRaw("\\")
1715 rquotes <- c(
1716 charToRaw("'"),
1717 charToRaw("\""),
1718 charToRaw("`")
1719 )
1720
1721 # iterate through characters in string
1722 raw <- c(charToRaw(string), as.raw(0L))
1723 i <- 0L
1724 n <- length(raw)
1725 quote <- raw()
1726
1727 # index for open delimiter match
1728 index <- 0L
1729 count <- 0L
1730
1731 while (i < n) {
1732
1733 # ensure we always advance index
1734 i <- i + 1L
1735
1736 # handle quoted states
1737 if (length(quote)) {
1738
1739 # skip escaped characters
1740 if (raw[[i]] == rbackslash) {
1741 i <- i + 1L
1742 next
1743 }
1744
1745 # check for escape from quote
1746 if (raw[[i]] == quote) {
1747 quote <- raw()
1748 next
1749 }
1750
1751 }
1752
1753 # skip comments
1754 if (raw[[i]] == rcomment) {
1755 i <- grepRaw("(?:$|\n)", raw, i)
1756 next
1757 }
1758
1759 # skip escaped characters
1760 if (raw[[i]] == rbackslash) {
1761 i <- i + 1L
1762 next
1763 }
1764
1765 # check for quotes
1766 idx <- match(raw[[i]], rquotes, nomatch = 0L)
1767 if (idx > 0) {
1768 quote <- rquotes[[idx]]
1769 next
1770 }
1771
1772 # check for open delimiter
1773 if (i %in% grepRaw(ropen, raw, i, fixed = TRUE)) {
1774
1775 # check for duplicate (escape)
1776 j <- i + length(ropen)
1777 if (j %in% grepRaw(ropen, raw, j, fixed = TRUE)) {
1778 i <- j + length(ropen) - 1L
1779 next
1780 }
1781
1782 # save index if we're starting a match
1783 if (count == 0L) {
1784 index <- i
1785 }
1786
1787 # increment match count
1788 count <- count + 1L
1789 next
1790
1791 }
1792
1793 # check for close delimiter
1794 if (i %in% grepRaw(rclose, raw, i, fixed = TRUE)) {
1795
1796 # check for duplicate (escape)
1797 j <- i + length(rclose)
1798 if (j %in% grepRaw(rclose, raw, j, fixed = TRUE)) {
1799 i <- j + length(rclose) - 1L
1800 next
1801 }
1802
1803 if (count > 0L) {
1804
1805 # decrement count if we have a match
1806 count <- count - 1L
1807
1808 # check for match and parse dependencies within
1809 if (count == 0L) {
1810
1811 # extract inner code
1812 lhs <- index + length(ropen)
1813 rhs <- i - 1L
1814 code <- rawToChar(raw[lhs:rhs])
1815
1816 # parse dependencies
1817 renv_dependencies_discover_r(text = code, envir = envir)
1818
1819 }
1820
1821 }
1822
1823 }
1824
1825 }
1826
1827 }
1828
1829 renv_dependencies_discover_r_parsnip <- function(node, envir) {
1830
1831 node <- renv_call_expect(node, "parsnip", "set_engine")
1832 if (is.null(node))
1833 return(FALSE)
1834
1835 matched <- catch(match.call(function(object, engine, ...) {}, node))
1836 if (inherits(matched, "error"))
1837 return(FALSE)
1838
1839 engine <- matched$engine
1840 if (!is.character(engine) || length(engine) != 1L)
1841 return(FALSE)
1842
1843 map <- getOption("renv.parsnip.engines", default = list(
1844 glm = "stats",
1845 glmnet = "glmnet",
1846 keras = "keras",
1847 kknn = "kknn",
1848 nnet = "nnet",
1849 rpart = "rpart",
1850 spark = "sparklyr",
1851 stan = "rstanarm"
1852 ))
1853
1854 packages <- if (is.function(map))
1855 tryCatch(map(engine), error = function(e) NULL)
1856 else
1857 map[[engine]]
1858
1859 if (is.null(packages))
1860 return(FALSE)
1861
1862 for (package in packages)
1863 envir[[package]] <- TRUE
1864
1865 # TODO: a number of model routines appear to depend on dials;
1866 # should we just assume it's required by default? or should
1867 # users normally be using tidymodels instead of parsnip directly?
1868 TRUE
1869
1870 }
1871
1872 renv_dependencies_discover_r_database <- function(node, envir) {
1873
1874 found <- FALSE
1875
1876 matched <- function(requirements) {
1877 for (requirement in requirements)
1878 envir[[requirement]] <<- TRUE
1879 found <<- TRUE
1880 }
1881
1882 db <- renv_dependencies_database()
1883 enumerate(db, function(package, dependencies) {
1884 enumerate(dependencies, function(method, requirements) {
1885
1886 if (is.call(node)) {
1887 expect <- renv_call_expect(node, package, method)
1888 if (!is.null(expect))
1889 return(matched(requirements))
1890 }
1891
1892 if (is.symbol(node)) {
1893 value <- as.character(node)
1894 if (identical(value, method))
1895 return(matched(requirements))
1896 }
1897
1898 })
1899 })
1900
1901 found
1902
1903 }
1904
1905 renv_dependencies_database <- function() {
1906 the$dependencies_database <- the$dependencies_database %||% {
1907 db <- getOption("renv.dependencies.database", default = list())
1908 db$ggplot2$geom_hex <- "hexbin"
1909 db$testthat$JunitReporter <- "xml2"
1910 db
1911 }
1912 }
1913
1914 renv_dependencies_list <- function(source,
1915 packages,
1916 require = "",
1917 version = "",
1918 dev = FALSE)
1919 {
1920 if (empty(packages))
1921 return(renv_dependencies_list_empty())
1922
1923 source <- source %||% rep.int(NA_character_, length(packages))
1924
1925 data_frame(
1926 Source = as.character(source),
1927 Package = as.character(packages),
1928 Require = require,
1929 Version = version,
1930 Dev = dev
1931 )
1932
1933 }
1934
1935 renv_dependencies_list_empty <- function() {
1936
1937 data_frame(
1938 Source = character(),
1939 Package = character(),
1940 Require = character(),
1941 Version = character(),
1942 Dev = logical()
1943 )
1944
1945 }
1946
1947 renv_dependencies_require <- function(package, type = NULL) {
1948
1949 if (requireNamespace(package, quietly = TRUE))
1950 return(TRUE)
1951
1952 if (once()) {
1953
1954 fmt <- lines(
1955 "The '%1$s' package is required to parse dependencies within %2$s",
1956 "Consider installing it with `install.packages(\"%1$s\")`."
1957 )
1958
1959 within <- if (is.null(type)) "this project" else paste(type, "files")
1960 warningf(fmt, package, within)
1961
1962 }
1963
1964 return(FALSE)
1965
1966 }
1967
1968 the$dependencies_state <- NULL
1969
1970 renv_dependencies_state <- function(key = NULL) {
1971 state <- the$dependencies_state
1972 if (is.null(key)) state else state[[key]]
1973 }
1974
1975 renv_dependencies_scope <- function(root = NULL, scope = parent.frame()) {
1976 state <- env(root = root, scanned = env(), problems = stack())
1977 the$dependencies_state <- state
1978 defer(the$dependencies_state <- NULL, scope = scope)
1979 }
1980
1981 renv_dependencies_error_push <- function(path = NULL, error = NULL) {
1982
1983 state <- renv_dependencies_state()
1984 if (is.null(state))
1985 return()
1986
1987 path <- path %||% state$path
1988 problem <- list(file = path, error = error)
1989 state$problems$push(problem)
1990
1991 }
1992
1993 renv_dependencies_error <- function(path, error = NULL, packages = NULL) {
1994
1995 # if no error, return early
1996 if (is.null(error))
1997 return(renv_dependencies_list(path, packages))
1998
1999 # coerce character message errors
2000 if (is.character(error))
2001 error <- simpleError(error)
2002
2003 # push the error report
2004 renv_dependencies_error_push(path, error)
2005
2006 # return dependency list
2007 renv_dependencies_list(path, packages)
2008
2009 }
2010
2011 renv_dependencies_report <- function(errors) {
2012
2013 if (identical(errors, "ignored"))
2014 return(FALSE)
2015
2016 state <- renv_dependencies_state()
2017 if (is.null(state))
2018 return(FALSE)
2019
2020 problems <- state$problems$data()
2021 if (empty(problems))
2022 return(TRUE)
2023
2024 # bind into list
2025 bound <- bapply(problems, function(problem) {
2026 fields <- c(renv_path_aliased(problem$file), problem$line, problem$column)
2027 header <- paste(fields, collapse = ":")
2028 message <- conditionMessage(problem$error)
2029 c(file = problem$file, header = header, message = message)
2030 })
2031
2032 # split based on header (group errors from same file)
2033 splat <- split(bound, bound$file)
2034
2035 # emit messages
2036 lines <- enumerate(splat, function(file, problem) {
2037 messages <- paste("Error", problem$message, sep = ": ", collapse = "\n\n")
2038 paste(c(header(file), messages, ""), collapse = "\n")
2039 })
2040
2041 bulletin(
2042 "WARNING: One or more problems were discovered while enumerating dependencies.",
2043 c("", lines),
2044 "Please see `?renv::dependencies` for more information.",
2045 bullets = FALSE
2046 )
2047
2048 if (identical(errors, "fatal")) {
2049 fmt <- "one or more problems were encountered while enumerating dependencies"
2050 stopf(fmt)
2051 }
2052
2053 renv_condition_signal("renv.dependencies.problems", problems)
2054 TRUE
2055
2056 }
2057
2058 renv_dependencies_eval <- function(expr) {
2059
2060 # create environment with small subset of "safe" symbols, that
2061 # are commonly used for chunk expressions
2062 syms <- c(
2063 "list", "c", "T", "F",
2064 "{", "(", "[", "[[",
2065 "::", ":::", "$", "@",
2066 ":",
2067 "+", "-", "*", "/",
2068 "<", ">", "<=", ">=", "==", "!=",
2069 "!",
2070 "&", "&&", "|", "||"
2071 )
2072
2073 vals <- mget(syms, envir = baseenv())
2074 envir <- list2env(vals, parent = emptyenv())
2075
2076 # evaluate in that environment
2077 eval(expr, envir = envir)
2078
2079 }
2080
2081 renv_dependencies_recurse <- function(object, callback) {
2082
2083 if (is.call(object))
2084 callback(object)
2085
2086 if (is.recursive(object))
2087 for (i in seq_along(object))
2088 if (is.call(object[[i]]))
2089 renv_dependencies_recurse_impl(object[[i]], callback)
2090
2091 }
2092
2093 renv_dependencies_recurse_impl <- function(object, callback) {
2094 callback(object)
2095 for (i in seq_along(object))
2096 if (is.call(object[[i]]))
2097 renv_dependencies_recurse_impl(object[[i]], callback)
2098 }
2099
2100 renv_dependencies_fields <- function(fields = NULL, project = NULL) {
2101
2102 fields <- fields %||% settings$package.dependency.fields(project = project)
2103
2104 expanded <- map(fields, function(field) {
2105
2106 case(
2107
2108 identical(field, FALSE)
2109 ~ NULL,
2110
2111 identical(field, "strong") || is.na(field)
2112 ~ c("Depends", "Imports", "LinkingTo"),
2113
2114 identical(field, "most") || identical(field, TRUE)
2115 ~ c("Depends", "Imports", "LinkingTo", "Suggests"),
2116
2117 identical(field, "all")
2118 ~ c("Depends", "Imports", "LinkingTo", "Suggests", "Enhances"),
2119
2120 field
2121
2122 )
2123
2124 })
2125
2126 unique(unlist(expanded, recursive = FALSE, use.names = FALSE))
2127
2128 }