Debian Codegraph @

R/manifest-convert.R

raw
1
2 #' Generate `renv.lock` from an Posit Connect `manifest.json`
3 #'
4 #' @description
5 #' Use `renv_lockfile_from_manifest()` to convert a `manifest.json` file from
6 #' an Posit Connect content bundle into an `renv.lock` lockfile.
7 #'
8 #' This function can be useful when you need to recreate the package environment
9 #' of a piece of content that is deployed to Posit Connect. The content bundle
10 #' contains a `manifest.json` file that is used to recreate the package
11 #' environment. This function will let you convert that manifest file to an
12 #' `renv.lock` file. Run `renv::restore()` after you've converted the file to
13 #' restore the package environment.
14 #'
15 #' @param manifest
16 #' The path to a `manifest.json` file.
17 #'
18 #' @param lockfile
19 #' The path to the lockfile to be generated and / or updated.
20 #' When `NA` (the default), the generated lockfile is returned as an \R
21 #' object; otherwise, the lockfile will be written to the path specified by
22 #' `lockfile`.
23 #'
24 #' @return
25 #' An renv lockfile.
26 #'
27 #' @keywords internal
28 renv_lockfile_from_manifest <- function(manifest = "manifest.json",
29 lockfile = NA,
30 project = NULL)
31 {
32 renv_scope_error_handler()
33 project <- renv_project_resolve(project)
34
35 # read the manifest (accept both lists and file paths)
36 manifest <- case(
37 is.character(manifest) ~ renv_json_read(manifest),
38 is.list(manifest) ~ manifest,
39 TRUE ~ renv_type_unexpected(manifest)
40 )
41
42 # convert descriptions into records
43 records <- map(manifest[["packages"]], function(entry) {
44 desc <- entry[["description"]]
45 renv_snapshot_description_impl(desc)
46 })
47
48 # extract repositories from descriptions
49 repos <- list()
50 for (entry in manifest[["packages"]]) {
51
52 if (is.null(entry[["Repository"]]))
53 next
54
55 src <- entry[["Source"]] %||% "CRAN"
56 repo <- entry[["Repository"]]
57
58 repos[[src]] <- repo
59
60 }
61
62 # extract version
63 version <- format(manifest[["platform"]] %||% getRversion())
64
65 # create R field for lockfile
66 r <- list(Version = version, Repositories = repos)
67
68 # create the lockfile
69 lock <- list(R = r, Packages = records)
70 class(lock) <- "renv_lockfile"
71
72 # return lockfile as R object if requested
73 if (is.na(lockfile))
74 return(lock)
75
76 # otherwise, write to file
77 renv_lockfile_write(lock, file = lockfile)
78
79 invisible(lock)
80
81 }