Skip to content

Commit

Permalink
Correctly avoid writing to the input file when there are no preserved…
Browse files Browse the repository at this point in the history
… HTML chunks (#2535)

Co-authored-by: Yihui Xie <[email protected]>
Co-authored-by: Jiří Moravec <[email protected]>
  • Loading branch information
yihui and J-Moravec committed Jan 18, 2024
1 parent 65916c3 commit 07e2a99
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 2 deletions.
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Type: Package
Package: rmarkdown
Title: Dynamic Documents for R
Version: 2.25.2
Version: 2.25.3
Authors@R: c(
person("JJ", "Allaire", , "[email protected]", role = "aut"),
person("Yihui", "Xie", , "[email protected]", role = c("aut", "cre"), comment = c(ORCID = "0000-0003-0645-5666")),
Expand Down
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ rmarkdown 2.26

- For the output format option `fig_crop: auto`, it will now use the same logic as in **knitr** to decide if cropping is possible (yihui/knitr#2246).

- Avoid corrupting input files by accident (thanks, @J-Moravec, #2534).


rmarkdown 2.25
================================================================================
Expand Down
7 changes: 6 additions & 1 deletion R/html_document_base.R
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,12 @@ html_document_base <- function(theme = NULL,
}

extract_preserve_chunks <- function(input_file, extract = extractPreserveChunks) {
input_str <- read_utf8(input_file)
# Don't try to modify the input file if it's not .md, otherwise the original
# input could be corrupted (#2534). In theory, preserved chunks should only
# exist in the intermediate .md file from knit(). If the .md file is not
# intermediate but original, this processing should be harmless.
if (!xfun::file_ext(input_file) %in% c('md', 'markdown')) return()
input_str <- one_string(read_utf8(input_file))
preserve <- extract(input_str)
if (!identical(preserve$value, input_str)) write_utf8(preserve$value, input_file)
preserve$chunks
Expand Down
9 changes: 9 additions & 0 deletions tests/testthat/test-render.R
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,12 @@ test_that("file_scope split correctly input file", {
expect_snapshot_file(splitted[1])
expect_snapshot_file(splitted[2])
})

test_that("Input file is not corrupted", {
input <- tempfile()
on.exit(unlink(input), add = TRUE, after = FALSE)
saveRDS("test", input)
# try() is necessary for Pandoc <= 2.14.2
try(render(input, quiet = TRUE))
expect_equal(readRDS(input), "test")
})

0 comments on commit 07e2a99

Please sign in to comment.