Debian Codegraph @

R/hydrate.R

raw
1
2 #' Copy packages from user libraries to a project library
3 #'
4 #' @description
5 #' `hydrate()` installs missing packages from a user library into the project
6 #' library. `hydrate()` is called automatically by [init()], and it is rare
7 #' that you should need it otherwise, as it can easily get your project into
8 #' an inconsistent state.
9 #'
10 #' It may very occasionally be useful to call `hydrate(update = "all")` if you
11 #' want to update project packages to match those installed in your global
12 #' library (as opposed to using [update()] which will get the latest versions
13 #' from CRAN). In this case, you should verify that your code continues to work,
14 #' then call [snapshot()] to record updated package versions in the lockfile.
15 #'
16 #' @inherit renv-params
17 #'
18 #' @param packages The set of \R packages to install. When `NULL`, the
19 #' packages found by [dependencies()] are used.
20 #'
21 #' @param library The \R library to be hydrated. When `NULL`, the active
22 #' library as reported by `.libPaths()` is used.
23 #'
24 #' @param repos The \R repositories to be used. If the project depends on any
25 #' \R packages which cannot be found within the user library paths, then
26 #' those packages will be installed from these repositories instead.
27 #'
28 #' @param update Boolean; should `hydrate()` attempt to update already-installed
29 #' packages if the requested package is already installed in the project
30 #' library? Set this to `"all"` if you'd like _all_ packages to be refreshed
31 #' from the source library if possible.
32 #'
33 #' @param sources A vector of library paths where renv should look for packages.
34 #' When `NULL` (the default), `hydrate()` will look in the system libraries
35 #' (the user library, the site library and the default library) then the
36 #' renv cache.
37 #'
38 #' If a package is not found in any of these locations, `hydrate()`
39 #' will try to install it from the active R repositories.
40 #'
41 #' @param prompt Boolean; prompt the user before taking any action? Ignored
42 #' when `report = FALSE`.
43 #'
44 #' @param report Boolean; display a report of what packages will be installed
45 #' by `renv::hydrate()`?
46 #'
47 #' @return A named \R list, giving the packages that were used for hydration
48 #' as well as the set of packages which were not found.
49 #'
50 #' @export
51 #'
52 #' @keywords internal
53 #'
54 #' @examples
55 #' \dontrun{
56 #'
57 #' # hydrate the active library
58 #' renv::hydrate()
59 #'
60 #' }
61 hydrate <- function(packages = NULL,
62 ...,
63 library = NULL,
64 repos = getOption("repos"),
65 update = FALSE,
66 sources = NULL,
67 prompt = interactive(),
68 report = TRUE,
69 project = NULL)
70 {
71 renv_scope_error_handler()
72 renv_dots_check(...)
73
74 project <- renv_project_resolve(project)
75 renv_project_lock(project = project)
76 renv_scope_verbose_if(prompt)
77
78 renv_activate_prompt("hydrate", library, prompt, project)
79
80 renv_scope_options(repos = repos)
81 library <- renv_path_normalize(library %||% renv_libpaths_active())
82 packages <- packages %||% renv_hydrate_packages(project)
83
84 # find packages used in this project, and the dependencies of those packages
85 deps <- renv_hydrate_dependencies(project, packages, sources)
86
87 # remove 'renv' since it's managed separately
88 deps$renv <- NULL
89
90 # figure out required packages which aren't installed
91 missing <- deps[!nzchar(deps)]
92
93 # also consider remotes; if a package is listed within Remotes,
94 # then choose to install that package instead of linking it
95 filter <- function(specs, remotes) {
96
97 packages <- enum_chr(remotes, function(package, remote) {
98
99 # if we have a package name, use it
100 if (is.character(package) && nzchar(package))
101 return(package)
102
103 # otherwise, resolve the remote and use the package field
104 remote <- resolve(remote)
105 remote[["Package"]]
106
107 })
108
109 keep(specs, packages)
110
111 }
112
113 remotes <- renv_project_remotes(project, filter = filter, resolve = TRUE)
114 missing[map_chr(remotes, `[[`, "Package")] <- ""
115
116 # remove base + missing packages
117 base <- renv_packages_base()
118 packages <- deps[renv_vector_diff(names(deps), c(names(missing), base))]
119
120 # figure out if we will copy or link
121 linkable <- renv_cache_linkable(project = project, library = library)
122
123 # get and construct path to library
124 ensure_directory(library)
125
126 # only hydrate with packages that are either not currently installed,
127 # or (if update = TRUE) the version in the library is newer
128 packages <- renv_hydrate_filter(packages, library, update)
129
130 # inform user about changes
131 if (report) {
132 renv_hydrate_report(packages, missing, linkable)
133 if (length(packages) || length(missing))
134 cancel_if(prompt && !proceed())
135 }
136
137 # check for nothing to be done
138 if (empty(packages) && empty(missing)) {
139 if (report)
140 writef("- No new packages were discovered in this project; nothing to do.")
141 return(invisible(list(packages = list(), missing = list())))
142 }
143
144 # copy packages from user library to cache
145 before <- Sys.time()
146 if (length(packages)) {
147 if (linkable)
148 renv_hydrate_link_packages(packages, library, project)
149 else
150 renv_hydrate_copy_packages(packages, library, project)
151 }
152 after <- Sys.time()
153
154 if (report) {
155 time <- difftime(after, before, units = "auto")
156 fmt <- "- Hydrated %s packages in %s."
157 writef(fmt, length(packages), renv_difftime_format(time))
158 }
159
160 # attempt to install missing packages (if any)
161 missing <- renv_hydrate_resolve_missing(project, library, remotes, missing)
162
163 # we're done!
164 result <- list(packages = packages, missing = missing)
165 invisible(result)
166 }
167
168 renv_hydrate_filter <- function(packages, library, update) {
169
170 # run filter
171 keep <- enumerate(packages, function(package, path) {
172 renv_hydrate_filter_impl(package, path, library, update)
173 })
174
175 # filter based on kept packages
176 packages[as.logical(keep)]
177
178 }
179
180 renv_hydrate_filter_impl <- function(package, path, library, update) {
181
182 # if user has requested hydration of all packages, respect that
183 if (identical(update, "all"))
184 return(TRUE)
185
186 # is the package already installed in the requested library?
187 # if not, then we'll want to hydrate this package
188 # if so, we'll want to compare the version first and
189 # hydrate only if the requested version is newer than the current
190 descpath <- file.path(library, package, "DESCRIPTION")
191 if (file.exists(descpath)) {
192 desc <- catch(renv_description_read(path = descpath))
193 if (inherits(desc, "error"))
194 return(TRUE)
195 }
196
197 # get the current package version
198 current <- catch(numeric_version(desc[["Version"]]))
199 if (inherits(current, "error"))
200 return(TRUE)
201
202 # if the package is already installed and we're not updating, stop here
203 if (identical(update, FALSE))
204 return(FALSE)
205
206 # check to-be-copied package version
207 requested <- catch({
208 desc <- renv_description_read(path = path)
209 numeric_version(desc[["Version"]])
210 })
211
212 # only hydrate with a newer version
213 requested > current
214
215 }
216
217 renv_hydrate_packages <- function(project) {
218 renv_snapshot_dependencies(project, dev = TRUE)
219 }
220
221 renv_hydrate_dependencies <- function(project,
222 packages = NULL,
223 libpaths = NULL)
224 {
225 ignored <- renv_project_ignored_packages(project = project)
226 packages <- renv_vector_diff(packages, ignored)
227 libpaths <- libpaths %||% renv_hydrate_libpaths()
228 renv_package_dependencies(packages, libpaths = libpaths, project = project)
229 }
230
231 # NOTE: we don't want to look in user / site libraries when testing
232 # on CRAN, as we may accidentally find versions of packages available
233 # on CRAN but not that we want to use during tests
234 renv_hydrate_libpaths <- function() {
235
236 conf <- config$hydrate.libpaths()
237 if (is.character(conf) && length(conf))
238 conf <- unlist(strsplit(conf, ":", fixed = TRUE))
239
240 libpaths <- case(
241 renv_tests_running() ~ character(),
242 length(conf) ~ conf,
243 ~ c(
244 renv_libpaths_default(),
245 renv_libpaths_user(),
246 renv_libpaths_site(),
247 renv_libpaths_system()
248 )
249 )
250
251 libpaths <- .expand_R_libs_env_var(libpaths)
252 unique(renv_path_normalize(libpaths))
253
254 }
255
256 # takes a package called 'package' installed at location 'location',
257 # copies that package into the cache, and then links from the cache
258 # to the (private) library 'library'
259 renv_hydrate_link_package <- function(package, location, library) {
260
261 # compute package record
262 record <- catch(renv_snapshot_description(location))
263 if (inherits(record, "error"))
264 return(FALSE)
265
266 # compute a hash now if we don't have one
267 record[["Hash"]] <- record[["Hash"]] %||% renv_hash_description(location)
268
269 # construct path to cache
270 cache <- renv_cache_find(record)
271 if (!nzchar(cache))
272 return(FALSE)
273
274 # copy package into the cache
275 if (!file.exists(cache)) {
276 ensure_parent_directory(cache)
277 renv_file_copy(location, cache)
278 }
279
280 # invoke cache callbacks
281 renv_cache_callbacks(cache)
282
283 # link package back from cache to library
284 target <- file.path(library, package)
285 ensure_parent_directory(target)
286 renv_file_link(cache, target, overwrite = TRUE)
287
288 }
289
290 renv_hydrate_link_packages <- function(packages, library, project) {
291
292 if (renv_path_same(library, renv_paths_library(project = project)))
293 printf("- Linking packages into the project library ... ")
294 else
295 printf("- Linking packages into %s ... ", renv_path_pretty(library))
296
297 callback <- renv_progress_callback(renv_hydrate_link_package, length(packages))
298 cached <- enumerate(packages, callback, library = library)
299 writef("Done!")
300 cached
301
302 }
303
304 # takes a package called 'package' installed at location 'location',
305 # and copies it to the library 'library'
306 renv_hydrate_copy_package <- function(package, location, library) {
307 target <- file.path(library, package)
308 renv_file_copy(location, target, overwrite = TRUE)
309 }
310
311 renv_hydrate_copy_packages <- function(packages, library, project) {
312
313 if (renv_path_same(library, renv_paths_library(project = project)))
314 printf("- Copying packages into the project library ... ")
315 else
316 printf("- Copying packages into %s ... ", renv_path_pretty(library))
317
318 callback <- renv_progress_callback(renv_hydrate_copy_package, length(packages))
319 copied <- enumerate(packages, callback, library = library)
320 writef("Done!")
321 copied
322 }
323
324 renv_hydrate_resolve_missing <- function(project, library, remotes, missing) {
325
326 # make sure requested library is made active
327 #
328 # note that we only want to place the requested library on the library path;
329 # we want to ensure that all required packages are hydrated into the
330 # requested library
331 #
332 # https://github.com/rstudio/renv/issues/1177
333 ensure_directory(library)
334 renv_scope_libpaths(library)
335
336 packages <- names(missing)
337 if (empty(packages))
338 return()
339
340 writef("- Resolving missing dependencies ... ")
341
342 # if pak is enabled, delegate installation to it
343 # https://github.com/rstudio/renv/issues/2282
344 if (config$pak.enabled() && !recursing()) {
345 renv_pak_init()
346 specs <- map_chr(packages, function(package) {
347 record <- remotes[[package]]
348 if (is.null(record))
349 package
350 else
351 renv_record_format_remote(record, pak = TRUE)
352 })
353 renv_pak_install(
354 packages = unname(specs),
355 library = library,
356 type = NULL,
357 rebuild = FALSE,
358 prompt = FALSE,
359 project = project
360 )
361 return(invisible())
362 }
363
364 # set up restore state for graph resolution
365 renv_scope_restore(
366 project = project,
367 library = library,
368 packages = packages,
369 records = remotes
370 )
371
372 # resolve dependency graph and install in parallel waves;
373 # renv_graph_install handles error reporting internally
374 descriptions <- renv_graph_init(packages, records = remotes, project = project)
375 if (empty(descriptions))
376 return()
377
378 records <- renv_graph_install(descriptions)
379
380 # determine which requested packages failed to install
381 failed <- setdiff(packages, names(records))
382 if (empty(failed))
383 return()
384
385 data <- lapply(failed, function(pkg) {
386 list(package = pkg, error = simpleError(sprintf("failed to install '%s'", pkg)))
387 })
388
389 invisible(data)
390
391 }
392
393 renv_hydrate_report <- function(packages, na, linkable) {
394
395 if (renv_bootstrap_tests_running())
396 return()
397
398 if (length(packages)) {
399
400 # this is mostly a hacky way to get a list of records that the existing
401 # record pretty-printer can handle in a clean way
402 records <- enumerate(packages, function(package, library) {
403 descpath <- file.path(library, "DESCRIPTION")
404 record <- renv_snapshot_description(descpath)
405 record$Repository <- NULL
406 record$Source <- renv_path_aliased(dirname(library))
407 record
408 })
409
410 preamble <- "The following packages were discovered:"
411 postamble <- sprintf(
412 "They will be %s into the project library.",
413 if (linkable) "linked" else "copied"
414 )
415
416 formatter <- function(lhs, rhs) {
417 renv_record_format_short(rhs, versioned = TRUE)
418 }
419
420 renv_pretty_print_records_pair(
421 preamble = preamble,
422 old = list(),
423 new = records,
424 postamble = postamble,
425 formatter = formatter
426 )
427
428 }
429
430 if (length(na)) {
431 bulletin(
432 "The following packages are used in this project, but not available locally:",
433 csort(names(na)),
434 "renv will attempt to download and install these packages."
435 )
436 }
437
438 }