-
Notifications
You must be signed in to change notification settings - Fork 152
/
dependencies.R
1718 lines (1320 loc) · 45.2 KB
/
dependencies.R
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' Find R package dependencies in a project
#'
#' @description
#' `dependencies()` will crawl files within your project, looking for \R files
#' and the packages used within those \R files. This is done primarily by
#' parsing the code and looking for calls of the form `library(package)`,
#' `require(package)`, `requireNamespace("package")`, and `package::method()`.
#' renv also supports package loading with
#' [box](https://cran.r-project.org/package=box) (`box::use(...)`) and
#' [pacman](https://cran.r-project.org/package=pacman) (`pacman::p_load(...)`)
#' .
#'
#' For \R package projects, dependencies expressed in the `DESCRIPTION` file
#' will also be discovered.
#'
#' Note that the rmarkdown package is required in order to crawl dependencies
#' in R Markdown files.
#'
#' # Missing dependencies
#'
#' `dependencies()` uses static analysis to determine which packages are used
#' by your project. This means that it inspects, but doesn't run, your
#' source. Static analysis generally works well, but is not 100% reliable in
#' detecting the packages required by your project. For example, renv is
#' unable to detect this kind of usage:
#'
#' ```{r eval=FALSE}
#' for (package in c("dplyr", "ggplot2")) {
#' library(package, character.only = TRUE)
#' }
#' ```
#'
#' It also can't generally tell if one of the packages you use, uses one of
#' its suggested packages. For example, `tidyr::separate_wider_delim()`
#' uses the stringr package which is only suggested, not required by tidyr.
#'
#' If you find that renv's dependency discovery misses one or more packages
#' that you actually use in your project, one escape hatch is to include a file
#' called `_dependencies.R` that includes straightforward library calls:
#'
#' ```
#' library(dplyr)
#' library(ggplot2)
#' library(stringr)
#' ```
#'
#' # Explicit dependencies
#'
#' Alternatively, you can suppress dependency discover and instead rely
#' on an explicit set of packages recorded by you in a project `DESCRIPTION` file.
#' Call `renv::settings$snapshot.type("explicit")` to enable "explicit" mode,
#' then enumerate your dependencies in a project `DESCRIPTION` file.
#'
#' In that case, your `DESCRIPTION` might look something like this:
#'
#' ```
#' Type: project
#' Description: My project.
#' Depends:
#' tidyverse,
#' devtools,
#' shiny,
#' data.table
#' ```
#'
#' # Ignoring files
#'
#' By default, renv will read your project's `.gitignore`s (if present) to
#' determine whether certain files or folders should be included when traversing
#' directories. If preferred, you can also create a `.renvignore` file (with
#' entries of the same format as a standard `.gitignore` file) to tell renv
#' which files to ignore within a directory. If both `.renvignore` and
#' `.gitignore` exist within a folder, the `.renvignore` will be used in lieu of
#' the `.gitignore`.
#'
#' See <https://git-scm.com/docs/gitignore> for documentation on the
#' `.gitignore` format. Some simple examples here:
#'
#' ```
#' # ignore all R Markdown files
#' *.Rmd
#'
#' # ignore all data folders
#' data/
#'
#' # ignore only data folders from the root of the project
#' /data/
#' ```
#'
#' Using ignore files is important if your project contains a large number
#' of files; for example, if you have a `data/` directory containing many
#' text files.
#' # Errors
#'
#' renv's attempts to enumerate package dependencies in your project can fail
#' -- most commonly, because of failures when attempting to parse your \R code.
#' You can use the `errors` argument to suppress these problems, but a
#' more robust solution is tell renv not to look at the problematic code.
#' As well as using `.renvignore`, as described above, you can also suppress errors
#' discovered within individual `.Rmd` chunks by including `renv.ignore=TRUE`
#' in the chunk header. For example:
#'
#' ```{r chunk-label, renv.ignore=TRUE}
#' # code in this chunk will be ignored by renv
#' ```
#'
#' Similarly, if you'd like renv to parse a chunk that is otherwise ignored
#' (e.g. because it has `eval=FALSE` as a chunk header), you can set:
#'
#' ```{r chunk-label, eval=FALSE, renv.ignore=FALSE}
#' # code in this chunk will _not_ be ignored
#' ```
#'
#' # Development dependencies
#'
#' renv attempts to distinguish between 'development' dependencies and
#' 'runtime' dependencies. For example, you might rely on e.g.
#' [devtools](https://cran.r-project.org/package=devtools) and
#' [roxygen2](https://cran.r-project.org/package=roxygen2) during development
#' for a project, but may not actually require these packages at runtime.
#' @inheritParams renv-params
#'
#' @param path The path to a `.R`, `.Rmd`, `.qmd`, `DESCRIPTION`, a directory
#' containing such files, or an R function. The default uses all files
#' found within the current working directory and its children.
#'
#' @param root The root directory to be used for dependency discovery.
#' Defaults to the active project directory. You may need to set this
#' explicitly to ensure that your project's `.renvignore`s (if any) are
#' properly handled.
#'
#' @param quiet Boolean; be quiet while checking for dependencies?
#' Setting `quiet = TRUE` is equivalent to setting `progress = FALSE`
#' and `errors = "ignored"`, and overrides those options when not `NULL`.
#'
#' @param progress Boolean; report progress output while enumerating
#' dependencies?
#'
#' @param errors How should errors that occur during dependency enumeration be
#' handled?
#'
#' * `"reported"` (the default): errors are reported to the user, but
#' otherwise ignored.
#' * `"fatal"`: errors are fatal and stop execution.
#' * `"ignored"`: errors are ignored and not reported to the user.
#'
#' @param dev Boolean; include development dependencies? These packages are
#' typically required when developing the project, but not when running it
#' (i.e. you want them installed when humans are working on the project but
#' not when computers are deploying it).
#'
#' Development dependencies include packages listed in the `Suggests` field
#' of a `DESCRIPTION` found in the project root, and roxygen2 or devtools if
#' their use is implied by other project metadata. They also include packages
#' used in `~/.Rprofile` if `config$user.profile()` is `TRUE`.
#'
#' @return An \R `data.frame` of discovered dependencies, mapping inferred
#' package names to the files in which they were discovered. Note that the
#' `Package` field might name a package remote, rather than just a plain
#' package name.
#'
#' @export
#'
#' @examples
#' \dontrun{
#'
#' # find R package dependencies in the current directory
#' renv::dependencies()
#'
#' }
dependencies <- function(
path = getwd(),
root = NULL,
...,
quiet = NULL,
progress = TRUE,
errors = c("reported", "fatal", "ignored"),
dev = FALSE)
{
renv_scope_error_handler()
# special case: if 'path' is a function, parse its body for dependencies
if (is.function(path))
return(renv_dependencies_discover_r(expr = body(path)))
renv_dependencies_impl(
path = path,
root = root,
quiet = quiet,
progress = progress,
errors = errors,
dev = dev,
...
)
}
renv_dependencies_impl <- function(
path = getwd(),
...,
root = NULL,
field = NULL,
quiet = NULL,
progress = FALSE,
errors = c("reported", "fatal", "ignored"),
dev = FALSE)
{
renv_dots_check(...)
path <- renv_path_normalize(path, mustWork = TRUE)
root <- root %||% renv_dependencies_root(path)
# handle 'quiet' parameter
if (quiet %||% FALSE) {
progress <- FALSE
errors <- "ignored"
}
# ignore errors when testing, unless explicitly asked for
if (renv_tests_running() && missing(errors))
errors <- "ignored"
# resolve errors
errors <- match.arg(errors)
before <- Sys.time()
renv_dependencies_scope(root = root)
files <- renv_dependencies_find(path, root)
deps <- renv_dependencies_discover(files, progress, errors)
after <- Sys.time()
elapsed <- difftime(after, before, units = "secs")
renv_condition_signal("renv.dependencies.elapsed_time", elapsed)
renv_dependencies_report(errors)
deps <- if (empty(deps) || nrow(deps) == 0L) {
renv_dependencies_list_empty()
} else {
# drop NAs, and only keep 'dev' dependencies if requested
rows(deps, deps$Dev %in% c(dev, FALSE))
}
take(deps, field)
}
renv_dependencies_root <- function(path = getwd()) {
path <- renv_path_normalize(path, mustWork = TRUE)
project <- renv_project_get(default = NULL)
if (!is.null(project) && all(renv_path_within(path, project)))
return(project)
roots <- uapply(path, renv_dependencies_root_impl)
if (empty(roots))
return(NULL)
uniroot <- unique(roots)
if (length(uniroot) > 1)
return(NULL)
uniroot
}
renv_dependencies_root_impl <- function(path) {
renv_file_find(path, function(parent) {
anchors <- c("DESCRIPTION", ".git", ".Rproj.user", "renv.lock", "renv")
for (anchor in anchors)
if (file.exists(file.path(parent, anchor)))
return(parent)
})
}
renv_dependencies_callback <- function(path) {
# user .Rprofile
if (renv_path_same(path, Sys.getenv("R_PROFILE_USER", unset = "~/.Rprofile"))) {
return(function(path) renv_dependencies_discover_r(path, dev = TRUE))
}
cbname <- list(
".Rprofile" = function(path) renv_dependencies_discover_r(path),
"DESCRIPTION" = function(path) renv_dependencies_discover_description(path),
"_bookdown.yml" = function(path) renv_dependencies_discover_bookdown(path),
"_pkgdown.yml" = function(path) renv_dependencies_discover_pkgdown(path),
"_quarto.yml" = function(path) renv_dependencies_discover_quarto(path),
"renv.lock" = function(path) renv_dependencies_discover_renv_lock(path),
"rsconnect" = function(path) renv_dependencies_discover_rsconnect(path)
)
cbext <- list(
".rproj" = function(path) renv_dependencies_discover_rproj(path),
".r" = function(path) renv_dependencies_discover_r(path),
".qmd" = function(path) renv_dependencies_discover_multimode(path, "qmd"),
".rmd" = function(path) renv_dependencies_discover_multimode(path, "rmd"),
".rmarkdown" = function(path) renv_dependencies_discover_multimode(path, "rmd"),
".rnw" = function(path) renv_dependencies_discover_multimode(path, "rnw"),
".ipynb" = function(path) renv_dependencies_discover_ipynb(path)
)
name <- basename(path)
ext <- tolower(fileext(path))
callback <- cbname[[name]] %||% cbext[[ext]]
if (!is.null(callback))
return(callback)
# for files without an extension, check if those might be executable by R
if (!nzchar(ext)) {
shebang <- renv_file_shebang(path)
if (grepl("\\b(?:R|r|Rscript)\\b", shebang))
return(function(path) renv_dependencies_discover_r(path))
}
}
renv_dependencies_find_extra <- function(root) {
# if we don't have a root, we don't have a project
if (is.null(root))
return(NULL)
# only run for root-level dependency checks
project <- renv_project_resolve()
if (!renv_path_same(root, project))
return(NULL)
# only run if we have a custom profile
profile <- renv_profile_get()
if (is.null(profile))
return(NULL)
# look for dependencies in the associated 'renv' folder
path <- renv_paths_renv(project = project)
renv_dependencies_find_impl(path, root, 0L)
}
renv_dependencies_find <- function(path = getwd(), root = getwd()) {
files <- lapply(path, renv_dependencies_find_impl, root = root, depth = 0)
extra <- renv_dependencies_find_extra(root)
if (config$user.profile()) {
rprofile_path <- Sys.getenv("R_PROFILE_USER", unset = "~/.Rprofile")
if (file.exists(rprofile_path)) {
extra <- c(extra, rprofile_path)
}
}
unlist(c(files, extra), recursive = TRUE, use.names = FALSE)
}
renv_dependencies_find_impl <- function(path, root, depth) {
# check file type
info <- renv_file_info(path)
# the file might have been removed after listing -- if so, just ignore it
if (is.na(info$isdir))
return(NULL)
# if this is a directory, recurse
if (info$isdir)
return(renv_dependencies_find_dir(path, root, depth))
path
}
renv_dependencies_find_dir <- function(path, root, depth) {
# check if this path should be ignored
excluded <- renv_renvignore_exec(path, root, path)
if (excluded)
return(character())
# check if we've already scanned this directory
# (necessary to guard against recursive symlinks)
if (!renv_platform_windows()) {
norm <- renv_path_normalize(path)
state <- renv_dependencies_state()
if (visited(norm, state$scanned))
return(character())
}
# list children
children <- renv_dependencies_find_dir_children(path, root, depth)
# find recursive dependencies
depth <- depth + 1
paths <- map(children, renv_dependencies_find_impl, root = root, depth = depth)
# explicitly include rsconnect folder
# (so we can infer a dependency on rsconnect when appropriate)
rsconnect <- file.path(path, "rsconnect")
if (file.exists(rsconnect))
paths <- c(rsconnect, paths)
paths
}
# return the set of files / subdirectories within a directory that should be
# crawled for dependencies
renv_dependencies_find_dir_children <- function(path, root, depth) {
# list files in the folder
children <- renv_file_list(path, full.names = TRUE)
# skip if this contains too many files
# https://github.com/rstudio/renv/issues/1186
count <- length(children)
if (count >= config$dependencies.limit()) {
relpath <- renv_path_relative(path, dirname(root))
renv_dependencies_find_dir_children_overload(relpath, count)
}
# remove files which are broken symlinks
children <- children[file.exists(children)]
# remove hard-coded ignores
# (only keep DESCRIPTION files at the top level)
ignored <- c("packrat", "renv", "revdep", "vendor", if (depth) "DESCRIPTION")
children <- children[!basename(children) %in% ignored]
# compute exclusions
excluded <- renv_renvignore_exec(path, root, children)
# keep only non-excluded children
children[!excluded]
}
renv_dependencies_find_dir_children_overload <- function(path, count) {
# check for missing state (e.g. if internal method called directly)
state <- renv_dependencies_state()
if (is.null(state))
return()
fmt <- "directory contains %s; consider ignoring this directory"
msg <- sprintf(fmt, nplural("file", count))
error <- simpleError(message = msg)
path <- path %||% state$path
problem <- list(file = path, error = error)
state$problems$push(problem)
}
renv_dependencies_discover <- function(paths, progress, errors) {
if (!renv_dependencies_discover_preflight(paths, errors))
return(invisible(list()))
# short path if we're not showing progress
if (identical(progress, FALSE))
return(bapply(paths, renv_dependencies_discover_impl))
# otherwise, run with progress reporting
# nocov start
printf("Finding R package dependencies ... ")
callback <- renv_progress_callback(renv_dependencies_discover_impl, length(paths))
deps <- lapply(paths, callback)
writef("Done!")
bind(deps)
# nocov end
}
renv_dependencies_discover_impl <- function(path) {
callback <- renv_dependencies_callback(path)
if (is.null(callback)) {
return(NULL)
}
tryCatch(
filebacked("dependencies", path, callback),
error = function(cnd) {
warning(cnd)
NULL
}
)
}
renv_dependencies_discover_preflight <- function(paths, errors) {
if (identical(errors, "ignored"))
return(TRUE)
if (length(paths) < config$dependencies.limit())
return(TRUE)
lines <- c(
"A large number of files (%i in total) have been discovered.",
"It may take renv a long time to crawl these files for dependencies.",
"Consider using .renvignore to ignore irrelevant files.",
"See `?renv::dependencies` for more information.",
"Set `options(renv.config.dependencies.limit = Inf)` to disable this warning.",
""
)
writef(lines, length(paths))
if (identical(errors, "reported"))
return(TRUE)
cancel_if(interactive() && !proceed())
TRUE
}
renv_dependencies_discover_renv_lock <- function(path) {
renv_dependencies_list(path, "renv")
}
renv_dependencies_discover_description <- function(path,
fields = NULL,
subdir = NULL,
project = NULL)
{
dcf <- catch(renv_description_read(path = path, subdir = subdir))
if (inherits(dcf, "error"))
return(renv_dependencies_error(path, error = dcf))
fields <- fields %||% {
# most callers don't pass in project so we need to get it from global state
project <- project %||%
renv_dependencies_state(key = "root") %||%
renv_restore_state(key = "root") %||%
renv_project_resolve()
# get fields from settings
fields <- settings$package.dependency.fields(project = project)
# if this is the DESCRIPTION file for the active project, include
# the dependencies for the active profile (if any) and Suggested fields.
# collect profile-specific dependencies as well
if (renv_path_same(file.path(project, "DESCRIPTION"), path)) {
fmt <- "Config/renv/profiles/%s/dependencies"
profile <- renv_profile_get()
fields <- c(fields, "Suggests", sprintf(fmt, profile))
}
fields
}
# make sure dependency fields are expanded
fields <- renv_description_dependency_fields_expand(fields)
data <- map(
fields,
renv_dependencies_discover_description_impl,
dcf = dcf,
path = path
)
# if this is a bioconductor package, add their implicit dependencies
if ("biocViews" %in% names(dcf)) {
data[[length(data) + 1L]] <- renv_dependencies_list(
source = path,
packages = c(renv_bioconductor_manager(), "BiocVersion")
)
}
bind(data)
}
renv_dependencies_discover_description_impl <- function(dcf, field, path) {
# read field
contents <- dcf[[field]]
if (!is.character(contents))
return(list())
# split on commas
parts <- strsplit(dcf[[field]], "\\s*,\\s*")[[1]]
# drop any empty fields
x <- parts[nzchar(parts)]
# match to split on remote, version
pattern <- paste0(
"([^,\\([:space:]]+)", # remote name
"(?:\\s*\\(([><=]+)\\s*([0-9.-]+)\\))?" # optional version specification
)
m <- regexec(pattern, x)
matches <- regmatches(x, m)
if (empty(matches))
return(list())
# create dependency list
renv_dependencies_list(
path,
extract_chr(matches, 2L),
extract_chr(matches, 3L),
extract_chr(matches, 4L),
dev = field == "Suggests"
)
}
renv_dependencies_discover_bookdown <- function(path) {
# TODO: other dependencies to parse from bookdown?
renv_dependencies_list(path, "bookdown")
}
renv_dependencies_discover_pkgdown <- function(path) {
# TODO: other dependencies to parse from pkgdown?
renv_dependencies_list(path, "pkgdown")
}
renv_dependencies_discover_quarto <- function(path) {
# TODO: other dependencies to parse from quarto?
#
# NOTE: we previously inferred a dependency on the R 'quarto' package here,
# but quarto is normally invoked directly (rather than via the package) and
# so such a dependency is not strictly necessary.
#
# https://github.com/rstudio/renv/issues/995
renv_dependencies_list_empty()
}
renv_dependencies_discover_rsconnect <- function(path) {
renv_dependencies_list(path, "rsconnect")
}
renv_dependencies_discover_multimode <- function(path, mode) {
# TODO: find in-line R code?
deps <- stack()
if (mode %in% c("rmd", "qmd"))
deps$push(renv_dependencies_discover_rmd_yaml_header(path, mode))
deps$push(renv_dependencies_discover_chunks(path, mode))
bind(Filter(NROW, deps$data()))
}
renv_dependencies_discover_rmd_yaml_header <- function(path, mode) {
deps <- stack(mode = "character")
# R Markdown documents always depend on rmarkdown
if (identical(mode, "rmd"))
deps$push("rmarkdown")
# try and read the document's YAML header
contents <- renv_file_read(path)
pattern <- "(?:^|\n)\\s*---\\s*(?:$|\n)"
matches <- gregexpr(pattern, contents, perl = TRUE)[[1L]]
# check that we have something that looks like a YAML header
ok <- length(matches) > 1L && matches[[1L]] == 1L
if (!ok)
return(renv_dependencies_list(path, packages = deps$data()))
# require yaml package for parsing YAML header
name <- case(
mode == "rmd" ~ "R Markdown",
mode == "qmd" ~ "Quarto Markdown"
)
# validate that we actually have the yaml package available
if (!renv_dependencies_require("yaml", name)) {
packages <- deps$data()
return(renv_dependencies_list(path, packages))
}
# extract YAML text
yamltext <- substring(contents, matches[[1L]] + 4L, matches[[2L]] - 1L)
yaml <- catch(renv_yaml_load(yamltext))
if (inherits(yaml, "error"))
return(renv_dependencies_error(path, error = yaml, packages = "rmarkdown"))
# check for Shiny runtime
runtime <- yaml[["runtime"]] %||% ""
if (pstring(runtime) && grepl("shiny", runtime, fixed = TRUE))
deps$push("shiny")
server <- yaml[["server"]] %||% ""
if (identical(server, "shiny"))
deps$push("shiny")
if (is.list(server) && identical(server[["type"]], "shiny"))
deps$push("shiny")
pattern <- renv_regexps_package_name()
# check recursively for package usages of the form 'package::method'
recurse(yaml, function(node, stack) {
# look for keys of the form 'package::method'
values <- c(names(node), if (pstring(node)) node)
for (value in values) {
call <- tryCatch(parse(text = value)[[1]], error = function(err) NULL)
if (renv_call_matches(call, name = c("::", ":::"), n_args = 2)) {
deps$push(as.character(call[[2L]]))
}
}
})
# check for dependency on bslib
theme <- catchall(yaml[[c("output", "html_document", "theme")]])
if (!inherits(theme, "error") && is.list(theme))
deps$push("bslib")
# check for parameterized documents
status <- catch(renv_dependencies_discover_rmd_yaml_header_params(yaml, deps))
if (inherits(status, "error"))
renv_dependencies_error_push(path, status)
# get list of dependencies
packages <- deps$data()
renv_dependencies_list(path, packages)
}
renv_dependencies_discover_rmd_yaml_header_params <- function(yaml, deps) {
# check for declared params
params <- yaml[["params"]]
if (!is.list(params))
return()
# infer dependency on shiny
deps$push("shiny")
# iterate through params, parsing dependencies from R code
for (param in params) {
# check for r types
type <- attr(param, "type", exact = TRUE)
if (!identical(type, "r"))
next
# attempt to parse dependencies
rdeps <- catch(renv_dependencies_discover_r(text = param))
if (inherits(rdeps, "error"))
next
# add each dependency
for (package in sort(unique(rdeps$Package)))
deps$push(package)
}
}
renv_dependencies_discover_chunks_ignore <- function(chunk) {
# if renv.ignore is set, respect it
ignore <- chunk$params[["renv.ignore"]]
if (!is.null(ignore))
return(truthy(ignore))
# skip non-R chunks
engine <- chunk$params[["engine"]]
ok <- is.character(engine) && engine %in% c("r", "rscript")
if (!ok)
return(TRUE)
# skip un-evaluated chunks
if (!truthy(chunk$params[["eval"]], default = TRUE))
return(TRUE)
# skip learnr exercises
if (truthy(chunk$params[["exercise"]], default = FALSE))
return(TRUE)
# skip chunks whose labels end in '-display'
label <- chunk$params[["label"]] %||% ""
if (grepl("-display$", label))
return(TRUE)
# ok, don't ignore this chunk
FALSE
}
renv_dependencies_discover_chunks <- function(path, mode) {
# figure out the appropriate begin, end patterns
type <- tolower(file_ext(path))
if (type %in% c("rmd", "qmd", "rmarkdown"))
type <- "md"
allpatterns <- renv_knitr_patterns()
patterns <- allpatterns[[type]]
if (is.null(patterns)) {
condition <- simpleCondition("not a recognized multi-mode R document")
return(renv_dependencies_error(path, error = condition))
}
# parse the chunks within
# NOTE: we need to proceed line-by-line since the chunk end pattern might
# end chunks not started by the chunk begin pattern (sad face)
encoding <- if (type == "md") "UTF-8" else "unknown"
contents <- readLines(path, warn = FALSE, encoding = encoding)
ranges <- renv_dependencies_discover_chunks_ranges(path, contents, patterns)
# extract chunk code from the used ranges
chunks <- .mapply(function(lhs, rhs) {
# parse params in header
header <- contents[[lhs]]
params <- renv_knitr_options_header(header, type)
# extract chunk contents (preserve newlines for nicer error reporting)
range <- seq.int(lhs + 1, length.out = rhs - lhs - 1)
code <- rep.int("", length(contents))
code[range] <- contents[range]
# also parse chunk options
params <- overlay(params, renv_knitr_options_chunk(code))
# return list of outputs
list(params = params, code = code)
}, ranges, NULL)
# iterate over chunks, and attempt to parse dependencies from each
cdeps <- bapply(chunks, function(chunk) {
# check whether this chunk should be ignored
if (renv_dependencies_discover_chunks_ignore(chunk))
return(character())
# remove reused chunk placeholders
pattern <- "<<[^>]+>>"
code <- gsub(pattern, "", chunk$code)
# okay, now we can discover deps
deps <- catch(renv_dependencies_discover_r(path = path, text = code))
if (inherits(deps, "error"))
return(renv_dependencies_error(path, error = deps))
deps
})
# check for dependencies in inline chunks as well
ideps <- renv_dependencies_discover_chunks_inline(path, contents)
# if this is a .qmd, infer a dependency on rmarkdown if we have any R chunks
qdeps <- NULL
if (mode %in% "qmd") {
for (chunk in chunks) {
engine <- chunk$params[["engine"]]
if (is.character(engine) && engine %in% c("r", "rscript")) {
qdeps <- renv_dependencies_list(path, "rmarkdown")
break
}
}
}
# paste them all together
deps <- bind(list(cdeps, ideps, qdeps))
if (is.null(deps))
return(deps)
deps$Source <- path
deps
}
renv_dependencies_discover_chunks_inline <- function(path, contents) {
pasted <- paste(contents, collapse = "\n")
matches <- gregexpr("`r ([^`]+)`", pasted, perl = TRUE)
if (identical(c(matches[[1L]]), -1L))
return(list())
text <- unlist(regmatches(pasted, matches), use.names = FALSE, recursive = FALSE)
code <- substring(text, 4L, nchar(text) - 1L)
deps <- renv_dependencies_discover_r(path = path, text = code)
if (inherits(deps, "error"))
return(renv_dependencies_error(path, error = deps))
deps
}
renv_dependencies_discover_chunks_ranges <- function(path, contents, patterns) {
output <- list()
chunk <- FALSE
start <- 1; end <- 1
for (i in seq_along(contents)) {
line <- contents[[i]]
if (chunk == FALSE && grepl(patterns$chunk.begin, line)) {
chunk <- TRUE
start <- i
next
}
if (chunk == TRUE && grepl(patterns$chunk.begin, line)) {
end <- i
output[[length(output) + 1]] <- list(lhs = start, rhs = end)
start <- i
next
}
if (chunk == TRUE && grepl(patterns$chunk.end, line)) {
chunk <- FALSE
end <- i
output[[length(output) + 1]] <- list(lhs = start, rhs = end)
next
}
}
if (chunk) {
message <- sprintf("chunk starting on line %i is not closed", start)
error <- simpleError(message)
renv_dependencies_error(path, error = error)
}
bind(output)
}
renv_dependencies_discover_ipynb <- function(path) {
json <- renv_json_read(path)
if (!identical(json$metadata$kernelspec$language, "R"))
return()
deps <- stack()
if (identical(json$metadata$kernelspec$name, "ir"))
deps$push(renv_dependencies_list(path, "IRkernel"))
for (cell in json$cells) {
if (cell$cell_type != "code")
next
code <- paste0(cell$source, collapse = "")
deps$push(renv_dependencies_discover_r(path, text = code))
}
bind(deps$data())
}
renv_dependencies_discover_rproj <- function(path) {
props <- renv_properties_read(path)
deps <- stack()
if (identical(props$PackageUseDevtools, "Yes")) {
deps$push("devtools")
deps$push("roxygen2")
}
renv_dependencies_list(path, deps$data(), dev = TRUE)
}
renv_dependencies_discover_r <- function(path = NULL,
text = NULL,
expr = NULL,
envir = NULL,
dev = FALSE)
{
expr <- case(
is.function(expr) ~ body(expr),
is.language(expr) ~ expr,
is.character(expr) ~ catch(renv_parse_text(expr)),
is.character(text) ~ catch(renv_parse_text(text)),
is.character(path) ~ catch(renv_parse_file(path)),
~ stop("internal error")
)
if (inherits(expr, "error"))
return(renv_dependencies_error(path, error = expr))
# update current path
state <- renv_dependencies_state()
if (!is.null(state))
renv_scope_binding(state, "path", path)
methods <- c(