Debian Codegraph @

R/retrieve.R

raw
1
2 #' Retrieve packages
3 #'
4 #' Retrieve (download) one or more packages from external sources.
5 #' Using `renv::retrieve()` can be useful in CI / CD workflows, where
6 #' you might want to download all packages listed in a lockfile
7 #' before later invoking [renv::restore()]. Packages will be downloaded
8 #' to an internal path within `renv`'s local state directories -- see
9 #' [paths] for more details.
10 #'
11 #' If `destdir` is `NULL` and the requested package is already available
12 #' within the `renv` cache, `renv` will return the path to that package
13 #' directory in the cache.
14 #'
15 #' @inheritParams renv-params
16 #'
17 #' @param lockfile The path to an `renv` lockfile. When set, `renv`
18 #' will retrieve the packages as defined within that lockfile.
19 #' If `packages` is also non-`NULL`, then only those packages will
20 #' be retrieved.
21 #'
22 #' @param destdir The directory where packages should be downloaded.
23 #' When `NULL` (the default), the default internal storage locations
24 #' (normally used by e.g. [renv::install()] or [renv::restore()]) will
25 #' be used.
26 #'
27 #' @returns A named vector, mapping package names to the paths where
28 #' those packages were downloaded.
29 #'
30 #' @export
31 #'
32 #' @examples
33 #' \dontrun{
34 #'
35 #' # retrieve package + versions as defined in the lockfile
36 #' # normally used as a pre-flight step to renv::restore()
37 #' renv::retrieve()
38 #'
39 #' # download one or more packages locally
40 #' renv::retrieve("rlang", destdir = ".")
41 #'
42 #' }
43 retrieve <- function(packages = NULL,
44 ...,
45 lockfile = NULL,
46 destdir = NULL,
47 project = NULL)
48 {
49 renv_consent_check()
50 renv_scope_error_handler()
51 renv_dots_check(...)
52
53 project <- renv_project_resolve(project)
54 renv_project_lock(project = project)
55
56 # set destdir if available
57 if (!is.null(destdir)) {
58 renv_scope_options(renv.config.cache.enabled = FALSE)
59 renv_scope_binding(the, "destdir", destdir)
60 }
61
62 # figure out which records we want to retrieve
63 if (is.null(packages) && is.null(lockfile)) {
64 lockfile <- renv_lockfile_load(project = project)
65 records <- renv_lockfile_records(lockfile)
66 packages <- names(records)
67 } else if (is.null(lockfile)) {
68 records <- map(packages, renv_remotes_resolve, latest = TRUE)
69 packages <- map_chr(records, `[[`, "Package")
70 names(records) <- packages
71 } else if (is.character(lockfile)) {
72 lockfile <- renv_lockfile_read(lockfile)
73 records <- renv_lockfile_records(lockfile)
74 packages <- packages %||% names(records)
75 }
76
77 # overlay project remotes
78 records <- overlay(renv_project_remotes(project), records)
79
80 # perform the retrieval
81 renv_scope_restore(
82 project = project,
83 library = library,
84 packages = packages,
85 records = records
86 )
87
88 result <- renv_retrieve_impl(packages)
89 map_chr(result, `[[`, "Path")
90 }
91
92 renv_retrieve_impl <- function(packages) {
93
94 # confirm that we have restore state set up
95 state <- renv_restore_state()
96 if (is.null(state))
97 stopf("renv_restore_begin() must be called first")
98
99 # normalize repositories (ensure @CRAN@ is resolved)
100 options(repos = renv_repos_normalize())
101
102 # transform repository URLs for PPM
103 if (renv_ppm_enabled()) {
104 repos <- getOption("repos")
105 renv_scope_options(repos = renv_ppm_transform(repos))
106 }
107
108 # ensure HTTPUserAgent is set (required for PPM binaries)
109 agent <- renv_http_useragent()
110 if (!grepl("renv", agent)) {
111 renv <- sprintf("renv (%s)", renv_metadata_version())
112 agent <- paste(renv, agent, sep = "; ")
113 }
114 renv_scope_options(HTTPUserAgent = agent)
115
116 before <- Sys.time()
117 handler <- state$handler
118 for (package in packages)
119 handler(package, renv_retrieve_impl_one(package))
120 after <- Sys.time()
121
122 state <- renv_restore_state()
123 count <- state$downloaded
124 if (count) {
125 elapsed <- difftime(after, before, units = "secs")
126 writef("Successfully downloaded %s in %s.", nplural("package", count), renv_difftime_format(elapsed))
127 writef("")
128 }
129
130 state$install$data()
131
132 }
133
134 renv_retrieve_impl_one <- function(package) {
135
136 # skip packages with 'base' priority
137 if (package %in% renv_packages_base())
138 return()
139
140 # if we've already attempted retrieval of this package, skip
141 state <- renv_restore_state()
142 if (!is.null(state$retrieved[[package]]))
143 return()
144
145 # insert a dummy value just to avoid infinite recursions
146 # (this will get updated on a successful installation later)
147 state$retrieved[[package]] <- NA
148
149 # extract record for package
150 records <- state$records
151 record <- records[[package]] %||% renv_retrieve_resolve(package)
152
153 # resolve lazy records
154 if (is.function(record)) {
155 state$records[[package]] <- resolve(record)
156 record <- state$records[[package]]
157 }
158
159 # normalize the record source
160 source <- renv_record_source(record, normalize = TRUE)
161
162 # don't install packages from incompatible OS
163 ostype <- tolower(record[["OS_type"]] %||% "")
164
165 skip <-
166 renv_platform_unix() && identical(ostype, "windows") ||
167 renv_platform_windows() && identical(ostype, "unix")
168
169 if (skip)
170 return()
171
172 # if this is a package from Bioconductor, activate those repositories now
173 if (source %in% c("bioconductor")) {
174 project <- renv_restore_state(key = "project")
175 renv_scope_bioconductor(project = project)
176 }
177
178 # if this is a package from R-Forge, activate its repository
179 if (source %in% c("repository")) {
180 repository <- record$Repository %||% ""
181 if (tolower(repository) %in% c("rforge", "r-forge")) {
182 repos <- getOption("repos")
183 if (!"R-Forge" %in% names(repos)) {
184 repos[["R-Forge"]] <- "https://R-Forge.R-project.org"
185 renv_scope_options(repos = repos)
186 }
187 }
188 }
189
190 # if the record doesn't declare the package version,
191 # treat it as a request for the latest version on CRAN
192 # TODO: should make this behavior configurable
193 uselatest <-
194 source %in% c("repository", "bioconductor") &&
195 is.null(record$Version)
196
197 if (uselatest) {
198 record <- withCallingHandlers(
199 renv_available_packages_latest(package),
200 error = function(err) stopf("package '%s' is not available", package)
201 )
202 }
203
204 # if the requested record is incompatible with the set
205 # of requested package versions thus far, request the
206 # latest version on the R package repositories
207 #
208 # TODO: handle more explicit dependency requirements
209 # TODO: report to the user if they have explicitly requested
210 # installation of this package version despite it being incompatible
211 compat <- renv_retrieve_incompatible(package, record)
212 if (NROW(compat)) {
213
214 # get the latest available package version
215 replacement <- renv_available_packages_latest(package)
216 if (is.null(replacement))
217 stopf("package '%s' is not available", package)
218
219 # if it's not compatible, then we might need to try again with
220 # a source version (assuming type = "both")
221 pkgtype <- getOption("pkgType")
222 if (identical(pkgtype, "both")) {
223 iscompat <- renv_retrieve_incompatible(package, replacement)
224 if (NROW(iscompat)) {
225 replacement <- renv_available_packages_latest(package, type = "source")
226 }
227 }
228
229 # report if we couldn't find a compatible package
230 renv_retrieve_incompatible_report(package, record, replacement, compat)
231 record <- replacement
232
233 }
234
235 rebuild <- renv_restore_rebuild_required(record)
236 if (!rebuild) {
237
238 # if we have an installed package matching the requested record, finish early
239 path <- renv_restore_find(package, record)
240 if (file.exists(path)) {
241 install <- !dirname(path) %in% renv_libpaths_all()
242 return(renv_retrieve_successful(record, path, install = install))
243 }
244
245 # if the requested record already exists in the cache,
246 # we'll use that package for install
247 cacheable <-
248 renv_cache_config_enabled(project = state$project) &&
249 renv_record_cacheable(record)
250
251 if (cacheable) {
252
253 # try to find the record in the cache
254 path <- renv_cache_find(record)
255 if (nzchar(path) && renv_cache_package_validate(path))
256 return(renv_retrieve_successful(record, path))
257
258 }
259
260 }
261
262 # if this is a URL source, then it should already have a local path
263 # check for the Path and Source fields and see if they resolve
264 fields <- c("Path", "Source")
265 for (field in fields) {
266
267 # check for a valid field
268 path <- record[[field]]
269 if (is.null(path))
270 next
271
272 # check whether it looks like an explicit source
273 isurl <-
274 is.character(path) &&
275 nzchar(path) &&
276 grepl("[/\\]|[.](?:zip|tgz|gz)$", path)
277
278 if (!isurl)
279 next
280
281 # error if the field is declared but doesn't exist
282 if (!file.exists(path)) {
283 fmt <- "record for package '%s' declares local source '%s', but that file does not exist"
284 stopf(fmt, record$Package, path)
285 }
286
287 # otherwise, success
288 path <- renv_path_normalize(path, mustWork = TRUE)
289 return(renv_retrieve_successful(record, path))
290
291 }
292
293
294 # try some early shortcut methods
295 shortcuts <- if (rebuild) c(
296 renv_retrieve_cellar
297 ) else c(
298 renv_retrieve_explicit,
299 renv_retrieve_cellar,
300 if (!renv_tests_running() && config$install.shortcuts())
301 renv_retrieve_libpaths
302 )
303
304 for (shortcut in shortcuts) {
305 retrieved <- catch(shortcut(record))
306 if (identical(retrieved, TRUE))
307 return(TRUE)
308 }
309
310 state$downloaded <- state$downloaded + 1L
311 if (state$downloaded == 1L)
312 writef(header("Downloading packages"))
313
314 # time to retrieve -- delegate based on previously-determined source
315 switch(source,
316 bioconductor = renv_retrieve_bioconductor(record),
317 bitbucket = renv_retrieve_bitbucket(record),
318 git = renv_retrieve_git(record),
319 github = renv_retrieve_github(record),
320 gitlab = renv_retrieve_gitlab(record),
321 local = renv_retrieve_local(record),
322 repository = renv_retrieve_repos(record),
323 url = renv_retrieve_url(record),
324 renv_retrieve_unknown_source(record)
325 )
326
327 }
328
329 renv_retrieve_name <- function(record, type = "source", ext = NULL) {
330 package <- record$Package
331 version <- record$RemoteSha %||% record$Version
332 ext <- ext %||% renv_package_ext(type)
333 sprintf("%s_%s%s", package, version, ext)
334 }
335
336 renv_retrieve_path <- function(record, type = "source", ext = NULL) {
337
338 # extract relevant record information
339 package <- record$Package
340 name <- renv_retrieve_name(record, type, ext)
341
342 # if we have a destdir override, use this
343 if (!is.null(the$destdir))
344 return(file.path(the$destdir, name))
345
346 # check for packages from an PPM binary URL, and
347 # update the package type if known
348 source <- renv_record_source(record)
349 if (renv_ppm_enabled()) {
350 url <- attr(record, "url")
351 if (is.character(url) && grepl("/__[^_]+__/", url))
352 type <- "binary"
353 }
354
355 # form path for package to be downloaded
356 if (type == "source")
357 renv_paths_source(source, package, name)
358 else if (type == "binary")
359 renv_paths_binary(source, package, name)
360 else
361 stopf("unrecognized type '%s'", type)
362 }
363
364 renv_retrieve_bioconductor <- function(record) {
365
366 # try to read the bioconductor version from the record
367 version <- renv_retrieve_bioconductor_version(record)
368
369 # activate Bioconductor repositories in this context
370 project <- renv_restore_state(key = "project")
371 renv_scope_bioconductor(project = project, version = version)
372
373 # retrieve record using updated repositories
374 renv_retrieve_repos(record)
375
376 }
377
378 renv_retrieve_bioconductor_version <- function(record) {
379
380 # read git branch
381 branch <- record[["git_branch"]]
382 if (is.null(branch))
383 return(NULL)
384
385 # try and parse version
386 parts <- strsplit(branch, "_", fixed = TRUE)[[1L]]
387 ok <-
388 length(parts) == 3L &&
389 tolower(parts[[1L]]) == "release"
390
391 if (!ok)
392 return(NULL)
393
394 # we have a version; use it
395 paste(tail(parts, n = -1L), collapse = ".")
396
397 }
398
399 renv_retrieve_bitbucket <- function(record) {
400
401 # query repositories endpoint to find download URL
402 host <- record$RemoteHost %||% config$bitbucket.host()
403 origin <- renv_retrieve_origin(host)
404 username <- record$RemoteUsername
405 repo <- record$RemoteRepo
406
407 # scope authentication
408 renv_scope_auth(repo)
409
410 fmt <- "%s/repositories/%s/%s"
411 url <- sprintf(fmt, origin, username, repo)
412
413 destfile <- renv_scope_tempfile("renv-bitbucket-")
414 download(url, destfile = destfile, quiet = TRUE)
415 json <- renv_json_read(destfile)
416
417 # now build URL to tarball
418 base <- json$links$html$href
419 ref <- record$RemoteSha %||% record$RemoteRef
420
421 fmt <- "%s/get/%s.tar.gz"
422 url <- sprintf(fmt, base, ref)
423
424 path <- renv_retrieve_path(record)
425
426 renv_retrieve_package(record, url, path)
427
428 }
429
430 renv_retrieve_github <- function(record) {
431
432 host <- record$RemoteHost %||% config$github.host()
433 origin <- renv_retrieve_origin(host)
434 username <- record$RemoteUsername
435 repo <- record$RemoteRepo
436 ref <- record$RemoteSha %||% record$RemoteRef
437
438 if (is.null(ref)) {
439 fmt <- "GitHub record for package '%s' has no recorded 'RemoteSha' / 'RemoteRef'"
440 stopf(fmt, record$Package)
441 }
442
443 fmt <- "%s/repos/%s/%s/tarball/%s"
444 url <- with(record, sprintf(fmt, origin, username, repo, ref))
445 path <- renv_retrieve_path(record)
446 renv_retrieve_package(record, url, path)
447
448 }
449
450 renv_retrieve_gitlab <- function(record) {
451
452 host <- record$RemoteHost %||% config$gitlab.host()
453 origin <- renv_retrieve_origin(host)
454
455 user <- record$RemoteUsername
456 repo <- record$RemoteRepo
457 id <- URLencode(paste(user, repo, sep = "/"), reserved = TRUE)
458
459 fmt <- "%s/api/v4/projects/%s/repository/archive.tar.gz"
460 url <- sprintf(fmt, origin, id)
461 path <- renv_retrieve_path(record)
462
463 sha <- record$RemoteSha %||% record$RemoteRef
464 if (!is.null(sha))
465 url <- paste(url, paste("sha", sha, sep = "="), sep = "?")
466
467 renv_retrieve_package(record, url, path)
468
469 }
470
471 renv_retrieve_git <- function(record) {
472 # NOTE: This path will later be used during the install step, so we don't
473 # want to clean it up afterwards
474 path <- tempfile("renv-git-")
475 ensure_directory(path)
476 renv_retrieve_git_impl(record, path)
477 renv_retrieve_successful(record, path)
478 }
479
480 renv_retrieve_git_impl <- function(record, path) {
481
482 renv_git_preflight()
483
484 package <- record$Package
485 url <- record$RemoteUrl
486 ref <- record$RemoteRef
487 sha <- record$RemoteSha
488
489 # figure out the default ref
490 gitref <- case(
491 nzchar(sha %||% "") ~ sha,
492 nzchar(ref %||% "") ~ ref,
493 "HEAD"
494 )
495
496 # be quiet if requested
497 quiet <- getOption("renv.git.quiet", default = TRUE)
498 quiet <- if (quiet) "--quiet" else ""
499
500 template <- heredoc('
501 git init ${QUIET}
502 git remote add origin "${ORIGIN}"
503 git fetch ${QUIET} --depth=1 origin "${REF}"
504 git reset ${QUIET} --hard FETCH_HEAD
505 ')
506
507 data <- list(
508 ORIGIN = url,
509 REF = gitref,
510 QUIET = quiet
511 )
512
513 commands <- renv_template_replace(template, data)
514 command <- gsub("\n", " && ", commands, fixed = TRUE)
515 if (renv_platform_windows())
516 command <- paste(comspec(), "/C", command)
517
518 printf("- Cloning '%s' ... ", url)
519
520 before <- Sys.time()
521
522 status <- local({
523 ensure_directory(path)
524 renv_scope_wd(path)
525 renv_scope_auth(record)
526 renv_scope_git_auth()
527 system(command)
528 })
529
530 after <- Sys.time()
531
532 if (status != 0L) {
533 fmt <- "error cloning '%s' from '%s' [status code %i]"
534 stopf(fmt, package, url, status)
535 }
536
537 fmt <- "OK [cloned repository in %s]"
538 elapsed <- difftime(after, before, units = "auto")
539 writef(fmt, renv_difftime_format(elapsed))
540
541 TRUE
542
543 }
544
545
546 renv_retrieve_cellar_find <- function(record, project = NULL) {
547
548 project <- renv_project_resolve(project)
549
550 # packages installed with 'remotes::install_local()' will
551 # have a RemoteUrl entry that we can use
552 url <- record$RemoteUrl %||% ""
553 if (file.exists(url)) {
554 path <- renv_path_normalize(url, mustWork = TRUE)
555 type <- if (fileext(path) %in% c(".tgz", ".zip")) "binary" else "source"
556 return(named(path, type))
557 }
558
559 # otherwise, look in the cellar
560 roots <- renv_cellar_roots(project)
561 for (type in c("binary", "source")) {
562
563 name <- renv_retrieve_name(record, type = type)
564 for (root in roots) {
565
566 package <- record$Package
567 paths <- c(
568 file.path(root, package, name),
569 file.path(root, name)
570 )
571
572 for (path in paths)
573 if (file.exists(path))
574 return(named(path, type))
575
576 }
577 }
578
579 fmt <- "%s [%s] is not available locally"
580 stopf(fmt, record$Package, record$Version)
581
582 }
583
584 renv_retrieve_cellar_report <- function(record) {
585
586 source <- renv_record_source(record)
587 if (source == "cellar")
588 return(record)
589
590 fmt <- "- Package %s [%s] will be installed from the cellar."
591 with(record, writef(fmt, Package, Version))
592
593 record
594
595 }
596
597 renv_retrieve_cellar <- function(record) {
598 source <- renv_retrieve_cellar_find(record)
599 record <- renv_retrieve_cellar_report(record)
600 renv_retrieve_successful(record, source)
601 }
602
603 renv_retrieve_libpaths <- function(record) {
604
605 libpaths <- c(renv_libpaths_user(), renv_libpaths_site())
606 for (libpath in libpaths)
607 if (renv_retrieve_libpaths_impl(record, libpath))
608 return(TRUE)
609
610 }
611
612 renv_retrieve_libpaths_impl <- function(record, libpath) {
613
614 # form path to installed package's DESCRIPTION
615 path <- file.path(libpath, record$Package)
616 if (!file.exists(path))
617 return(FALSE)
618
619 # read DESCRIPTION
620 desc <- renv_description_read(path = path)
621
622 # check if it's compatible with the requested record
623 fields <- c("Package", "Version", grep("^Remote", names(record), value = TRUE))
624 compatible <- identical(record[fields], desc[fields])
625 if (!compatible)
626 return(FALSE)
627
628 # check that it was built for a compatible version of R
629 version <- catch(renv_description_built_version(desc))
630 if (inherits(version, "error") || is.na(version))
631 return(FALSE)
632
633 ok <- catch(renv_version_compare(version, getRversion(), 2L) == 0)
634 if (!isTRUE(ok))
635 return(FALSE)
636
637 # check that this package has a known source
638 source <- renv_snapshot_description_source(desc)
639 if (identical(source$Source, "unknown"))
640 return(FALSE)
641
642 # OK: copy this package as-is
643 renv_retrieve_successful(record, path)
644
645 }
646
647 renv_retrieve_explicit <- function(record) {
648
649 # try parsing as a local remote
650 source <- record$Path %||% record$RemoteUrl %||% ""
651 if (nzchar(source)) {
652 resolved <- catch(renv_remotes_resolve_path(source))
653 if (inherits(resolved, "error"))
654 return(FALSE)
655 }
656
657 # treat as 'local' source but extract path
658 normalized <- renv_path_normalize(source, mustWork = TRUE)
659 resolved$Source <- "Local"
660 renv_retrieve_successful(resolved, normalized)
661
662 }
663
664 renv_retrieve_repos <- function(record) {
665
666 # if this record is tagged with a type + url, we can
667 # use that directly for retrieval
668 if (renv_record_tagged(record))
669 return(renv_retrieve_repos_impl(record))
670
671 # figure out what package sources are okay to use here
672 pkgtype <- getOption("pkgType", default = "source")
673
674 srcok <-
675 pkgtype %in% c("both", "source") ||
676 getOption("install.packages.check.source", default = "yes") %in% "yes"
677
678 binok <-
679 pkgtype %in% c("both", "binary") ||
680 grepl("binary", pkgtype, fixed = TRUE)
681
682 # collect list of 'methods' for retrieval
683 methods <- stack(mode = "list")
684
685 # add binary package methods
686 if (binok) {
687
688 # prefer repository binaries if available
689 methods$push(renv_retrieve_repos_binary)
690
691 # also try fallback binary locations (for Nexus)
692 methods$push(renv_retrieve_repos_binary_fallback)
693
694 # if p3m is enabled, check those binaries as well
695 if (renv_p3m_enabled())
696 methods$push(renv_retrieve_repos_p3m)
697
698 }
699
700 # next, try to retrieve from sources
701 if (srcok) {
702
703 # retrieve from source repositories
704 methods$push(renv_retrieve_repos_source)
705
706 # also try fallback source locations (for Nexus)
707 methods$push(renv_retrieve_repos_source_fallback)
708
709 # if this is a package from r-universe, try restoring from github
710 # (currently inferred from presence for RemoteUrl field)
711 unifields <- c("RemoteUrl", "RemoteSha")
712 if (all(unifields %in% names(record)))
713 methods$push(renv_retrieve_git)
714 else
715 methods$push(renv_retrieve_repos_archive)
716
717 }
718
719 # capture errors for reporting
720 errors <- stack()
721
722 for (method in methods$data()) {
723
724 status <- catch(
725 withCallingHandlers(
726 method(record),
727 renv.retrieve.error = function(error) {
728 errors$push(error$data)
729 }
730 )
731 )
732
733 if (inherits(status, "error")) {
734 errors$push(status)
735 next
736 }
737
738 if (identical(status, TRUE))
739 return(TRUE)
740
741 if (!is.logical(status)) {
742 fmt <- "internal error: unexpected status code '%s'"
743 warningf(fmt, stringify(status))
744 }
745
746 }
747
748 # if we couldn't download the package, report the errors we saw
749 local({
750 renv_scope_options(warn = 1L)
751 for (error in errors$data())
752 warning(error)
753 })
754
755 remote <- renv_record_format_remote(record, compact = TRUE)
756 stopf("failed to retrieve package '%s'", remote)
757
758 }
759
760 renv_retrieve_url_resolve <- function(record) {
761
762 # https://github.com/rstudio/renv/issues/2060
763 pkgref <- record$RemotePkgRef
764 if (!is.null(pkgref)) {
765 remote <- renv_remotes_parse(pkgref)
766 if (identical(remote$type, "url"))
767 return(remote$url)
768 }
769
770 record$RemoteUrl
771
772 }
773
774 renv_retrieve_url <- function(record) {
775 url <- renv_retrieve_url_resolve(record)
776 resolved <- renv_remotes_resolve_url(url, quiet = FALSE)
777 renv_retrieve_successful(record, resolved$Path)
778 }
779
780 renv_retrieve_repos_archive_name <- function(record, type = "source") {
781
782 file <- record$File
783 if (length(file) && !is.na(file))
784 return(file)
785
786 ext <- renv_package_ext(type)
787 paste0(record$Package, "_", record$Version, ext)
788
789 }
790
791 renv_retrieve_repos_p3m <- function(record) {
792
793 # TODO: support Linux
794 if (renv_platform_linux())
795 return(FALSE)
796
797 # ensure local database is up-to-date
798 renv_p3m_database_refresh(explicit = FALSE)
799
800 # check that we have an available database
801 path <- renv_p3m_database_path()
802 if (!file.exists(path))
803 return(FALSE)
804
805 # attempt to read it
806 database <- catch(renv_p3m_database_load())
807 if (inherits(database, "error")) {
808 warning(database)
809 return(FALSE)
810 }
811
812 # get entry for this version of R + platform
813 suffix <- contrib.url("", type = "binary")
814 entry <- database[[suffix]]
815 if (is.null(entry))
816 return(FALSE)
817
818 # check for known entry for this package + version
819 key <- paste(record$Package, record$Version)
820 idate <- entry[[key]]
821 if (is.null(idate))
822 return(FALSE)
823
824 # convert from integer to date
825 date <- as.Date(idate, origin = "1970-01-01")
826
827 # form url to binary package
828 base <- renv_p3m_url(date, suffix)
829 name <- renv_retrieve_name(record, type = "binary")
830 url <- file.path(base, name)
831
832 # form path to saved file
833 path <- renv_retrieve_path(record, "binary")
834
835 # tag record with repository name
836 record <- overlay(record, list(
837 Source = "Repository",
838 Repository = "P3M"
839 ))
840
841 # attempt to retrieve
842 renv_retrieve_package(record, url, path)
843
844 }
845
846 renv_retrieve_repos_binary <- function(record) {
847 renv_retrieve_repos_impl(record, "binary")
848 }
849
850 renv_retrieve_repos_binary_fallback <- function(record) {
851
852 for (repo in getOption("repos")) {
853 if (renv_nexus_enabled(repo)) {
854 repourl <- contrib.url(repo, type = "binary")
855 status <- catch(renv_retrieve_repos_impl(record, "binary", repo = repourl))
856 if (!inherits(status, "error"))
857 return(status)
858 }
859 }
860
861 FALSE
862
863 }
864
865 renv_retrieve_repos_source <- function(record) {
866 renv_retrieve_repos_impl(record, "source")
867 }
868
869 renv_retrieve_repos_source_fallback <- function(record, repo) {
870
871 for (repo in getOption("repos")) {
872 if (renv_nexus_enabled(repo)) {
873 repourl <- contrib.url(repo, type = "source")
874 status <- catch(renv_retrieve_repos_impl(record, "source", repo = repourl))
875 if (!inherits(status, "error"))
876 return(status)
877 }
878 }
879
880 FALSE
881
882 }
883
884 renv_retrieve_repos_archive <- function(record) {
885
886 # get the current repositories
887 repos <- getOption("repos")
888
889 # if this record has a repository recorded, use or prefer it;
890 # in strict mode with a URL-valued Repository, use only that repository
891 repository <- record[["Repository"]]
892 strict <- renv_restore_state(key = "strict") %||% FALSE
893 if (is.character(repository)) {
894 names(repository) <- names(repository) %||% repository
895 if (grepl("://", repository, fixed = TRUE)) {
896 repos <- when(strict, repository, c(repository, repos))
897 } else if (!strict && repository %in% names(repos)) {
898 matches <- names(repos) == repository
899 repos <- c(repos[matches], repos[!matches])
900 }
901 }
902
903 for (repo in repos) {
904
905 # try to determine path to package in archive
906 root <- renv_retrieve_repos_archive_root(repo, record)
907 if (is.null(root))
908 next
909
910 # attempt download; report errors via condition handler
911 name <- renv_retrieve_repos_archive_name(record, type = "source")
912 status <- catch(renv_retrieve_repos_impl(record, "source", name, root))
913 if (inherits(status, "error")) {
914 attr(status, "record") <- record
915 renv_condition_signal("renv.retrieve.error", status)
916 }
917
918 # exit now if we had success
919 if (identical(status, TRUE))
920 return(TRUE)
921
922 }
923
924 return(FALSE)
925
926 }
927
928 renv_retrieve_repos_archive_root <- function(url, record) {
929
930 # allow users to provide a custom archive path for a record,
931 # in case they're using a repository that happens to archive
932 # packages with a different format than regular CRAN network
933 # https://github.com/rstudio/renv/issues/602
934 override <- getOption("renv.retrieve.repos.archive.path")
935 if (is.function(override)) {
936 result <- override(url, record)
937 if (!is.null(result))
938 return(result)
939 }
940
941 # retrieve the appropriate formatter for this repository url
942 formatter <- memoize(
943 key = url,
944 value = renv_retrieve_repos_archive_formatter(url)
945 )
946
947 # use it
948 formatter(url, record)
949
950 }
951
952 renv_retrieve_repos_archive_formatter <- function(url) {
953
954 # list of known formatters
955 formatters <- list(
956
957 # default CRAN format
958 cran = function(repo, record) {
959 with(record, file.path(repo, "src/contrib/Archive", Package))
960 },
961
962 # format used by older releases of Artifactory
963 # https://github.com/rstudio/renv/issues/602
964 # https://github.com/rstudio/renv/issues/1996
965 artifactory = function(repo, record) {
966 with(record, file.path(repo, "src/contrib/Archive", Package, Version))
967 },
968
969 # format used by Nexus
970 # https://github.com/rstudio/renv/issues/595
971 nexus = function(repo, record) {
972 with(record, file.path(repo, "src/contrib"))
973 }
974
975 )
976
977 # check for an override
978 override <- getOption("renv.repos.formatters")
979 if (!is.null(override)) {
980 formatter <- formatters[[override[[url]] %||% ""]]
981 if (!is.null(formatter))
982 return(formatter)
983 }
984
985 # build URL to PACKAGES file in src/contrib
986 pkgurl <- file.path(url, "src/contrib/PACKAGES")
987 headers <- renv_download_headers(pkgurl)
988
989 # use the headers to infer the repository type
990 if ("x-artifactory-id" %in% names(headers)) {
991 formatters[["cran"]]
992 } else if (grepl("Nexus", headers[["server"]] %||% "")) {
993 formatters[["nexus"]]
994 } else {
995 formatters[["cran"]]
996 }
997
998 }
999
1000 # NOTE: If 'repo' is provided, it should be the path to the appropriate 'arm'
1001 # of a repository, which is normally generated from the repository URL via
1002 # 'contrib.url()'.
1003 renv_retrieve_repos_impl <- function(record,
1004 type = NULL,
1005 name = NULL,
1006 repo = NULL)
1007 {
1008 package <- record$Package
1009 version <- record$Version
1010
1011 type <- type %||% attr(record, "type", exact = TRUE)
1012 name <- name %||% renv_retrieve_repos_archive_name(record, type)
1013 repo <- repo %||% attr(record, "url", exact = TRUE)
1014
1015 # if we weren't provided a repository for this package, try to find it
1016 if (is.null(repo)) {
1017
1018 # in strict mode with a URL-valued Repository, search only that repository
1019 repository <- record[["Repository"]]
1020 strict <- renv_restore_state(key = "strict") %||% FALSE
1021 repos <- if (strict && is.character(repository) && grepl("://", repository, fixed = TRUE))
1022 renv_repos_baseurl(repository)
1023
1024 entry <- catch(
1025 renv_available_packages_entry(
1026 package = package,
1027 type = type,
1028 filter = version,
1029 repos = repos,
1030 prefer = record[["Repository"]]
1031 )
1032 )
1033
1034 if (inherits(entry, "error")) {
1035 attr(entry, "record") <- record
1036 renv_condition_signal("renv.retrieve.error", entry)
1037 return(FALSE)
1038 }
1039
1040 # get repository path
1041 repo <- entry$Repository
1042
1043 # add in the path if available
1044 path <- entry$Path
1045 if (length(path) && !is.na(path))
1046 repo <- file.path(repo, path)
1047
1048 # update the tarball name if it was declared
1049 file <- entry$File
1050 if (length(file) && !is.na(file))
1051 name <- file
1052
1053 }
1054
1055 url <- file.path(repo, name)
1056 path <- renv_retrieve_path(record, type)
1057
1058 renv_retrieve_package(record, url, path)
1059
1060 }
1061
1062
1063 renv_retrieve_package <- function(record, url, path) {
1064
1065 ensure_parent_directory(path)
1066 type <- renv_record_source(record)
1067 status <- local({
1068 renv_scope_auth(record)
1069 preamble <- renv_retrieve_package_preamble(record, url)
1070 catch(download(url, preamble = preamble, destfile = path, type = type))
1071 })
1072
1073 # report error for logging upstream
1074 if (inherits(status, "error")) {
1075 attr(status, "record") <- record
1076 renv_condition_signal("renv.retrieve.error", status)
1077 }
1078
1079 # handle FALSE returns (shouldn't normally happen?)
1080 if (identical(status, FALSE)) {
1081 fmt <- "an unknown error occurred installing '%s' (%s)"
1082 msg <- sprintf(fmt, record$Package, renv_record_format_remote(record))
1083 status <- simpleError(msg)
1084 }
1085
1086 # handle errors
1087 if (inherits(status, "error"))
1088 stop(status)
1089
1090 # handle success
1091 renv_retrieve_successful(record, path)
1092
1093 }
1094
1095 renv_retrieve_package_preamble <- function(record, url) {
1096
1097 package <- record[["Package"]]
1098 version <- record[["Version"]]
1099
1100 source <- record[["Repository"]] %||% record[["Source"]]
1101 if (identical(source, "Repository"))
1102 source <- record[["RemoteReposName"]]
1103
1104 parts <- c(package, version, if (length(source)) c("from", source))
1105 body <- paste(parts, collapse = " ")
1106
1107 fmt <- "- Downloading %s ... "
1108 msg <- sprintf(fmt, body)
1109
1110 format(msg, width = the$install_step_width)
1111
1112 }
1113
1114 renv_retrieve_successful_subdir <- function(record, path) {
1115
1116 # if it's a file, assume RemoteSubdir needs to be honored
1117 info <- file.info(path, extra_cols = FALSE)
1118 if (identical(info$isdir, FALSE))
1119 return(record$RemoteSubdir)
1120
1121 # otherwise, respect RemoteSubdir only if it seems to
1122 # point at a valid DESCRPITION file
1123 if (!is.null(record$RemoteSubdir)) {
1124 parts <- c(path, record$RemoteSubdir, "DESCRIPTION")
1125 descpath <- paste(parts, collapse = "/")
1126 if (file.exists(descpath))
1127 return(record$RemoteSubdir)
1128 }
1129
1130 }
1131
1132 renv_retrieve_successful <- function(record, path, install = TRUE) {
1133
1134 # if we downloaded an archive, adjust its permissions here
1135 mode <- Sys.getenv("RENV_CACHE_MODE", unset = NA)
1136 if (!is.na(mode)) {
1137 info <- file.info(path, extra_cols = FALSE)
1138 if (identical(info$isdir, FALSE)) {
1139 parent <- dirname(path)
1140 renv_system_exec(
1141 command = "chmod",
1142 args = c("-Rf", renv_shell_quote(mode), renv_shell_path(parent)),
1143 action = "chmoding cached package",
1144 quiet = TRUE,
1145 success = NULL
1146 )
1147 }
1148 }
1149
1150 # the handling of 'subdir' here is a little awkward, as this function
1151 # can receive:
1152 #
1153 # - archives, whose package might live within a sub-directory;
1154 # - folders, whose package might live within a sub-directory;
1155 # - cache paths, for which the subdir is no longer relevant
1156 #
1157 # this warrants a proper cleanup, but for now we we use a hack
1158 subdir <- renv_retrieve_successful_subdir(record, path)
1159
1160 # augment record with information from DESCRIPTION file
1161 desc <- renv_description_read(path, subdir = subdir)
1162
1163 # update the record's package name, version
1164 # TODO: should we warn if they didn't match for some reason?
1165 package <- record$Package <- desc$Package
1166 record$Version <- desc$Version
1167
1168 # add in path information to record (used later during install)
1169 record$Path <- path
1170
1171 # add information on the retrieved record
1172 state <- renv_restore_state()
1173 state$retrieved[[package]] <- record
1174
1175 # record this package's requirements
1176 requirements <- state$requirements
1177
1178 # figure out the dependency fields to use -- if the user explicitly requested
1179 # this package be installed, but also provided a 'dependencies' argument in
1180 # the call to 'install()', then we want to install those as well.
1181 #
1182 # however, those packages need to be installed at a lower priority, since it's
1183 # common for there to be circular-ish dependency relationships, where one
1184 # package A imports package B, but package B suggests package A in turn.
1185 fields <- if (package %in% state$packages) the$install_dependency_fields else "strong"
1186 deps <- renv_dependencies_discover_description(path, subdir = subdir, fields = fields)
1187 if (length(deps$Source))
1188 deps$Source <- record$Package
1189
1190 # set up package requirements for 'strong' dependencies
1191 rowapply(deps, function(dep) {
1192 package <- dep[["Package"]]
1193 requirements[[package]] <- requirements[[package]] %||% stack()
1194 requirements[[package]]$push(dep)
1195 })
1196
1197 # read and handle remotes declared by this package
1198 remotes <- desc$Remotes
1199 if (length(remotes) && config$install.remotes())
1200 renv_retrieve_remotes(remotes)
1201
1202 # split into strong + weak dependencies
1203 strong <- deps$Type %in% c("Depends", "Imports", "LinkingTo")
1204 strongdeps <- rows(deps, strong)
1205 weakdeps <- rows(deps, !strong)
1206
1207 # recursively install strong dependencies first
1208 if (state$recursive && nrow(strongdeps)) local({
1209
1210 # make sure bioconductor repositories are active before install if necessary
1211 if (nzchar(desc[["biocViews"]] %||% "")) {
1212 repos <- renv_bioconductor_repos()
1213 renv_scope_options(repos = repos)
1214 }
1215
1216 # now recurse
1217 renv_retrieve_successful_recurse(strongdeps)
1218
1219 })
1220
1221 # mark package as requiring install if needed
1222 if (install && !state$install$contains(package))
1223 state$install$insert(package, record)
1224
1225 # now recursively retrieve weak dependencies
1226 if (state$recursive && nrow(weakdeps)) local({
1227
1228 # make sure bioconductor repositories are active before install if necessary
1229 if (nzchar(desc[["biocViews"]] %||% "")) {
1230 repos <- renv_bioconductor_repos()
1231 renv_scope_options(repos = repos)
1232 }
1233
1234 # now recursive
1235 renv_retrieve_successful_recurse(weakdeps)
1236
1237 })
1238
1239 TRUE
1240
1241 }
1242
1243 renv_retrieve_successful_recurse <- function(deps) {
1244 remotes <- setdiff(unique(deps$Package), renv_packages_base())
1245 for (remote in remotes)
1246 renv_retrieve_successful_recurse_impl(remote)
1247 }
1248
1249 renv_retrieve_successful_recurse_impl_check <- function(remote) {
1250
1251 # only done for package names
1252 if (!grepl(renv_regexps_package_name(), remote))
1253 return(FALSE)
1254
1255 # check whether this package has been retrieved yet
1256 state <- renv_restore_state()
1257 record <- state$retrieved[[remote]]
1258 if (is.null(record) || identical(record, NA))
1259 return(FALSE)
1260
1261 # check the current requirements for this package
1262 incompat <- renv_retrieve_incompatible(remote, record)
1263 if (NROW(incompat) == 0L)
1264 return(FALSE)
1265
1266 # we have an incompatible record; ensure it gets retrieved
1267 state$retrieved[[remote]] <- NULL
1268 TRUE
1269
1270 }
1271
1272 renv_retrieve_successful_recurse_impl <- function(remote) {
1273
1274 # if remote is a plain package name that we've already retrieved,
1275 # we may need to retrieve it again if the version of that package
1276 # required is greater than the previously-obtained version
1277 #
1278 # TODO: implement a proper solver so we can stop doing these hacks...
1279 # if this is a 'plain' package remote, retrieve it
1280 force <- renv_retrieve_successful_recurse_impl_check(remote)
1281
1282 dynamic(
1283 key = list(remote = remote),
1284 value = renv_retrieve_successful_recurse_impl_one(remote),
1285 force = force
1286 )
1287
1288 }
1289
1290 renv_retrieve_successful_recurse_impl_one <- function(remote) {
1291
1292 # ignore base packages
1293 base <- renv_packages_base()
1294 if (remote %in% base)
1295 return(list())
1296
1297 # if this is a 'plain' package remote, retrieve it
1298 if (grepl(renv_regexps_package_name(), remote)) {
1299 renv_retrieve_impl_one(remote)
1300 return(list())
1301 }
1302
1303 # otherwise, handle custom remotes
1304 record <- renv_retrieve_remotes_impl(remote)
1305 if (length(record)) {
1306 renv_retrieve_impl_one(record$Package)
1307 return(list())
1308 }
1309
1310 list()
1311
1312 }
1313
1314 renv_retrieve_local <- function(record) {
1315
1316 # try to find a matching local package
1317 status <- catch(renv_retrieve_cellar(record))
1318 if (!inherits(status, "error"))
1319 return(status)
1320
1321 # failed; try to retrieve from an R package repository
1322 record$Source <- "Repository"
1323 renv_retrieve_repos(record)
1324
1325 }
1326
1327 renv_retrieve_unknown_source <- function(record) {
1328 renv_retrieve_local(record)
1329 }
1330
1331 # TODO: what should we do if we detect incompatible remotes?
1332 # e.g. if pkg A requests 'r-lib/[email protected]' but pkg B requests
1333 # 'r-lib/[email protected]'.
1334 renv_retrieve_remotes <- function(remotes) {
1335 remotes <- strsplit(remotes, "\\s*,\\s*")[[1L]]
1336 for (remote in remotes)
1337 renv_retrieve_remotes_impl(remote)
1338 }
1339
1340 renv_retrieve_remotes_impl <- function(remote) {
1341
1342 dynamic(
1343 key = list(remote = remote),
1344 value = renv_retrieve_remotes_impl_one(remote)
1345 )
1346
1347 }
1348
1349 renv_retrieve_remotes_impl_one <- function(remote) {
1350
1351 # TODO: allow customization of behavior when remote parsing fails?
1352 resolved <- catch(renv_remotes_resolve(remote))
1353 if (inherits(resolved, "error")) {
1354 warningf("failed to resolve remote '%s'; skipping", remote)
1355 return(invisible(NULL))
1356 }
1357
1358 # get the current package record
1359 state <- renv_restore_state()
1360 package <- resolved$Package
1361 record <- state$records[[package]]
1362
1363 # if we already have a package record, and it's not a 'plain'
1364 # repository record, skip
1365 skip <-
1366 !is.null(record) &&
1367 !identical(record, list(Package = package, Source = "Repository"))
1368
1369 if (skip) {
1370 dlog("retrieve", "skipping remote '%s'; it's already been declared", remote)
1371 dlog("retrieve", "using existing remote '%s'", stringify(record))
1372 return(invisible(NULL))
1373 }
1374
1375 # update the requested record
1376 dlog("retrieve", "using remote '%s'", remote)
1377 state$records[[package]] <- resolved
1378
1379 # mark the record as needing retrieval
1380 state$retrieved[[package]] <- NULL
1381
1382 # return new record
1383 invisible(resolved)
1384
1385 }
1386
1387 renv_retrieve_resolve <- function(package) {
1388 tryCatch(
1389 renv_snapshot_description(package = package),
1390 error = function(e) {
1391 renv_retrieve_missing_record(package)
1392 }
1393 )
1394 }
1395
1396 renv_retrieve_missing_record <- function(package) {
1397
1398 # TODO: allow users to configure the action to take here, e.g.
1399 #
1400 # 1. retrieve latest from R repositories (the default),
1401 # 2. request a package + version to be retrieved,
1402 # 3. hard error
1403 #
1404 record <- renv_available_packages_latest(package)
1405 if (!is.null(record))
1406 return(record)
1407
1408 fmt <- heredoc("
1409 renv was unable to find a compatible version of package '%1$s'.
1410
1411 The latest-available version %1$s is '%2$s', but that version
1412 does not appear to be compatible with this version of R.
1413
1414 You may need to manually re-install a different version of '%1$s'.
1415 ")
1416
1417 entry <- renv_available_packages_entry(package, type = "source")
1418 version <- entry$Version %||% "<unknown>"
1419
1420 writef(fmt, package, version)
1421
1422 stopf("failed to find a compatible version of the '%s' package", package)
1423
1424 }
1425
1426 # check to see if this requested record is incompatible
1427 # with the set of required dependencies recorded thus far
1428 # during the package retrieval process
1429 renv_retrieve_incompatible <- function(package, record) {
1430
1431 state <- renv_restore_state()
1432 record <- renv_record_validate(package, record)
1433
1434 # check and see if the installed version satisfies all requirements
1435 requirements <- state$requirements[[package]]
1436 if (is.null(requirements))
1437 return(NULL)
1438
1439 data <- bind(requirements$data())
1440 explicit <- data[nzchar(data$Require) & nzchar(data$Version), ]
1441 if (nrow(explicit) == 0)
1442 return(NULL)
1443
1444 # drop 'Dev' column
1445 explicit$Dev <- NULL
1446
1447 # retrieve record version
1448 version <- record$Version
1449 if (is.null(version))
1450 return(NULL)
1451
1452 # for each row, compute whether we're compatible
1453 rversion <- numeric_version(version)
1454 compatible <- map_lgl(seq_len(nrow(explicit)), function(i) {
1455 expr <- call(explicit$Require[[i]], rversion, explicit$Version[[i]])
1456 eval(expr, envir = baseenv())
1457 })
1458
1459 # keep whatever wasn't compatible
1460 explicit[!compatible, ]
1461
1462 }
1463
1464 renv_retrieve_incompatible_report <- function(package, record, replacement, compat) {
1465
1466 # only report if the user explicitly requesting installation of a particular
1467 # version of a package, but that package isn't actually compatible
1468 state <- renv_restore_state()
1469 if (!package %in% state$packages)
1470 return()
1471
1472 fmt <- "%s (requires %s %s %s)"
1473 values <- with(compat, sprintf(fmt, Source, Package, Require, Version))
1474
1475 fmt <- "Installation of '%s %s' was requested, but the following constraints are not met:"
1476 preamble <- with(record, sprintf(fmt, Package, Version))
1477
1478 fmt <- "renv will try to install '%s %s' instead."
1479 postamble <- with(replacement, sprintf(fmt, Package, Version))
1480
1481 if (!renv_tests_running()) {
1482 bulletin(
1483 preamble = preamble,
1484 values = values,
1485 postamble = postamble
1486 )
1487 }
1488
1489 }
1490
1491 renv_retrieve_origin <- function(host) {
1492
1493 # NOTE: some host URLs may come with a protocol already formed;
1494 # if we find a protocol, use it as-is
1495 if (grepl("://", host, fixed = TRUE))
1496 return(host)
1497
1498 # otherwise, prepend protocol (assume https)
1499 paste("https", host, sep = "://")
1500
1501 }