Skip to content

Commit

Permalink
infer knitr, rmarkdown dependency for R scripts with YAML front-matter
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinushey committed Nov 13, 2024
1 parent 809374d commit 7ec0ad8
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 1 deletion.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@

# renv 1.1.0 (UNRELEASED)

* `renv` now infers a dependency on `rmarkdown` and `knitr` for R scripts which
include YAML front-matter. (#2023)

* The performance of `renv`'s built-in JSON reader has been improved. (#2021)

* Fixed an issue where `renv` could erroneously create a binding called 'object'
Expand Down
13 changes: 12 additions & 1 deletion R/dependencies.R
Original file line number Diff line number Diff line change
Expand Up @@ -1100,8 +1100,19 @@ renv_dependencies_discover_r <- function(path = NULL,
}

renv_dependencies_recurse(expr, callback)

packages <- ls(envir = envir, all.names = TRUE)

# also try to detect knitr::spin() dependencies -- this needs to
# happen outside of the regular dependency discovery machinery
# as it will rely on checking comments in the document
#
# https://github.com/rstudio/renv/issues/2023
if (is.character(text) || is.character(path)) {
text <- text %||% readLines(path, n = 1L, warn = FALSE)
if (length(text) && grepl("^\\s*#'\\s*[-]{3}\\s*$", text[[1L]], perl = TRUE))
packages <- union(c("knitr", "rmarkdown"), packages)
}

renv_dependencies_list(path, packages, dev = dev)
}

Expand Down
8 changes: 8 additions & 0 deletions tests/testthat/resources/knitr-spin.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#' ---
#' title: Palmer Penguins
#' author: Norah Jones
#' date: 3/12/23
#' format: html
#' ---

print(42)
5 changes: 5 additions & 0 deletions tests/testthat/test-dependencies.R
Original file line number Diff line number Diff line change
Expand Up @@ -625,3 +625,8 @@ test_that("dependencies() does not create 'object' in parent environment", {
result <- dependencies("resources/code.R", quiet = TRUE)
expect_false(exists("object", envir = environment(), inherits = FALSE))
})

test_that("R scripts that appear destined for knitr::spin() are detected", {
result <- dependencies("resources/knitr-spin.R", quiet = TRUE)
expect_contains(result$Package, c("knitr", "rmarkdown"))
})

0 comments on commit 7ec0ad8

Please sign in to comment.