diff --git a/R/all-classes.R b/R/all-classes.R index 42409e655a..43a697a645 100644 --- a/R/all-classes.R +++ b/R/all-classes.R @@ -337,6 +337,7 @@ class_ggplot <- S7::new_class( layout = class_layout, labels = class_labels, meta = S7::class_list, + version = S7::new_S3_class("package_version"), plot_env = S7::class_environment ), constructor = function( @@ -368,6 +369,7 @@ class_ggplot <- S7::new_class( layout = layout %||% ggproto(NULL, Layout), labels = labels, meta = meta, + version = current_version, plot_env = plot_env ) } diff --git a/R/plot-build.R b/R/plot-build.R index 344fc8a13c..141ec5af70 100644 --- a/R/plot-build.R +++ b/R/plot-build.R @@ -31,6 +31,14 @@ ggplot_build <- function(plot, ...) { if (!is.null(env)) { attach_plot_env(env) } + if (!identical(try_prop(plot, "version"), current_version)) { + cli::cli_abort(c( + "The plot object was created with a different version of ggplot2. \\ + Please reconstruct the plot.", + i = "Did you save the plot object to disk?" + )) + } + UseMethod("ggplot_build") } diff --git a/R/zzz.R b/R/zzz.R index bc757f9ef6..593ff568f1 100644 --- a/R/zzz.R +++ b/R/zzz.R @@ -37,6 +37,9 @@ on_load( if (getRversion() >= "4.3.0") registerS3method("+", "gg", add_gg) ) +current_version <- NULL +on_load(current_version <- packageVersion("ggplot2")) + on_load(S7::methods_register()) .onLoad <- function(...) { run_on_load() diff --git a/tests/testthat/_snaps/plot-build.md b/tests/testthat/_snaps/plot-build.md new file mode 100644 index 0000000000..0453368bd9 --- /dev/null +++ b/tests/testthat/_snaps/plot-build.md @@ -0,0 +1,9 @@ +# attempting the render plot build with previous version fails + + Code + print(p) + Condition + Error in `ggplot_build()`: + ! The plot object was created with a different version of ggplot2. Please reconstruct the plot. + i Did you save the plot object to disk? + diff --git a/tests/testthat/test-plot-build.R b/tests/testthat/test-plot-build.R index cfb4cf6e4a..96ff987b33 100644 --- a/tests/testthat/test-plot-build.R +++ b/tests/testthat/test-plot-build.R @@ -52,3 +52,9 @@ test_that("strings are not converted to factors", { expect_type(get_layer_data(p)$label, "character") }) + +test_that("attempting the render plot build with previous version fails", { + p <- ggplot(mtcars, aes(disp, mpg)) + geom_point() + p@version <- package_version("3.5.2") + expect_snapshot(print(p), error = TRUE) +})