Skip to content

Commit

Permalink
netCDF: honour BAND_NAMES creation option in CreateCopy()
Browse files Browse the repository at this point in the history
Fixes #10646
  • Loading branch information
rouault committed Aug 26, 2024
1 parent 35cc8c4 commit f8d85a4
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
26 changes: 26 additions & 0 deletions autotest/gdrivers/netcdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -6510,6 +6510,32 @@ def test_band_names_creation_option(tmp_path):
assert gdal.GetSubdatasetInfo(sds_names[1]).GetSubdatasetComponent() == "prate"


@gdaltest.enable_exceptions()
def test_band_names_creation_option_createcopy(tmp_path):

fname = tmp_path / "out.nc"

# 1 band, 2 names
with pytest.raises(Exception, match="but 2 names provided"):
src_ds = gdal.GetDriverByName("MEM").Create("", 1, 1)
gdal.GetDriverByName("NetCDF").CreateCopy(
fname, src_ds, options={"BAND_NAMES": "t2m,prate"}
)

# 2 bands, 2 names
src_ds = gdal.GetDriverByName("MEM").Create("", 1, 1, 2)
with gdal.GetDriverByName("NetCDF").CreateCopy(
fname, src_ds, options={"BAND_NAMES": "t2m,prate"}
):
pass

with gdal.Open(fname) as ds:
sds_names = [sds[0] for sds in ds.GetSubDatasets()]

assert gdal.GetSubdatasetInfo(sds_names[0]).GetSubdatasetComponent() == "t2m"
assert gdal.GetSubdatasetInfo(sds_names[1]).GetSubdatasetComponent() == "prate"


@gdaltest.enable_exceptions()
def test_netcdf_create_metadata_with_equal_sign(tmp_path):

Expand Down
25 changes: 24 additions & 1 deletion frmts/netcdf/netcdfdataset.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9483,6 +9483,24 @@ netCDFDataset::CreateCopy(const char *pszFilename, GDALDataset *poSrcDS,
}
}

CPLStringList aosBandNames;
if (const char *pszBandNames =
CSLFetchNameValue(papszOptions, "BAND_NAMES"))
{
aosBandNames =
CSLTokenizeString2(pszBandNames, ",", CSLT_HONOURSTRINGS);

if (aosBandNames.Count() != nBands)
{
CPLError(CE_Failure, CPLE_OpenFailed,
"Attempted to create netCDF with %d bands but %d names "
"provided in BAND_NAMES.",
nBands, aosBandNames.Count());

return nullptr;
}
}

if (!pfnProgress(0.0, nullptr, pProgressData))
return nullptr;

Expand Down Expand Up @@ -9692,7 +9710,12 @@ netCDFDataset::CreateCopy(const char *pszFilename, GDALDataset *poSrcDS,
const char *pszNETCDF_VARNAME =
poSrcBand->GetMetadataItem("NETCDF_VARNAME");
char szBandName[NC_MAX_NAME + 1];
if (pszNETCDF_VARNAME)
if (!aosBandNames.empty())
{
snprintf(szBandName, sizeof(szBandName), "%s",
aosBandNames[iBand - 1]);
}
else if (pszNETCDF_VARNAME)
{
if (nBands > 1 && papszExtraDimNames == nullptr)
snprintf(szBandName, sizeof(szBandName), "%s%d",
Expand Down

0 comments on commit f8d85a4

Please sign in to comment.