Given a set of R packages I would like to find out which ones come hierarchically first in a dependency graph.
Context:
The motivation behind this comes from wanting to create a system setup (via Docker) in which I can manually specify all packages and their versions and install (via remotes::install_version
package) them with dependencies=FALSE
and upgrade='never'
so that I actually get what I request. This will only work if everything is installed in the right order.
I am answering with my own solution but I'm also interested in other ones that may be better.
Use tools::package_dependencies()
to retrieve all dependencies and then iteratively construct the hierarchy.
# packages of interest
packages <- c("haven", "tibble", "rlang", "hms", "vctrs")
dependencies <- tools::package_dependencies(packages, db = available.packages())
hierarchy <- c()
c <- 0
while(length(dependencies) > 0) {
all_package_names <- names(dependencies)
c <- c + 1
# show current iteration
print(c)
for(i in 1:length(dependencies)) {
curr_pack <- names(dependencies[i])
curr_deps <- dependencies[[i]]
if(! any(curr_deps %in% all_package_names)) {
hierarchy <- c(hierarchy, curr_pack)
}
}
dependencies[hierarchy] <- NULL
}
hierarchy