Skip to content

Commit

Permalink
Throw error if libdir is not empty but selfcontained = TRUE
Browse files Browse the repository at this point in the history
Fixes #417 and saves users from accidentally deleting important files by throwing an error when the user provides a `libdir` that contains files. This is only an issue when `selfcontained = TRUE` because otherwise the files written into `libdir` are not removed after saving the widget html.
  • Loading branch information
gadenbuie committed May 1, 2023
1 parent e234c0e commit 1c021b8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
15 changes: 14 additions & 1 deletion R/savewidget.R
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
#' (with external resources base64 encoded) or a file with external resources
#' placed in an adjacent directory.
#' @param libdir Directory to copy HTML dependencies into (defaults to
#' filename_files).
#' filename_files). When `selfcontained = TRUE`, this directory must be empty
#' or not exist, in which case it will be created temporarily and removed
#' when the widget is saved.
#' @param background Text string giving the html background color of the widget.
#' Defaults to white.
#' @param title Text to use as the title of the generated page.
Expand All @@ -18,6 +20,17 @@ saveWidget <- function(widget, file, selfcontained = TRUE, libdir = NULL,
background = "white", title = class(widget)[[1]],
knitrOptions = list()) {

if (selfcontained && !is.null(libdir) && file_test("-d", libdir)) {
libdir_files <- setdiff(dir(libdir, all.files = TRUE), c(".", ".."))
if (length(libdir_files) > 0) {
stop(
"`selfcontained = TRUE` but the `libdir` directory exists and contains files. ",
"When `selfcontained = TRUE`, the `libdir` directory is used ",
"temporarily and then deleted when the widget is saved."
)
}
}

# Transform #RRGGBB/#RRGGBBAA colors to rgba(r,g,b,a) form, because the
# pound sign interferes with pandoc processing
if (grepl("^#", background, perl = TRUE)) {
Expand Down
19 changes: 19 additions & 0 deletions tests/testthat/test-savewidget.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
test_that("saveWidget errors if `selfcontained = TRUE` and `libdir` is not empty", {
tmpdir <- tempfile()
dir.create(tmpdir)
on.exit(unlink(tmpdir, recursive = TRUE), add = TRUE)

owd <- setwd(tmpdir)
on.exit(setwd(owd), add = TRUE)

# widget
widget <- widget_html("widgetE", "htmlwidgets", id = "id", style = NULL, class = NULL)

# Create a libdir with something in it
dir.create("libdir")
writeLines("not empty", file.path("libdir", "not-empty.txt"))

expect_error(
saveWidget(widget, "widget.html", selfcontained = TRUE, libdir = "libdir")
)
})

0 comments on commit 1c021b8

Please sign in to comment.