Make `getNamespaceVersion()` work with temporary packages created with `usethis::create_package()`

I wrote a package to cite other R packages. I use dummy packages created with usethis::create_package() for testing.

I'd like to use getNamespaceVersion() (rather than packageVersion()) to get package versions because it's faster, returns a character vector by default and is a bit cleaner in my opinion. The problem is that getNamespaceVersion() requires to have package metadata files to work, which is not the case of the fake packages I use.

local({
  local_pkg <- function(Package, ..., env = parent.frame()) {
    dir <- withr::local_tempdir(.local_envir = env)
    withr::local_libpaths(dir, action = "prefix", .local_envir = env)
    pkg_path <- file.path(dir, Package)
    usethis::ui_silence(
      usethis::create_package(
        path = pkg_path,
        fields = list(Type = "Package", Package = Package, ...),
        rstudio = FALSE,
        open = FALSE
      )
    )
  }
  
  local_pkg(
    "foo",
    Title = "Bar",
    `Authors@R` = utils::person("X", "Y", role = "aut"),
    Version = "1.0.0",
    Date = "2020-01-01"
  )
  
  getNamespaceVersion("foo")
})
#> <NA> 
#>   NA 
#> Warning message:
#> In loadNamespace(name) : package ‘foo’ has no 'package.rds' in Meta/

Is there an easy and efficient way to create or emulate the files needed to make getNamespaceVersion() work with such temporary packages?

getNamespaceVersion() only works if you install the package first. Alternatively, you can also load it with pkgload::load_all().

1 Like

Installing the package isn't fast enough but pkgload::load_all() works like a charm.

I may have talked a bit too soon. It works in all cases except when I render a .Rmd document in a callr subprocess, in which case it returns NA again.

Here's how I implemented load_all():

local_pkg <- function(Package, ..., env = parent.frame()) {
  dir <- withr::local_tempdir(.local_envir = env)
  withr::local_libpaths(dir, action = "prefix", .local_envir = env)
  pkg_path <- file.path(dir, Package)
  usethis::ui_silence(
    usethis::create_package(
      path = pkg_path,
      fields = list(Type = "Package", Package = Package, ...),
      rstudio = FALSE,
      open = FALSE
    )
  )
  devtools::load_all(pkg_path, export_all = FALSE, quiet = TRUE)
}

I use callr:r() with the default arguments.

Here's a reproducible example using the code on this repo:

# devtools::load_all()
local({
  load_foo()
  dir <- local_files(make_template(lines = "`r pkrt(foo)`"))
  read_local_file(dir)
})

Again, you either need to install the package, or use pkgload::load_all(), this time in the callr subprocess.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.