diff --git a/NEWS.md b/NEWS.md index e4e079c..394a59a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,12 @@ # rsi (development version) +* `stack_rasters()` will only rename bands if `band_names` is the same length as + the number of bands in the output raster (or missing, or defined by a + function). It will now warn you if these lengths are different. Previously, if + you provided more than the required number of band names, `stack_rasters()` + would silently ignore the extra names, and would error if you provided fewer + names than bands. + # rsi 0.1.2 * `get_stac_data()` no longer includes `mask_band` in its outputs when diff --git a/R/stack_rasters.R b/R/stack_rasters.R index 2f0aa11..d25b0b4 100644 --- a/R/stack_rasters.R +++ b/R/stack_rasters.R @@ -180,6 +180,8 @@ stack_rasters <- function(rasters, if (!missing(band_names) && is.function(band_names)) { var_names <- band_names(var_names) } + # technically we could have skipped reading the names of each raster here + # and just accepted the band names, but we want to check the CRS anyway if (!missing(band_names) && is.character(band_names)) { var_names <- band_names } @@ -233,12 +235,26 @@ stack_rasters <- function(rasters, band_no <- 1 vrt_bands <- vector("list", length(intermediate_vrt)) + + set_names <- FALSE + if (length(intermediate_vrt) == length(var_names)) { + set_names <- TRUE + } else if (!missing(band_names)) { + rlang::warn( + c( + "The number of band names provided did not match the number of bands in the output file.", + i = "Ignoring the provided band names and using default values instead." + ), + class = "rsi_band_name_length_mismatch" + ) + } + for (vrt in intermediate_vrt) { vrt <- readLines(vrt) band_def <- grep("VRTRasterBand", vrt) vrt <- vrt[seq(band_def[[1]], band_def[[2]])] vrt[1] <- gsub("band=\"1\"", paste0("band=\"", band_no, "\""), vrt[1]) - if (length(intermediate_vrt) == length(var_names)) { + if (set_names) { vrt <- c( vrt[1], paste0(" ", var_names[[band_no]], ""), diff --git a/tests/testthat/test-stack_rasters.R b/tests/testthat/test-stack_rasters.R index b7502eb..75de787 100644 --- a/tests/testthat/test-stack_rasters.R +++ b/tests/testthat/test-stack_rasters.R @@ -143,3 +143,23 @@ test_that("type_and_length checks", { error = TRUE ) }) + +test_that("stack_rasters warns when band names aren't the right length", { + expect_warning( + stack_rasters( + list(system.file("rasters/example_sentinel1.tif", package = "rsi")), + tempfile(fileext = ".vrt"), + band_names = "VH" + ), + class = "rsi_band_name_length_mismatch" + ) + + expect_warning( + stack_rasters( + list(system.file("rasters/example_sentinel1.tif", package = "rsi")), + tempfile(fileext = ".vrt"), + band_names = c("VH", "VV", "EXTRA") + ), + class = "rsi_band_name_length_mismatch" + ) +})