Debian Codegraph @

R/bootstrap.R

raw
1
2 `%||%` <- function(x, y) {
3 if (is.null(x)) y else x
4 }
5
6 catf <- function(fmt, ..., appendLF = TRUE) {
7
8 quiet <- getOption("renv.bootstrap.quiet", default = FALSE)
9 if (quiet)
10 return(invisible())
11
12 # also check for config environment variables that should suppress messages
13 # https://github.com/rstudio/renv/issues/2214
14 enabled <- Sys.getenv("RENV_CONFIG_STARTUP_QUIET", unset = NA)
15 if (!is.na(enabled) && tolower(enabled) %in% c("true", "1"))
16 return(invisible())
17
18 enabled <- Sys.getenv("RENV_CONFIG_SYNCHRONIZED_CHECK", unset = NA)
19 if (!is.na(enabled) && tolower(enabled) %in% c("false", "0"))
20 return(invisible())
21
22 msg <- sprintf(fmt, ...)
23 cat(msg, file = stdout(), sep = if (appendLF) "\n" else "")
24
25 invisible(msg)
26
27 }
28
29 header <- function(label,
30 ...,
31 prefix = "#",
32 suffix = "-",
33 n = min(getOption("width"), 78))
34 {
35 label <- sprintf(label, ...)
36 n <- max(n - nchar(label) - nchar(prefix) - 2L, 8L)
37 if (n <= 0)
38 return(paste(prefix, label))
39
40 tail <- paste(rep.int(suffix, n), collapse = "")
41 paste0(prefix, " ", label, " ", tail)
42
43 }
44
45 heredoc <- function(text, leave = 0) {
46
47 # remove leading, trailing whitespace
48 trimmed <- gsub("^\\s*\\n|\\n\\s*$", "", text)
49
50 # split into lines
51 lines <- strsplit(trimmed, "\n", fixed = TRUE)[[1L]]
52
53 # compute common indent
54 indent <- regexpr("[^[:space:]]", lines)
55 common <- min(setdiff(indent, -1L)) - leave
56 text <- paste(substring(lines, common), collapse = "\n")
57
58 # substitute in ANSI links for executable renv code
59 ansify(text)
60
61 }
62
63 bootstrap <- function(version, library) {
64
65 friendly <- renv_bootstrap_version_friendly(version)
66 section <- header(sprintf("Bootstrapping renv %s", friendly))
67 catf(section)
68
69 # ensure the target library path exists; required for file.copy(..., recursive = TRUE)
70 dir.create(library, showWarnings = FALSE, recursive = TRUE)
71
72 # try to install renv from cache
73 md5 <- attr(version, "md5", exact = TRUE)
74 if (length(md5)) {
75 pkgpath <- renv_bootstrap_find(version)
76 if (length(pkgpath) && file.exists(pkgpath)) {
77 ok <- file.copy(pkgpath, library, recursive = TRUE)
78 if (isTRUE(ok))
79 return(invisible())
80 }
81 }
82
83 # attempt to download renv
84 catf("- Downloading renv ... ", appendLF = FALSE)
85 withCallingHandlers(
86 tarball <- renv_bootstrap_download(version),
87 error = function(err) {
88 catf("FAILED")
89 stop("failed to download:\n", conditionMessage(err))
90 }
91 )
92 catf("OK")
93 on.exit(unlink(tarball), add = TRUE)
94
95 # now attempt to install
96 catf("- Installing renv ... ", appendLF = FALSE)
97 withCallingHandlers(
98 status <- renv_bootstrap_install(version, tarball, library),
99 error = function(err) {
100 catf("FAILED")
101 stop("failed to install:\n", conditionMessage(err))
102 }
103 )
104 catf("OK")
105
106 # add empty line to break up bootstrapping from normal output
107 catf("")
108 return(invisible())
109 }
110
111 renv_bootstrap_tests_running <- function() {
112 getOption("renv.tests.running", default = FALSE)
113 }
114
115 renv_bootstrap_repos <- function() {
116
117 # get CRAN repository
118 cran <- getOption("renv.repos.cran", "https://cloud.r-project.org")
119
120 # check for repos override
121 repos <- Sys.getenv("RENV_CONFIG_REPOS_OVERRIDE", unset = NA)
122 if (!is.na(repos)) {
123
124 # split on ';' if present
125 parts <- strsplit(repos, ";", fixed = TRUE)[[1L]]
126
127 # split into named repositories if present
128 idx <- regexpr("=", parts, fixed = TRUE)
129 keys <- substring(parts, 1L, idx - 1L)
130 vals <- substring(parts, idx + 1L)
131 names(vals) <- keys
132
133 # if we have a single unnamed repository, call it CRAN
134 if (length(vals) == 1L && identical(keys, ""))
135 names(vals) <- "CRAN"
136
137 return(vals)
138
139 }
140
141 # check for lockfile repositories
142 repos <- tryCatch(renv_bootstrap_repos_lockfile(), error = identity)
143 if (!inherits(repos, "error") && length(repos))
144 return(repos)
145
146 # retrieve current repos
147 repos <- getOption("repos")
148
149 # ensure @CRAN@ entries are resolved
150 repos[repos == "@CRAN@"] <- cran
151
152 # add in renv.bootstrap.repos if set
153 default <- c(FALLBACK = "https://cloud.r-project.org")
154 extra <- getOption("renv.bootstrap.repos", default = default)
155 repos <- c(repos, extra)
156
157 # remove duplicates that might've snuck in
158 dupes <- duplicated(repos) | duplicated(names(repos))
159 repos[!dupes]
160
161 }
162
163 renv_bootstrap_repos_lockfile <- function() {
164
165 lockpath <- Sys.getenv("RENV_PATHS_LOCKFILE", unset = "renv.lock")
166 if (!file.exists(lockpath))
167 return(NULL)
168
169 lockfile <- tryCatch(renv_json_read(lockpath), error = identity)
170 if (inherits(lockfile, "error")) {
171 warning(lockfile)
172 return(NULL)
173 }
174
175 repos <- lockfile$R$Repositories
176 if (length(repos) == 0)
177 return(NULL)
178
179 keys <- vapply(repos, `[[`, "Name", FUN.VALUE = character(1))
180 vals <- vapply(repos, `[[`, "URL", FUN.VALUE = character(1))
181 names(vals) <- keys
182
183 return(vals)
184
185 }
186
187 renv_bootstrap_download <- function(version) {
188
189 sha <- attr(version, "sha", exact = TRUE)
190
191 methods <- if (!is.null(sha)) {
192
193 # attempting to bootstrap a development version of renv
194 c(
195 function() renv_bootstrap_download_tarball(sha),
196 function() renv_bootstrap_download_github(sha)
197 )
198
199 } else {
200
201 # attempting to bootstrap a release version of renv
202 c(
203 function() renv_bootstrap_download_tarball(version),
204 function() renv_bootstrap_download_cran_latest(version),
205 function() renv_bootstrap_download_cran_archive(version)
206 )
207
208 }
209
210 for (method in methods) {
211 path <- tryCatch(method(), error = identity)
212 if (is.character(path) && file.exists(path))
213 return(path)
214 }
215
216 stop("All download methods failed")
217
218 }
219
220 renv_bootstrap_download_impl <- function(url, destfile) {
221
222 mode <- "wb"
223
224 # https://bugs.r-project.org/bugzilla/show_bug.cgi?id=17715
225 fixup <-
226 Sys.info()[["sysname"]] == "Windows" &&
227 substring(url, 1L, 5L) == "file:"
228
229 if (fixup)
230 mode <- "w+b"
231
232 args <- list(
233 url = url,
234 destfile = destfile,
235 mode = mode,
236 quiet = TRUE
237 )
238
239 if ("headers" %in% names(formals(utils::download.file))) {
240 headers <- renv_bootstrap_download_custom_headers(url)
241 if (length(headers) && is.character(headers))
242 args$headers <- headers
243 }
244
245 do.call(utils::download.file, args)
246
247 }
248
249 renv_bootstrap_download_custom_headers <- function(url) {
250
251 headers <- getOption("renv.download.headers")
252 if (is.null(headers))
253 return(character())
254
255 if (!is.function(headers))
256 stopf("'renv.download.headers' is not a function")
257
258 headers <- headers(url)
259 if (length(headers) == 0L)
260 return(character())
261
262 if (is.list(headers))
263 headers <- unlist(headers, recursive = FALSE, use.names = TRUE)
264
265 ok <-
266 is.character(headers) &&
267 is.character(names(headers)) &&
268 all(nzchar(names(headers)))
269
270 if (!ok)
271 stop("invocation of 'renv.download.headers' did not return a named character vector")
272
273 headers
274
275 }
276
277 renv_bootstrap_download_cran_latest <- function(version) {
278
279 spec <- renv_bootstrap_download_cran_latest_find(version)
280 type <- spec$type
281 repos <- spec$repos
282
283 baseurl <- utils::contrib.url(repos = repos, type = type)
284 ext <- if (identical(type, "source"))
285 ".tar.gz"
286 else if (Sys.info()[["sysname"]] == "Windows")
287 ".zip"
288 else
289 ".tgz"
290 name <- sprintf("renv_%s%s", version, ext)
291 url <- paste(baseurl, name, sep = "/")
292
293 destfile <- file.path(tempdir(), name)
294 status <- tryCatch(
295 renv_bootstrap_download_impl(url, destfile),
296 condition = identity
297 )
298
299 if (inherits(status, "condition"))
300 return(FALSE)
301
302 # report success and return
303 destfile
304
305 }
306
307 renv_bootstrap_download_cran_latest_find <- function(version) {
308
309 # check whether binaries are supported on this system
310 binary <-
311 getOption("renv.bootstrap.binary", default = TRUE) &&
312 !identical(.Platform$pkgType, "source") &&
313 !identical(getOption("pkgType"), "source") &&
314 Sys.info()[["sysname"]] %in% c("Darwin", "Windows")
315
316 types <- c(if (binary) "binary", "source")
317
318 # iterate over types + repositories
319 for (type in types) {
320 for (repos in renv_bootstrap_repos()) {
321
322 # build arguments for utils::available.packages() call
323 args <- list(type = type, repos = repos)
324
325 # add custom headers if available -- note that
326 # utils::available.packages() will pass this to download.file()
327 if ("headers" %in% names(formals(utils::download.file))) {
328 headers <- renv_bootstrap_download_custom_headers(repos)
329 if (length(headers) && is.character(headers))
330 args$headers <- headers
331 }
332
333 # retrieve package database
334 db <- tryCatch(
335 as.data.frame(
336 do.call(utils::available.packages, args),
337 stringsAsFactors = FALSE
338 ),
339 error = identity
340 )
341
342 if (inherits(db, "error"))
343 next
344
345 # check for compatible entry
346 entry <- db[db$Package %in% "renv" & db$Version %in% version, ]
347 if (nrow(entry) == 0)
348 next
349
350 # found it; return spec to caller
351 spec <- list(entry = entry, type = type, repos = repos)
352 return(spec)
353
354 }
355 }
356
357 # if we got here, we failed to find renv
358 fmt <- "renv %s is not available from your declared package repositories"
359 stop(sprintf(fmt, version))
360
361 }
362
363 renv_bootstrap_download_cran_archive <- function(version) {
364
365 name <- sprintf("renv_%s.tar.gz", version)
366 repos <- renv_bootstrap_repos()
367 urls <- file.path(repos, "src/contrib/Archive/renv", name)
368 destfile <- file.path(tempdir(), name)
369
370 for (url in urls) {
371
372 status <- tryCatch(
373 renv_bootstrap_download_impl(url, destfile),
374 condition = identity
375 )
376
377 if (identical(status, 0L))
378 return(destfile)
379
380 }
381
382 return(FALSE)
383
384 }
385
386 renv_bootstrap_find <- function(version) {
387
388 path <- renv_bootstrap_find_cache(version)
389 if (length(path) && file.exists(path)) {
390 catf("- Using renv %s from global package cache", version)
391 return(path)
392 }
393
394 }
395
396 renv_bootstrap_find_cache <- function(version) {
397
398 md5 <- attr(version, "md5", exact = TRUE)
399 if (is.null(md5))
400 return()
401
402 # infer path to renv cache
403 cache <- Sys.getenv("RENV_PATHS_CACHE", unset = "")
404 if (!nzchar(cache)) {
405 root <- Sys.getenv("RENV_PATHS_ROOT", unset = NA)
406 if (!is.na(root))
407 cache <- file.path(root, "cache")
408 }
409
410 if (!nzchar(cache)) {
411 tools <- asNamespace("tools")
412 if (is.function(tools$R_user_dir)) {
413 root <- tools$R_user_dir("renv", "cache")
414 cache <- file.path(root, "cache")
415 }
416 }
417
418 # start completing path to cache
419 file.path(
420 cache,
421 renv_bootstrap_cache_version(),
422 renv_bootstrap_platform_prefix(),
423 "renv",
424 version,
425 md5,
426 "renv"
427 )
428
429 }
430
431 renv_bootstrap_download_tarball <- function(version) {
432
433 # if the user has provided the path to a tarball via
434 # an environment variable, then use it
435 tarball <- Sys.getenv("RENV_BOOTSTRAP_TARBALL", unset = NA)
436 if (is.na(tarball))
437 return()
438
439 # allow directories
440 if (dir.exists(tarball)) {
441 name <- sprintf("renv_%s.tar.gz", version)
442 tarball <- file.path(tarball, name)
443 }
444
445 # bail if it doesn't exist
446 if (!file.exists(tarball)) {
447
448 # let the user know we weren't able to honour their request
449 fmt <- "- RENV_BOOTSTRAP_TARBALL is set (%s) but does not exist."
450 msg <- sprintf(fmt, tarball)
451 warning(msg)
452
453 # bail
454 return()
455
456 }
457
458 catf("- Using local tarball '%s'.", tarball)
459 tarball
460
461 }
462
463 renv_bootstrap_github_token <- function() {
464 for (envvar in c("GITHUB_TOKEN", "GITHUB_PAT", "GH_TOKEN")) {
465 envval <- Sys.getenv(envvar, unset = NA)
466 if (!is.na(envval))
467 return(envval)
468 }
469 }
470
471 renv_bootstrap_download_github <- function(version) {
472
473 enabled <- Sys.getenv("RENV_BOOTSTRAP_FROM_GITHUB", unset = "TRUE")
474 if (!identical(enabled, "TRUE"))
475 return(FALSE)
476
477 # prepare download options
478 token <- renv_bootstrap_github_token()
479 if (is.null(token))
480 token <- ""
481
482 if (nzchar(Sys.which("curl")) && nzchar(token)) {
483 fmt <- "--location --fail --header \"Authorization: token %s\""
484 extra <- sprintf(fmt, token)
485 saved <- options("download.file.method", "download.file.extra")
486 options(download.file.method = "curl", download.file.extra = extra)
487 on.exit(do.call(base::options, saved), add = TRUE)
488 } else if (nzchar(Sys.which("wget")) && nzchar(token)) {
489 fmt <- "--header=\"Authorization: token %s\""
490 extra <- sprintf(fmt, token)
491 saved <- options("download.file.method", "download.file.extra")
492 options(download.file.method = "wget", download.file.extra = extra)
493 on.exit(do.call(base::options, saved), add = TRUE)
494 }
495
496 url <- file.path("https://api.github.com/repos/rstudio/renv/tarball", version)
497 name <- sprintf("renv_%s.tar.gz", version)
498 destfile <- file.path(tempdir(), name)
499
500 status <- tryCatch(
501 renv_bootstrap_download_impl(url, destfile),
502 condition = identity
503 )
504
505 if (!identical(status, 0L))
506 return(FALSE)
507
508 renv_bootstrap_download_augment(destfile)
509
510 return(destfile)
511
512 }
513
514 # Add Sha to DESCRIPTION. This is stop gap until #890, after which we
515 # can use renv::install() to fully capture metadata.
516 renv_bootstrap_download_augment <- function(destfile) {
517 sha <- renv_bootstrap_git_extract_sha1_tar(destfile)
518 if (is.null(sha)) {
519 return()
520 }
521
522 # Untar
523 tempdir <- tempfile("renv-github-")
524 on.exit(unlink(tempdir, recursive = TRUE), add = TRUE)
525 untar(destfile, exdir = tempdir)
526 pkgdir <- dir(tempdir, full.names = TRUE)[[1]]
527
528 # Modify description
529 desc_path <- file.path(pkgdir, "DESCRIPTION")
530 desc_lines <- readLines(desc_path)
531 remotes_fields <- c(
532 "RemoteType: github",
533 "RemoteHost: api.github.com",
534 "RemoteRepo: renv",
535 "RemoteUsername: rstudio",
536 "RemotePkgRef: rstudio/renv",
537 paste("RemoteRef: ", sha),
538 paste("RemoteSha: ", sha)
539 )
540 writeLines(c(desc_lines[desc_lines != ""], remotes_fields), con = desc_path)
541
542 # Re-tar
543 local({
544 old <- setwd(tempdir)
545 on.exit(setwd(old), add = TRUE)
546
547 tar(destfile, compression = "gzip")
548 })
549 invisible()
550 }
551
552 # Extract the commit hash from a git archive. Git archives include the SHA1
553 # hash as the comment field of the tarball pax extended header
554 # (see https://www.kernel.org/pub/software/scm/git/docs/git-archive.html)
555 # For GitHub archives this should be the first header after the default one
556 # (512 byte) header.
557 renv_bootstrap_git_extract_sha1_tar <- function(bundle) {
558
559 # open the bundle for reading
560 # We use gzcon for everything because (from ?gzcon)
561 # > Reading from a connection which does not supply a 'gzip' magic
562 # > header is equivalent to reading from the original connection
563 conn <- gzcon(file(bundle, open = "rb", raw = TRUE))
564 on.exit(close(conn))
565
566 # The default pax header is 512 bytes long and the first pax extended header
567 # with the comment should be 51 bytes long
568 # `52 comment=` (11 chars) + 40 byte SHA1 hash
569 len <- 0x200 + 0x33
570 res <- rawToChar(readBin(conn, "raw", n = len)[0x201:len])
571
572 if (grepl("^52 comment=", res)) {
573 sub("52 comment=", "", res)
574 } else {
575 NULL
576 }
577 }
578
579 renv_bootstrap_install <- function(version, tarball, library) {
580
581 # attempt to install it into project library
582 dir.create(library, showWarnings = FALSE, recursive = TRUE)
583 output <- renv_bootstrap_install_impl(library, tarball)
584
585 # check for successful install
586 status <- attr(output, "status")
587 if (is.null(status) || identical(status, 0L))
588 return(status)
589
590 # an error occurred; report it
591 header <- "installation of renv failed"
592 lines <- paste(rep.int("=", nchar(header)), collapse = "")
593 text <- paste(c(header, lines, output), collapse = "\n")
594 stop(text)
595
596 }
597
598 renv_bootstrap_install_impl <- function(library, tarball) {
599
600 # invoke using system2 so we can capture and report output
601 bin <- R.home("bin")
602 exe <- if (Sys.info()[["sysname"]] == "Windows") "R.exe" else "R"
603 R <- file.path(bin, exe)
604
605 args <- c(
606 "--vanilla", "CMD", "INSTALL", "--no-multiarch",
607 "-l", shQuote(path.expand(library)),
608 shQuote(path.expand(tarball))
609 )
610
611 system2(R, args, stdout = TRUE, stderr = TRUE)
612
613 }
614
615 renv_bootstrap_platform_prefix_default <- function() {
616
617 # read version component
618 version <- Sys.getenv("RENV_PATHS_VERSION", unset = "R-%v")
619
620 # expand placeholders
621 placeholders <- list(
622 list("%v", format(getRversion()[1, 1:2])),
623 list("%V", format(getRversion()[1, 1:3]))
624 )
625
626 for (placeholder in placeholders)
627 version <- gsub(placeholder[[1L]], placeholder[[2L]], version, fixed = TRUE)
628
629 # include SVN revision for development versions of R
630 # (to avoid sharing platform-specific artefacts with released versions of R)
631 devel <-
632 identical(R.version[["status"]], "Under development (unstable)") ||
633 identical(R.version[["nickname"]], "Unsuffered Consequences")
634
635 if (devel)
636 version <- paste(version, R.version[["svn rev"]], sep = "-r")
637
638 version
639
640 }
641
642 renv_bootstrap_platform_prefix <- function() {
643
644 # construct version prefix
645 version <- renv_bootstrap_platform_prefix_default()
646
647 # build list of path components
648 components <- c(version, R.version$platform)
649
650 # include prefix if provided by user
651 prefix <- renv_bootstrap_platform_prefix_impl()
652 if (!is.na(prefix) && nzchar(prefix))
653 components <- c(prefix, components)
654
655 # build prefix
656 paste(components, collapse = "/")
657
658 }
659
660 renv_bootstrap_platform_prefix_impl <- function() {
661
662 # if an explicit prefix has been supplied, use it
663 prefix <- Sys.getenv("RENV_PATHS_PREFIX", unset = NA)
664 if (!is.na(prefix))
665 return(prefix)
666
667 # if the user has requested an automatic prefix, generate it
668 auto <- Sys.getenv("RENV_PATHS_PREFIX_AUTO", unset = NA)
669 if (is.na(auto) && getRversion() >= "4.4.0")
670 auto <- "TRUE"
671
672 if (auto %in% c("TRUE", "True", "true", "1"))
673 return(renv_bootstrap_platform_prefix_auto())
674
675 # empty string on failure
676 ""
677
678 }
679
680 renv_bootstrap_platform_prefix_auto <- function() {
681
682 prefix <- tryCatch(renv_bootstrap_platform_os(), error = identity)
683 if (inherits(prefix, "error") || prefix %in% "unknown") {
684
685 msg <- paste(
686 "failed to infer current operating system",
687 "please file a bug report at https://github.com/rstudio/renv/issues",
688 sep = "; "
689 )
690
691 warning(msg)
692
693 }
694
695 prefix
696
697 }
698
699 renv_bootstrap_platform_os <- function() {
700
701 sysinfo <- Sys.info()
702 sysname <- sysinfo[["sysname"]]
703
704 # handle Windows + macOS up front
705 if (sysname == "Windows")
706 return("windows")
707 else if (sysname == "Darwin")
708 return("macos")
709
710 # check for os-release files
711 for (file in c("/etc/os-release", "/usr/lib/os-release"))
712 if (file.exists(file))
713 return(renv_bootstrap_platform_os_via_os_release(file, sysinfo))
714
715 # check for redhat-release files
716 if (file.exists("/etc/redhat-release"))
717 return(renv_bootstrap_platform_os_via_redhat_release())
718
719 "unknown"
720
721 }
722
723 renv_bootstrap_platform_os_via_os_release <- function(file, sysinfo) {
724
725 # read /etc/os-release
726 release <- utils::read.table(
727 file = file,
728 sep = "=",
729 quote = c("\"", "'"),
730 col.names = c("Key", "Value"),
731 comment.char = "#",
732 stringsAsFactors = FALSE
733 )
734
735 vars <- as.list(release$Value)
736 names(vars) <- release$Key
737
738 # get os name
739 os <- tolower(sysinfo[["sysname"]])
740
741 # read id
742 id <- "unknown"
743 for (field in c("ID", "ID_LIKE")) {
744 if (field %in% names(vars) && nzchar(vars[[field]])) {
745 id <- vars[[field]]
746 break
747 }
748 }
749
750 # read version
751 version <- "unknown"
752 for (field in c("UBUNTU_CODENAME", "VERSION_CODENAME", "VERSION_ID", "BUILD_ID")) {
753 if (field %in% names(vars) && nzchar(vars[[field]])) {
754 version <- vars[[field]]
755 break
756 }
757 }
758
759 # join together
760 paste(c(os, id, version), collapse = "-")
761
762 }
763
764 renv_bootstrap_platform_os_via_redhat_release <- function() {
765
766 # read /etc/redhat-release
767 contents <- readLines("/etc/redhat-release", warn = FALSE)
768
769 # infer id
770 id <- if (grepl("centos", contents, ignore.case = TRUE))
771 "centos"
772 else if (grepl("redhat", contents, ignore.case = TRUE))
773 "redhat"
774 else
775 "unknown"
776
777 # try to find a version component (very hacky)
778 version <- "unknown"
779
780 parts <- strsplit(contents, "[[:space:]]")[[1L]]
781 for (part in parts) {
782
783 nv <- tryCatch(numeric_version(part), error = identity)
784 if (inherits(nv, "error"))
785 next
786
787 version <- nv[1, 1]
788 break
789
790 }
791
792 paste(c("linux", id, version), collapse = "-")
793
794 }
795
796 renv_bootstrap_library_root_name <- function(project) {
797
798 # use project name as-is if requested
799 asis <- Sys.getenv("RENV_PATHS_LIBRARY_ROOT_ASIS", unset = "FALSE")
800 if (asis)
801 return(basename(project))
802
803 # otherwise, disambiguate based on project's path
804 id <- substring(renv_bootstrap_hash_text(project), 1L, 8L)
805 paste(basename(project), id, sep = "-")
806
807 }
808
809 renv_bootstrap_library_root <- function(project) {
810
811 prefix <- renv_bootstrap_profile_prefix()
812
813 path <- Sys.getenv("RENV_PATHS_LIBRARY", unset = NA)
814 if (!is.na(path))
815 return(paste(c(path, prefix), collapse = "/"))
816
817 path <- renv_bootstrap_library_root_impl(project)
818 if (!is.null(path)) {
819 name <- renv_bootstrap_library_root_name(project)
820 return(paste(c(path, prefix, name), collapse = "/"))
821 }
822
823 renv_bootstrap_paths_renv("library", project = project)
824
825 }
826
827 renv_bootstrap_library_root_impl <- function(project) {
828
829 root <- Sys.getenv("RENV_PATHS_LIBRARY_ROOT", unset = NA)
830 if (!is.na(root))
831 return(root)
832
833 type <- renv_bootstrap_project_type(project)
834 if (identical(type, "package")) {
835 userdir <- renv_bootstrap_user_dir()
836 return(file.path(userdir, "library"))
837 }
838
839 }
840
841 renv_bootstrap_validate_version <- function(version, description = NULL) {
842
843 # resolve description file
844 #
845 # avoid passing lib.loc to `packageDescription()` below, since R will
846 # use the loaded version of the package by default anyhow. note that
847 # this function should only be called after 'renv' is loaded
848 # https://github.com/rstudio/renv/issues/1625
849 description <- description %||% packageDescription("renv")
850
851 # check whether requested version 'version' matches loaded version of renv
852 sha <- attr(version, "sha", exact = TRUE)
853 valid <- if (!is.null(sha))
854 renv_bootstrap_validate_version_dev(sha, description)
855 else
856 renv_bootstrap_validate_version_release(version, description)
857
858 if (valid)
859 return(TRUE)
860
861 # the loaded version of renv doesn't match the requested version;
862 # give the user instructions on how to proceed
863 dev <- identical(description[["RemoteType"]], "github")
864 remote <- if (dev)
865 paste("rstudio/renv", description[["RemoteSha"]], sep = "@")
866 else
867 paste("renv", description[["Version"]], sep = "@")
868
869 # display both loaded version + sha if available
870 friendly <- renv_bootstrap_version_friendly(
871 version = description[["Version"]],
872 sha = if (dev) description[["RemoteSha"]]
873 )
874
875 fmt <- heredoc("
876 renv %1$s was loaded from project library, but this project is configured to use renv %2$s.
877 - Use `renv::record(\"%3$s\")` to record renv %1$s in the lockfile.
878 - Use `renv::restore(packages = \"renv\")` to install renv %2$s into the project library.
879 ")
880 catf(fmt, friendly, renv_bootstrap_version_friendly(version), remote)
881
882 FALSE
883
884 }
885
886 renv_bootstrap_validate_version_dev <- function(version, description) {
887
888 expected <- description[["RemoteSha"]]
889 if (!is.character(expected))
890 return(FALSE)
891
892 pattern <- sprintf("^\\Q%s\\E", version)
893 grepl(pattern, expected, perl = TRUE)
894
895 }
896
897 renv_bootstrap_validate_version_release <- function(version, description) {
898 expected <- description[["Version"]]
899 is.character(expected) && identical(c(expected), c(version))
900 }
901
902 renv_bootstrap_hash_text <- function(text) {
903
904 hashfile <- tempfile("renv-hash-")
905 on.exit(unlink(hashfile), add = TRUE)
906
907 writeLines(text, con = hashfile)
908 tools::md5sum(hashfile)
909
910 }
911
912 renv_bootstrap_load <- function(project, libpath, version) {
913
914 # try to load renv from the project library
915 if (!requireNamespace("renv", lib.loc = libpath, quietly = TRUE))
916 return(FALSE)
917
918 # warn if the version of renv loaded does not match
919 renv_bootstrap_validate_version(version)
920
921 # execute renv load hooks, if any
922 hooks <- getHook("renv::autoload")
923 for (hook in hooks)
924 if (is.function(hook))
925 tryCatch(hook(), error = warnify)
926
927 # load the project
928 renv::load(project)
929
930 TRUE
931
932 }
933
934 renv_bootstrap_profile_load <- function(project) {
935
936 # if RENV_PROFILE is already set, just use that
937 profile <- Sys.getenv("RENV_PROFILE", unset = NA)
938 if (!is.na(profile) && nzchar(profile))
939 return(profile)
940
941 # check for a profile file (nothing to do if it doesn't exist)
942 path <- renv_bootstrap_paths_renv("profile", profile = FALSE, project = project)
943 if (!file.exists(path))
944 return(NULL)
945
946 # read the profile, and set it if it exists
947 contents <- readLines(path, warn = FALSE)
948 if (length(contents) == 0L)
949 return(NULL)
950
951 # set RENV_PROFILE
952 profile <- contents[[1L]]
953 if (!profile %in% c("", "default"))
954 Sys.setenv(RENV_PROFILE = profile)
955
956 profile
957
958 }
959
960 renv_bootstrap_profile_prefix <- function() {
961 profile <- renv_bootstrap_profile_get()
962 if (!is.null(profile))
963 return(file.path("profiles", profile, "renv"))
964 }
965
966 renv_bootstrap_profile_get <- function() {
967 profile <- Sys.getenv("RENV_PROFILE", unset = "")
968 renv_bootstrap_profile_normalize(profile)
969 }
970
971 renv_bootstrap_profile_set <- function(profile) {
972 profile <- renv_bootstrap_profile_normalize(profile)
973 if (is.null(profile))
974 Sys.unsetenv("RENV_PROFILE")
975 else
976 Sys.setenv(RENV_PROFILE = profile)
977 }
978
979 renv_bootstrap_profile_normalize <- function(profile) {
980
981 if (is.null(profile) || profile %in% c("", "default"))
982 return(NULL)
983
984 profile
985
986 }
987
988 renv_bootstrap_path_absolute <- function(path) {
989
990 substr(path, 1L, 1L) %in% c("~", "/", "\\") || (
991 substr(path, 1L, 1L) %in% c(letters, LETTERS) &&
992 substr(path, 2L, 3L) %in% c(":/", ":\\")
993 )
994
995 }
996
997 renv_bootstrap_paths_renv <- function(..., profile = TRUE, project = NULL) {
998 renv <- Sys.getenv("RENV_PATHS_RENV", unset = "renv")
999 root <- if (renv_bootstrap_path_absolute(renv)) NULL else project
1000 prefix <- if (profile) renv_bootstrap_profile_prefix()
1001 components <- c(root, renv, prefix, ...)
1002 paste(components, collapse = "/")
1003 }
1004
1005 renv_bootstrap_project_type <- function(path) {
1006
1007 descpath <- file.path(path, "DESCRIPTION")
1008 if (!file.exists(descpath))
1009 return("unknown")
1010
1011 desc <- tryCatch(
1012 read.dcf(descpath, all = TRUE),
1013 error = identity
1014 )
1015
1016 if (inherits(desc, "error"))
1017 return("unknown")
1018
1019 type <- desc$Type
1020 if (!is.null(type))
1021 return(tolower(type))
1022
1023 package <- desc$Package
1024 if (!is.null(package))
1025 return("package")
1026
1027 "unknown"
1028
1029 }
1030
1031 renv_bootstrap_user_dir <- function() {
1032 dir <- renv_bootstrap_user_dir_impl()
1033 path.expand(chartr("\\", "/", dir))
1034 }
1035
1036 renv_bootstrap_user_dir_impl <- function() {
1037
1038 # use local override if set
1039 override <- getOption("renv.userdir.override")
1040 if (!is.null(override))
1041 return(override)
1042
1043 # use R_user_dir if available
1044 tools <- asNamespace("tools")
1045 if (is.function(tools$R_user_dir))
1046 return(tools$R_user_dir("renv", "cache"))
1047
1048 # try using our own backfill for older versions of R
1049 envvars <- c("R_USER_CACHE_DIR", "XDG_CACHE_HOME")
1050 for (envvar in envvars) {
1051 root <- Sys.getenv(envvar, unset = NA)
1052 if (!is.na(root))
1053 return(file.path(root, "R/renv"))
1054 }
1055
1056 # use platform-specific default fallbacks
1057 if (Sys.info()[["sysname"]] == "Windows")
1058 file.path(Sys.getenv("LOCALAPPDATA"), "R/cache/R/renv")
1059 else if (Sys.info()[["sysname"]] == "Darwin")
1060 "~/Library/Caches/org.R-project.R/R/renv"
1061 else
1062 "~/.cache/R/renv"
1063
1064 }
1065
1066 renv_bootstrap_version_friendly <- function(version, shafmt = NULL, sha = NULL) {
1067 sha <- sha %||% attr(version, "sha", exact = TRUE)
1068 parts <- c(version, sprintf(shafmt %||% " [sha: %s]", substring(sha, 1L, 7L)))
1069 paste(parts, collapse = "")
1070 }
1071
1072 renv_bootstrap_exec <- function(project, libpath, version) {
1073 if (!renv_bootstrap_load(project, libpath, version))
1074 renv_bootstrap_run(project, libpath, version)
1075 }
1076
1077 renv_bootstrap_run <- function(project, libpath, version) {
1078 tryCatch(
1079 renv_bootstrap_run_impl(project, libpath, version),
1080 error = function(e) {
1081 msg <- paste(
1082 "failed to bootstrap renv: the project will not be loaded.",
1083 paste("Reason:", conditionMessage(e)),
1084 "Use `renv::activate()` to re-initialize the project.",
1085 sep = "\n"
1086 )
1087 warning(msg, call. = FALSE)
1088 }
1089 )
1090 }
1091
1092 renv_bootstrap_run_impl <- function(project, libpath, version) {
1093
1094 # perform bootstrap
1095 bootstrap(version, libpath)
1096
1097 # exit early if we're just testing bootstrap
1098 if (!is.na(Sys.getenv("RENV_BOOTSTRAP_INSTALL_ONLY", unset = NA)))
1099 return(TRUE)
1100
1101 # try again to load
1102 if (requireNamespace("renv", lib.loc = libpath, quietly = TRUE)) {
1103 return(renv::load(project = project))
1104 }
1105
1106 # failed to download or load renv; warn the user
1107 msg <- c(
1108 "Failed to find an renv installation: the project will not be loaded.",
1109 "Use `renv::activate()` to re-initialize the project."
1110 )
1111
1112 warning(paste(msg, collapse = "\n"), call. = FALSE)
1113
1114 }
1115
1116 renv_bootstrap_cache_version <- function() {
1117 # NOTE: users should normally not override the cache version;
1118 # this is provided just to make testing easier
1119 Sys.getenv("RENV_CACHE_VERSION", unset = "v5")
1120 }
1121
1122 renv_bootstrap_cache_version_previous <- function() {
1123 version <- renv_bootstrap_cache_version()
1124 number <- as.integer(substring(version, 2L))
1125 paste("v", number - 1L, sep = "")
1126 }