rcran

Is a robust and OS agnostic function to download tar.gz archives from CRAN implemented somewhere?


I have done some searching but I can't find anything that will do the job "out-of-the-box". The majority of threads revolves around installing but I'm interested in downloading. I have written my own small utility (see below), but I'm interesed in something more OS agnostic, which is likely also more robust and does not require personal maintenance.

Have I overlooked something or does this simply not exists?

Function:

get_pack_tar_gz <- function(package, version, destination = ".") {
  package_tar_gz_string <- paste0(package, "_", version, ".tar.gz")
  latest_version_url <- paste0("https://cran.r-project.org/src/contrib/",
                               package_tar_gz_string)
  archive_version_url <- paste0("https://cran.r-project.org/src/contrib/Archive/",
                                package,
                                "/",
                                package_tar_gz_string)
  
  latest_return <- suppressWarnings(
    system(paste0("wget --spider ", latest_version_url, " 2> /dev/null"), intern = TRUE)
  )
  latest_return_status <- attributes(latest_return)$status
  
  if(length(latest_return_status) == 0) {
    system(paste0("wget -q https://cran.r-project.org/src/contrib/",
                  package_tar_gz_string,
                  " -P ",
                  destination))
  } else if(latest_return_status == 8) {
    system(paste0("wget -q https://cran.r-project.org/src/contrib/Archive/",
                  package,
                  "/",
                  package_tar_gz_string, 
                  " -P ",
                  destination))
  } else {
    stop("Unexpected!")
  }
  if(! file.exists(paste0(destination, "/", package_tar_gz_string))) {
    stop("No file retrieved!")
  }
}

Example calls:

get_pack_tar_gz(package = "tidyr", version = "1.3.1")
get_pack_tar_gz(package = "tidyr", version = "0.1")

Solution

  • Based on the comment from MrFlick we can rewrite a download call for several packages more concisely as follows:

    # example data
    packs_to_dl <- structure(list(name = c("fastmap", "r2r", "urca"),
                                  version = c("1.1.0", "0.1.1", "1.3-3"),
                                  out_file = c("fastmap_1.1.0.tar.gz",
                                               "r2r_0.1.1.tar.gz",
                                               "urca_1.3-3.tar.gz")),
                             row.names = c(1L, 2L, 3L),
                             class = "data.frame")
    
    # download
    download.file(unlist(purrr::pmap(list(packs_to_dl$name,
                                          packs_to_dl$version,
                                          "https://cran.r-project.org",
                                          "source"),
                                     remotes:::download_version_url)),
                  destfile = packs_to_dl$out_file)