diff --git a/apps/rustgis-python/src/lib.rs b/apps/rustgis-python/src/lib.rs index 7ba4810486..4b15504169 100644 --- a/apps/rustgis-python/src/lib.rs +++ b/apps/rustgis-python/src/lib.rs @@ -221,10 +221,8 @@ impl Engine { .unwrap_or_default(); let (ds, report) = found.load_all_reported().map_err(|e| format!("{}: {e}", found.name))?; let name = found.name.clone(); - match report.skipped { - 0 => {} - 1 => session.warn(format!("{name}: 1 row couldn't be read and was left out")), - n => session.warn(format!("{name}: {n} rows couldn't be read and were left out")), + if report.skipped > 0 { + session.say(rustgis_engine::cmd::whole::unread_note(&name, report.skipped)); } // A Z/M loss this export says from its read; one said only when the layer opened // isn't said here again, so the export's own note says it. @@ -249,7 +247,7 @@ impl Engine { // a feature with a place that can't be given there is in it without its geometry. let (lonlat, unplaced) = ds.in_lonlat_leaving_out()?; if let Some(note) = rustgis_engine::data::unplaced_note(&format!("{name} as GeoJSON"), &ds.name, unplaced) { - session.notify(note, false); + session.say(note); } return Ok(rustgis_engine::data::io::to_geojson(&lonlat).to_string()); } @@ -267,7 +265,7 @@ impl Engine { session.say(note); } if let Some(note) = unplaced { - session.notify(note, false); + session.say(note); } return Ok(text); } @@ -302,7 +300,7 @@ impl Engine { session.say(note); } if let Some(note) = rustgis_engine::data::unplaced_note(&format!("{} as GeoJSON", ds.name), &ds.name, unplaced) { - session.notify(note, false); + session.say(note); } Ok::(text) }); diff --git a/crates/data/src/export.rs b/crates/data/src/export.rs index 392e38bf3a..8cdf77524f 100644 --- a/crates/data/src/export.rs +++ b/crates/data/src/export.rs @@ -76,7 +76,7 @@ pub struct Exported { /// empty for the other formats). pub written_values: Vec, /// GeoParquet timestamp representation changes counted during export. - pub date_messages: Vec, + pub date_messages: Vec, /// What reading the source lost or assumed besides the counts above /// ([`crate::source::Batch::notes`]), said as they are. pub read_notes: crate::loss::Notes, diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index d77095b25a..9ab87de52f 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -524,10 +524,11 @@ fn geoparquet_counts_values_written_as_null() { assert_eq!(streamed.unfit, vec![0, 2, 1, 1]); let note = crate::source::parquet::unfit_note(&layer.fields, &streamed.unfit, "lossy.parquet").unwrap(); assert_eq!( - note, + note.as_str(), "lossy.parquet: 4 values couldn't be written as their columns' types and were written as null, in 'count', 'share', 'open'" ); - assert_eq!(crate::source::parquet::values_note(&ds, "lossy.parquet").as_deref(), Some(note.as_str())); + assert_eq!(note.loss, Some(crate::loss::LossCode::DroppedValue)); + assert_eq!(crate::source::parquet::values_note(&ds, "lossy.parquet").as_ref().map(crate::loss::Note::as_str), Some(note.as_str())); let back = read_back(&d.join("lossy.parquet")); assert_eq!((&back.features[1].attrs[1], &back.features[3].attrs[3]), (&Value::Null, &Value::Null)); @@ -543,7 +544,7 @@ fn geoparquet_counts_values_written_as_null() { let fields = vec![Field::new("a\u{202E}b\nc", FieldType::Integer), Field::new("x".repeat(60), FieldType::Integer)]; let note = crate::source::parquet::unfit_note(&fields, &[1, 1], "out\u{2028}.parquet").unwrap(); let want = "out .parquet: 2 values couldn't be written as their columns' types and were written as null, in 'a b c'"; - assert_eq!(note, format!("{want}, '{}…'", "x".repeat(40))); + assert_eq!(note.as_str(), format!("{want}, '{}…'", "x".repeat(40))); let _ = std::fs::remove_dir_all(d); } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index e5dd5d686d..8bdb90d1d8 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -606,11 +606,13 @@ pub fn holds_a_system(ext: &str) -> bool { /// What is said of a CSV export of a point layer written in `crs` other than longitude/latitude: /// the file can't say its system, so adding it back needs it given. `None` otherwise. -pub fn csv_system_note(path: &str, geometry_type: GeometryType, crs: Crs) -> Option { +pub fn csv_system_note(path: &str, geometry_type: GeometryType, crs: Crs) -> Option { let ext = Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); - (ext == "csv" && geometry_type == GeometryType::Point && crs != Crs::LonLat).then(|| { - format!("{path}: its coordinates are in {}, which a CSV file can't say; give that system when adding it back", crs.label()) - }) + (ext == "csv" && geometry_type == GeometryType::Point && crs != Crs::LonLat) + .then(|| { + format!("{path}: its coordinates are in {}, which a CSV file can't say; give that system when adding it back", crs.label()) + }) + .map(|t| crate::loss::Note::loss(crate::loss::LossCode::DroppedCrsName, t)) } /// The coordinate system an export to extension `ext` is written in when none is asked for: the @@ -923,11 +925,12 @@ fn leave_out_unplaced(f: &mut crate::Feature, to: &crate::raster::Reprojection, /// What an export to `target` says of the `n` features of `layer` with a place `crs` can't hold /// ([`project_leaving_out`]): their geometry is left out, and in a format that holds only /// features with geometry the feature too. `None` for none. -pub fn unplaced_export_note(target: &str, layer: &str, n: usize, crs: Crs) -> Option { +pub fn unplaced_export_note(target: &str, layer: &str, n: usize, crs: Crs) -> Option { let system = if crs == Crs::LonLat { "WGS 84 (EPSG:4326)".to_string() } else { crs.label() }; (n > 0).then(|| { format!("{target}: {n} feature(s) of {layer} have a place that can't be given in {system}, so their geometry is left out (and the feature, in a format that holds only features with geometry)") }) + .map(|t| crate::loss::Note::loss(crate::loss::LossCode::DroppedGeometry, t)) } /// [`project_features`] without a step of its own: it counts each feature in the step under way @@ -1029,7 +1032,12 @@ pub fn write_bytes_in(ds: &Dataset, ext: &str, crs: Crs) -> Result<(Vec, usi /// can't hold is written without its geometry ([`project_leaving_out`]), and the notes say how /// many ([`unplaced_export_note`]). Also gives the dataset's [`Dataset::lonlat_extent`], as /// [`write_path_placed`] does, so a download converts each place once too. -pub fn write_bytes_noted(ds: &Dataset, ext: &str, crs: Crs, name: &str) -> Result<(Vec, usize, Vec, rustgis_geom::Extent)> { +pub fn write_bytes_noted( + ds: &Dataset, + ext: &str, + crs: Crs, + name: &str, +) -> Result<(Vec, usize, Vec, rustgis_geom::Extent)> { let ext = ext.to_ascii_lowercase(); if crs != Crs::LonLat { if !holds_a_system(&ext) { @@ -1135,7 +1143,12 @@ pub fn write_path_in(ds: &Dataset, path: &Path, crs: Crs) -> Result { /// couldn't remove once the new ones landed, [`kept_backups_note`]). A feature with a place `crs` /// can't hold is written without its geometry, and the notes say how many /// ([`unplaced_export_note`]). -pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> Result<(usize, Option, Vec)> { +pub fn write_path_to( + ds: &Dataset, + path: &Path, + crs: Crs, + gpkg: &GpkgTable, +) -> Result<(usize, Option, Vec)> { write_path_as(ds, path, crs, gpkg, true).map(|(left_out, table, notes, _)| (left_out, table, notes)) } @@ -1147,7 +1160,7 @@ pub fn write_path_placed( path: &Path, crs: Crs, gpkg: &GpkgTable, -) -> Result<(usize, Option, Vec, rustgis_geom::Extent)> { +) -> Result<(usize, Option, Vec, rustgis_geom::Extent)> { let (left_out, table, notes, placed) = write_path_as(ds, path, crs, gpkg, true)?; Ok((left_out, table, notes, lonlat_extent_placed(ds, crs, placed))) } @@ -1161,7 +1174,7 @@ fn write_path_as( crs: Crs, gpkg: &GpkgTable, leaving_out: bool, -) -> Result<(usize, Option, Vec, Option)> { +) -> Result<(usize, Option, Vec, Option)> { let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); if crs != Crs::LonLat && PROJECTED_FORMATS.contains(&ext.as_str()) { check_projected(&ext, crs)?; @@ -1200,7 +1213,7 @@ fn write_path_as( let (parts, left_out) = shapefile_parts_in(ds, crs)?; let parts: Vec<(std::path::PathBuf, Vec)> = parts.into_iter().map(|(e, bytes)| (shapefile_part(path, e), bytes)).collect(); let kept = place_shapefile(path, &stage_shapefile(&parts)?)?; - Ok((left_out, None, unplaced.into_iter().chain(kept_backups_note(path, &kept)).collect(), placed)) + Ok((left_out, None, unplaced.into_iter().chain(kept_backups_note(path, &kept).map(crate::loss::Note::plain)).collect(), placed)) } _ if crs != Crs::LonLat && !holds_a_system(&ext) => { Err(DataError::Unsupported(format!(".{ext} in {} (it holds longitude/latitude only)", crs.label()))) @@ -4575,7 +4588,7 @@ pub(crate) fn cut(s: &str, max: usize) -> &str { /// Line breaks, other control characters and the characters that reorder text (bidirectional /// marks, embeddings, overrides and isolates) in a name or in `target` show as spaces, and a /// long name only its first 40 bytes. -pub fn shapefile_names_note(fields: &[Field], target: &str) -> Option { +pub fn shapefile_names_note(fields: &[Field], target: &str) -> Option { names_note(fields, dbf_names(fields), target, "a Shapefile (10 bytes at most, unique ignoring case)") } @@ -4604,13 +4617,13 @@ pub(crate) fn free_column_name(fields: &[Field], base: &str) -> String { /// What an export to a GeoPackage says when field names differ only in case, which SQLite's /// columns can't ([`geopackage_columns`]), or `None` when every name is kept; written as /// [`shapefile_names_note`] is. -pub fn geopackage_names_note(fields: &[Field], target: &str) -> Option { +pub fn geopackage_names_note(fields: &[Field], target: &str) -> Option { names_note(fields, geopackage_columns(fields), target, "a GeoPackage (unique ignoring case)") } /// One notice of the fields whose names became `names` in `target`, a file of the kind `what` /// describes, or `None` when every name is kept. -fn names_note(fields: &[Field], names: Vec, target: &str, what: &str) -> Option { +fn names_note(fields: &[Field], names: Vec, target: &str, what: &str) -> Option { let renamed: Vec<(&str, String)> = fields.iter().zip(names).filter(|(f, n)| f.name != *n).map(|(f, n)| (f.name.as_str(), n)).collect(); if renamed.is_empty() { return None; @@ -4632,7 +4645,10 @@ fn names_note(fields: &[Field], names: Vec, target: &str, what: &str) -> .collect(); let more = if renamed.len() > 5 { format!(" and {} more", renamed.len() - 5) } else { String::new() }; let count = if renamed.len() == 1 { "1 field name was".to_string() } else { format!("{} field names were", renamed.len()) }; - Some(format!("{target}: {count} changed to fit {what}: {}{more}", listed.join(", "))) + Some(crate::loss::Note::loss( + crate::loss::LossCode::ChangedFieldName, + format!("{target}: {count} changed to fit {what}: {}{more}", listed.join(", ")), + )) } /// What an export to `target` says of the date fields it writes as ISO 8601 text, losing the field @@ -4704,28 +4720,34 @@ pub fn fine_dates<'a>(features: impl IntoIterator, fi /// What a GeoPackage export to `target` says of the date-times it rounded to the millisecond /// ([`fine_dates`]). `None` when there were none. -pub fn fine_dates_note(fields: &[Field], counts: &[usize], target: &str) -> Option { +pub fn fine_dates_note(fields: &[Field], counts: &[usize], target: &str) -> Option { let total: usize = counts.iter().sum(); if total == 0 { return None; } let target: String = target.chars().map(dbf_notice_char).collect(); let what = if total == 1 { "1 date-time was".to_string() } else { format!("{total} date-times were") }; - Some(format!("{target}: {what} rounded to the millisecond, as GeoPackage stores them, in {}", named_fields(fields, counts))) + Some(crate::loss::Note::loss( + crate::loss::LossCode::ChangedRounded, + format!("{target}: {what} rounded to the millisecond, as GeoPackage stores them, in {}", named_fields(fields, counts)), + )) } /// What a GeoPackage export to `target` says of the date-times it wrote in UTC ([`offset_dates`]). /// `None` when there were none. -pub fn utc_dates_note(fields: &[Field], counts: &[usize], target: &str) -> Option { +pub fn utc_dates_note(fields: &[Field], counts: &[usize], target: &str) -> Option { let total: usize = counts.iter().sum(); if total == 0 { return None; } let target: String = target.chars().map(dbf_notice_char).collect(); let what = if total == 1 { "1 date-time was".to_string() } else { format!("{total} date-times were") }; - Some(format!( - "{target}: {what} written in UTC, as GeoPackage stores them, without their own offsets, in {}", - named_fields(fields, counts) + Some(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!( + "{target}: {what} written in UTC, as GeoPackage stores them, without their own offsets, in {}", + named_fields(fields, counts) + ), )) } @@ -4779,7 +4801,7 @@ pub fn text_in_dates<'a>(features: impl IntoIterator, /// What a GeoPackage export to `target` says of the text it wrote in date fields /// ([`text_in_dates`]). `None` when there was none. -pub fn text_in_dates_note(fields: &[Field], counts: &[usize], target: &str) -> Option { +pub fn text_in_dates_note(fields: &[Field], counts: &[usize], target: &str) -> Option { let total: usize = counts.iter().sum(); if total == 0 { return None; @@ -4790,7 +4812,10 @@ pub fn text_in_dates_note(fields: &[Field], counts: &[usize], target: &str) -> O } else { format!("{total} values aren't dates and were written as they are, and read") }; - Some(format!("{target}: {what} back empty, in {}", named_fields(fields, counts))) + Some(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{target}: {what} back empty, in {}", named_fields(fields, counts)), + )) } /// The fields with a count, quoted, the first five named: `'a', 'b' and 3 more`. @@ -4855,7 +4880,7 @@ struct DbfLosses { /// Counts text cut to 254 bytes, non-null values left empty, and numbers rounded to the field's /// precision, in rows whose geometry is written. Each kind has one notice naming the affected /// source fields (first five, bounded and flattened); a clean dataset gives none. -pub fn shapefile_values_notes(ds: &Dataset, target: &str) -> Vec { +pub fn shapefile_values_notes(ds: &Dataset, target: &str) -> Vec { let decimals: Vec<_> = ds.fields.iter().enumerate().map(|(k, f)| if f.ty == FieldType::Double { dbf_decimals(ds, k) } else { 0 }).collect(); let mut counts = vec![DbfLosses::default(); ds.fields.len()]; @@ -4900,7 +4925,10 @@ pub fn shapefile_values_notes(ds: &Dataset, target: &str) -> Vec { let (cut, fields) = selected(|n| n.text); if cut > 0 { let what = if cut == 1 { "1 text value was".into() } else { format!("{cut} text values were") }; - notes.push(format!("{target}: {what} cut to at most 254 bytes, in {fields}")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::ChangedCut, + format!("{target}: {what} cut to at most 254 bytes, in {fields}"), + )); } let (empty, fields) = selected(|n| n.empty); if empty > 0 { @@ -4909,12 +4937,15 @@ pub fn shapefile_values_notes(ds: &Dataset, target: &str) -> Vec { } else { format!("{empty} values couldn't be written to their dBase fields and were") }; - notes.push(format!("{target}: {what} left empty, in {fields}")); + notes.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, format!("{target}: {what} left empty, in {fields}"))); } let (rounded, fields) = selected(|n| n.rounded); if rounded > 0 { let what = if rounded == 1 { "1 number was".into() } else { format!("{rounded} numbers were") }; - notes.push(format!("{target}: {what} rounded to fit dBase field precision, in {fields}")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::ChangedRounded, + format!("{target}: {what} rounded to fit dBase field precision, in {fields}"), + )); } notes } @@ -5005,13 +5036,14 @@ fn dbf_boolean(value: &Value) -> Option { /// Shapefile export (`.shp`, or zipped) writes only drawable geometry of the layer's one kind (it /// writes no null shapes, though the format has them); FlatGeobuf, KML and GPX exports write only /// features with geometry; the other formats leave nothing out. -pub fn left_out_note(name: &str, ext: &str, left_out: usize) -> Option { +pub fn left_out_note(name: &str, ext: &str, left_out: usize) -> Option { (left_out > 0).then(|| match ext { "shp" | "zip" => format!( "{name}: {left_out} features left out of the Shapefile: without drawable geometry, or with geometry of another kind than the layer's" ), _ => format!("{name}: {left_out} features without drawable geometry were left out"), }) + .map(|t| crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, t)) } /// Changes made by a CSV export to geometry and to text guarded for spreadsheets. @@ -5068,7 +5100,7 @@ impl CsvLosses { /// One notice for each loss of a layer written to `target`; none without loss. Geometry /// not written is counted by feature, whatever its kind: a layer of one type can hold others. - pub fn notes(&self, fields: &[Field], target: &str) -> Vec { + pub fn notes(&self, fields: &[Field], target: &str) -> Vec { let mut notes = Vec::new(); if self.as_one_point > 0 { let what = if self.as_one_point == 1 { @@ -5076,11 +5108,17 @@ impl CsvLosses { } else { format!("{} features have more than one point (a multipoint, line or polygon) and were", self.as_one_point) }; - notes.push(format!("{target}: {what} written as one, as CSV holds a point a row")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!("{target}: {what} written as one, as CSV holds a point a row"), + )); } if self.unwritten > 0 { let what = if self.unwritten == 1 { "1 feature".to_string() } else { format!("{} features", self.unwritten) }; - notes.push(format!("{target}: CSV holds a point a row, so the geometry of {what} wasn't written, only the attributes")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!("{target}: CSV holds a point a row, so the geometry of {what} wasn't written, only the attributes"), + )); } let total: usize = self.guarded.iter().sum(); if total > 0 { @@ -5093,7 +5131,9 @@ impl CsvLosses { .map(|(f, n)| format!("'{}' ({n})", dbf_notice_name(&f.name))) .collect::>() .join(", "); - notes.push(format!("{target}: CSV prefixed {total} text {values} with an apostrophe for spreadsheet protection in {affected}")); + notes.push(crate::loss::Note::plain(format!( + "{target}: CSV prefixed {total} text {values} with an apostrophe for spreadsheet protection in {affected}" + ))); } notes } @@ -5390,7 +5430,7 @@ impl TextLosses { /// One notice for each loss of a layer with `fields` written to `target`, with a count and /// the fields; none without loss. - pub fn notes(&self, fields: &[Field], target: &str) -> Vec { + pub fn notes(&self, fields: &[Field], target: &str) -> Vec { let numbers = |t: &FieldText| t.column.is_some_and(|c| c.ty() != FieldType::Text); // Each field's count over the layers read back. let counts = |count: &dyn Fn(&FieldText) -> usize| -> Vec { @@ -5409,7 +5449,10 @@ impl TextLosses { (n, true) => format!("{n} text values end with spaces"), (n, false) => format!("{n} text values start or end with spaces, tabs or line breaks"), }; - notes.push(format!("{target}: {what}, which reading the file back drops, in {}", named_fields(fields, &trimmed))); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{target}: {what}, which reading the file back drops, in {}", named_fields(fields, &trimmed)), + )); } let n: usize = blank.iter().sum(); if n > 0 { @@ -5419,36 +5462,45 @@ impl TextLosses { (1, true) => "1 text value, blank or , reads".to_string(), (n, true) => format!("{n} text values, blank or , read"), }; - notes.push(format!("{target}: {what} back as empty (null), in {}", named_fields(fields, &blank))); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{target}: {what} back as empty (null), in {}", named_fields(fields, &blank)), + )); } let nul = counts(&|t| t.nul); let n: usize = nul.iter().sum(); if n > 0 { let what = if n == 1 { "1 text value holds".to_string() } else { format!("{n} text values hold") }; - notes.push(format!( + notes.push(crate::loss::Note::loss(crate::loss::LossCode::ChangedCut, format!( "{target}: {what} a NUL character, and reading the file back keeps only the text before it, read as empty (null) when that is blank, in {}", named_fields(fields, &nul) - )); + ))); } let apostrophe = counts(&|t| t.apostrophe); let n: usize = apostrophe.iter().sum(); if n > 0 { let what = if n == 1 { "1 text value starts".to_string() } else { format!("{n} text values start") }; - notes.push(format!( + notes.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, format!( "{target}: {what} with an apostrophe before =, +, -, @, a tab or a line break, which reading the file back takes for the formula guard and drops, in {}", named_fields(fields, &apostrophe) - )); + ))); } if self.unread > 0 { let what = if self.unread == 1 { "1 feature is".to_string() } else { format!("{} features are", self.unread) }; - notes.push(format!( - "{target}: {what} written but won't read back: no coordinate is inside longitude/latitude, or too few for the shape" + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!( + "{target}: {what} written but won't read back: no coordinate is inside longitude/latitude, or too few for the shape" + ), )); } if self.vertices > 0 { let what = if self.vertices == 1 { "1 vertex won't".to_string() } else { format!("{} vertices won't", self.vertices) }; - notes.push(format!( - "{target}: {what} read back with the features kept: outside longitude/latitude, or in a part left with too few to keep" + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!( + "{target}: {what} read back with the features kept: outside longitude/latitude, or in a part left with too few to keep" + ), )); } notes @@ -5485,12 +5537,12 @@ impl std::ops::AddAssign for TextLosses { /// [`gpx_notes`] with each feature named from `name_field`, and [`TextLosses`]' (a Shapefile's /// other values are [`shapefile_values_notes`]). A streamed export counts CSV's changes a chunk /// at a time instead. -pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option, target: &str) -> Result> { +pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option, target: &str) -> Result { export_losses_notes_in(ds, ext, name_field, target, Crs::LonLat) } /// As [`export_losses_notes`], for an export written in `crs`. -pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option, target: &str, crs: Crs) -> Result> { +pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option, target: &str, crs: Crs) -> Result { let mut notes = match ext { "csv" => { // Of the coordinates the file is written in: longitude/latitude, or another @@ -5514,21 +5566,41 @@ pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)? }; let mut notes = losses.notes(&ds.fields, target); - notes.extend(losses.coordinates_note_in(&ds.fields, target, crs)); + notes.extend(losses.coordinates_note_in(&ds.fields, target, crs).map(crate::loss::Note::plain)); notes } - "kml" | "kmz" => kml_empty_fields_note(ds, target)?.into_iter().chain(kml_blank_names_note(ds, target)?).collect(), - "gpx" => gpx_notes(ds, name_field, target), + "kml" | "kmz" => { + let placed = written_with_geometry(ds)?; + kml_empty_fields_note(ds, &placed, target)?.into_iter().chain(kml_blank_names_note(ds, &placed, target)?).collect() + } + "gpx" => gpx_notes(ds, name_field, target)?, _ => Vec::new(), }; - notes.extend(TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, ext, name_field).notes(&ds.fields, target)); - Ok(notes) + notes.extend(text_losses_written(ds, ext, name_field)?.notes(&ds.fields, target)); + Ok(notes.into()) +} + +/// [`TextLosses`] of `ds` as written to a file with extension `ext`. KML and GPX hold +/// longitude/latitude, so a layer held in another system has its places checked where the writer +/// puts them: a chunk of features converted at a time (no copy of the layer), one with a place +/// that can't be given there without its geometry, as it is written. +fn text_losses_written(ds: &Dataset, ext: &str, name_field: Option) -> Result { + let of = |features: &[crate::Feature]| TextLosses::of(features, &ds.fields, ds.geometry_type, ext, name_field); + let to = if matches!(ext, "kml" | "kmz" | "gpx") { Some(ds.lonlat_conversion().map_err(DataError::of_conversion)?) } else { None }; + let Some(to) = to.filter(|to| !to.is_identity()) else { return Ok(of(&ds.features)) }; + let mut losses = TextLosses::default(); + for chunk in ds.features.chunks(8192) { + let mut chunk = chunk.to_vec(); + project_each_leaving_out(&mut chunk, &to, false)?; + losses += of(&chunk); + } + Ok(losses) } /// KML fields whose name is blank once trimmed, with values in the placemarks written: each is /// written as ``, which reading drops, so the column and its values are gone /// (#2415). A field with no value written is said by [`kml_empty_fields_note`]. -fn kml_blank_names_note(ds: &Dataset, target: &str) -> Result> { +fn kml_blank_names_note(ds: &Dataset, placed: &[bool], target: &str) -> Result> { let blank: Vec = ds.fields.iter().enumerate().filter(|(_, f)| f.name.trim().is_empty()).map(|(k, _)| k).collect(); if blank.is_empty() { return Ok(None); @@ -5536,7 +5608,7 @@ fn kml_blank_names_note(ds: &Dataset, target: &str) -> Result> { // One pass over the placemarks written, looking at Cancel as [`kml_empty_fields_note`] does. let mut with_value = vec![false; blank.len()]; let mut values = 0usize; - for f in ds.features.iter().filter(|f| f.geometry.is_some()) { + for f in ds.features.iter().zip(placed).filter(|(_, p)| **p).map(|(f, _)| f) { crate::progress::check()?; for (has, k) in with_value.iter_mut().zip(&blank) { if f.attrs.get(*k).is_some_and(|v| !v.is_null()) { @@ -5553,16 +5625,33 @@ fn kml_blank_names_note(ds: &Dataset, target: &str) -> Result> { format!( "{target}: {fields} with a blank name, and {written} in them, won't read back: reading KML drops extended data without a name" ) - })) + }) + .map(|t| crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, t))) +} + +/// Per feature of `ds`, whether a KML or GPX file of it writes the feature with its geometry: it has one, with a +/// place in longitude/latitude. The writer leaves out the geometry of a feature held in another +/// system whose place can't be given there. +/// One pass over the features, looking at Cancel between them. +fn written_with_geometry(ds: &Dataset) -> Result> { + let to = ds.lonlat_conversion().map_err(DataError::of_conversion)?; + let to = (!to.is_identity()).then_some(to); + ds.features + .iter() + .map(|f| { + crate::progress::check()?; + Ok(f.geometry.as_ref().is_some_and(|g| to.as_ref().is_none_or(|to| Dataset::converted_to_lonlat(to, g).is_some()))) + }) + .collect() } /// KML writes ExtendedData only for non-null values of placemarks it writes. Report every /// field absent from that output, even when an unwritten feature has a value for it. -fn kml_empty_fields_note(ds: &Dataset, target: &str) -> Result> { +fn kml_empty_fields_note(ds: &Dataset, placed: &[bool], target: &str) -> Result> { let mut written = vec![false; ds.fields.len()]; - for f in &ds.features { + for (f, placemark) in ds.features.iter().zip(placed) { crate::progress::check()?; - if f.geometry.is_some() { + if *placemark { for (written, value) in written.iter_mut().zip(&f.attrs) { *written |= !value.is_null(); } @@ -5579,7 +5668,11 @@ fn kml_empty_fields_note(ds: &Dataset, target: &str) -> Result> { Ok((!empty.is_empty()).then(|| { let count = empty.len(); let fields = if count == 1 { "field" } else { "fields" }; - format!("{target}: KML omitted {count} {fields} with no values in the placemarks written ({})", empty.join(", ")) + // Fields with no values lose nothing: said, without a code. + crate::loss::Note::plain(format!( + "{target}: KML omitted {count} {fields} with no values in the placemarks written ({})", + empty.join(", ") + )) })) } @@ -5597,8 +5690,10 @@ pub fn gpx_left_out(ds: &Dataset) -> usize { /// What a GPX file of `ds` can't hold, each feature named from field `name_field`: other /// fields' values, polygons (written as tracks along their outer rings, holes left out) and /// multipoints (a waypoint per point). One notice per kind; none for a layer GPX holds whole. -pub fn gpx_notes(ds: &Dataset, name_field: Option, target: &str) -> Vec { - let drawn = || ds.features.iter().filter(|f| f.geometry.is_some()); +pub fn gpx_notes(ds: &Dataset, name_field: Option, target: &str) -> Result> { + // Each feature placed once: the fields below go over them again. + let placed = written_with_geometry(ds)?; + let drawn = || ds.features.iter().zip(&placed).filter(|(_, p)| **p).map(|(f, _)| f); // Every other field, null everywhere or not: it isn't in the file, so it doesn't come back. // Fields with values come first, so the names shown before "and N more" are the ones that lost data. let mut fields: Vec<(bool, &str)> = (ds.fields.iter().enumerate()) @@ -5606,6 +5701,8 @@ pub fn gpx_notes(ds: &Dataset, name_field: Option, target: &str) -> Vec = fields.into_iter().map(|(_, name)| name).collect(); let (mut polygons, mut holes, mut multipoints) = (0, 0, 0); for g in drawn().filter_map(|f| f.geometry.as_ref()) { @@ -5623,7 +5720,12 @@ pub fn gpx_notes(ds: &Dataset, name_field: Option, target: &str) -> Vec = fields.iter().take(5).map(|s| format!("'{}'", dbf_notice_name(s))).collect(); let more = if fields.len() > 5 { format!(" and {} more", fields.len() - 5) } else { String::new() }; let what = if fields.len() == 1 { "1 field wasn't" } else { "fields weren't" }; - notes.push(format!("{target}: GPX holds a name for each feature, so {what} written: {}{more}", names.join(", "))); + let text = format!("{target}: GPX holds a name for each feature, so {what} written: {}{more}", names.join(", ")); + notes.push(if lost_values { + crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, text) + } else { + crate::loss::Note::plain(text) + }); } if polygons > 0 { let what = if polygons == 1 { "1 polygon was".to_string() } else { format!("{polygons} polygons were") }; @@ -5632,13 +5734,19 @@ pub fn gpx_notes(ds: &Dataset, name_field: Option, target: &str) -> Vec ", and 1 hole left out".to_string(), n => format!(", and {n} holes left out"), }; - notes.push(format!("{target}: GPX has no areas, so {what} written as tracks along their outer edges{left}")); + // Written as their outlines; what is lost are the holes, when there are any. + let text = format!("{target}: GPX has no areas, so {what} written as tracks along their outer edges{left}"); + notes.push(if holes > 0 { + crate::loss::Note::loss(crate::loss::LossCode::DroppedRing, text) + } else { + crate::loss::Note::plain(text) + }); } if multipoints > 0 { let what = if multipoints == 1 { "1 multipoint was".to_string() } else { format!("{multipoints} multipoints were") }; - notes.push(format!("{target}: {what} written as a waypoint for each of its points")); + notes.push(crate::loss::Note::plain(format!("{target}: {what} written as a waypoint for each of its points"))); } - notes + Ok(notes) } /// Whether [`shapefile_parts_in`] writes a feature with geometry `g` to a layer of type `gt`: one @@ -5727,7 +5835,7 @@ fn shapefile_geometry_losses(g: Option<&Geometry>, gt: GeometryType, drawable: f /// writes is drawable (an infinite latitude in Web Mercator is written at 85.05°), and only parts /// too short to draw are left out. `target` names what was written; line /// breaks and other control characters in it show as spaces. -pub fn shapefile_geometry_notes(ds: &Dataset, target: &str, crs: Crs) -> Vec { +pub fn shapefile_geometry_notes(ds: &Dataset, target: &str, crs: Crs) -> Vec { // Written as held when `crs` is the system the layer holds its coordinates in; otherwise a // converted copy, which refused every vertex that isn't a place. let drawable: fn(&Coord) -> bool = if crs == ds.coord_crs() { |c| c.x.is_finite() && c.y.is_finite() } else { |_| true }; @@ -5745,16 +5853,22 @@ pub fn shapefile_geometry_notes(ds: &Dataset, target: &str, crs: Crs) -> Vec 0 { - let (one, many, why) = if ds.geometry_type == GeometryType::Polyline { - ("line part", "line parts", "with fewer than 2 drawable vertices") + use crate::loss::LossCode::{DroppedGeometry, DroppedRing}; + let (one, many, why, code) = if ds.geometry_type == GeometryType::Polyline { + ("line part", "line parts", "with fewer than 2 drawable vertices", DroppedGeometry) } else { - ("polygon ring", "polygon rings", "with fewer than 3 drawable vertices or in a polygon whose outer ring was left out") + ( + "polygon ring", + "polygon rings", + "with fewer than 3 drawable vertices or in a polygon whose outer ring was left out", + DroppedRing, + ) }; let what = if parts == 1 { format!("1 {one} was") } else { format!("{parts} {many} were") }; - notes.push(format!("{target}: {what} left out of the Shapefile, {why}")); + notes.push(crate::loss::Note::loss(code, format!("{target}: {what} left out of the Shapefile, {why}"))); } notes } @@ -6346,14 +6460,17 @@ mod tests { fn left_out_notes_say_what_the_format_cant_hold() { for ext in ["shp", "zip"] { assert_eq!( - left_out_note("out", ext, 2).as_deref(), + left_out_note("out", ext, 2).as_ref().map(crate::loss::Note::as_str), Some( "out: 2 features left out of the Shapefile: without drawable geometry, or with geometry of another kind than the layer's" ) ); } for ext in ["fgb", "kml", "gpx"] { - assert_eq!(left_out_note("out", ext, 1).as_deref(), Some("out: 1 features without drawable geometry were left out")); + assert_eq!( + left_out_note("out", ext, 1).as_ref().map(crate::loss::Note::as_str), + Some("out: 1 features without drawable geometry were left out") + ); } assert_eq!(left_out_note("out", "shp", 0), None); assert_eq!(left_out_note("out", "gpkg", 0), None); @@ -6385,9 +6502,12 @@ mod tests { let (back, _) = read_path(&dir.path().join("mp.shp"))?; assert_eq!(coords(&back.features[0].geometry), 3); assert_eq!( - shapefile_geometry_notes(&points, "mp.shp", Crs::LonLat), + shapefile_geometry_notes(&points, "mp.shp", Crs::LonLat).iter().map(crate::loss::Note::as_str).collect::>(), ["mp.shp: 1 vertex with a missing or infinite coordinate was left out of the Shapefile"] ); + assert!( + shapefile_geometry_notes(&points, "mp.shp", Crs::LonLat).iter().all(|n| n.loss == Some(crate::loss::LossCode::DroppedGeometry)) + ); // Lines: two vertices go, and the part left with one finite vertex goes with them, as does // a part written with one vertex. @@ -6398,7 +6518,7 @@ mod tests { let (back, _) = read_path(&dir.path().join("lines.shp"))?; assert_eq!(coords(&back.features[0].geometry), 2); assert_eq!( - shapefile_geometry_notes(&lines, "lines.shp", Crs::LonLat), + shapefile_geometry_notes(&lines, "lines.shp", Crs::LonLat).iter().map(crate::loss::Note::as_str).collect::>(), [ "lines.shp: 2 vertices with a missing or infinite coordinate were left out of the Shapefile", "lines.shp: 2 line parts were left out of the Shapefile, with fewer than 2 drawable vertices", @@ -6422,7 +6542,7 @@ mod tests { let (back, _) = read_path(&dir.path().join("polys.shp"))?; assert_eq!(coords(&back.features[0].geometry), 5); assert_eq!( - shapefile_geometry_notes(&polys, "polys.shp", Crs::LonLat), + shapefile_geometry_notes(&polys, "polys.shp", Crs::LonLat).iter().map(crate::loss::Note::as_str).collect::>(), [ "polys.shp: 5 vertices with a missing or infinite coordinate were left out of the Shapefile", "polys.shp: 3 polygon rings were left out of the Shapefile, with fewer than 3 drawable vertices or in a polygon whose outer ring was left out", @@ -6458,14 +6578,14 @@ mod tests { let (back, _) = read_path(&dir.path().join("merc.shp"))?; assert_eq!(coords(&back.features[0].geometry), 4); assert_eq!( - shapefile_geometry_notes(&merc, "merc.shp", Crs::WebMercator), + shapefile_geometry_notes(&merc, "merc.shp", Crs::WebMercator).iter().map(crate::loss::Note::as_str).collect::>(), ["merc.shp: 1 line part was left out of the Shapefile, with fewer than 2 drawable vertices"] ); assert_eq!(write_path(&merc, &dir.path().join("merc-4326.shp"))?, 0); let (back, _) = read_path(&dir.path().join("merc-4326.shp"))?; assert_eq!(coords(&back.features[0].geometry), 2); assert_eq!( - shapefile_geometry_notes(&merc, "merc-4326.shp", Crs::LonLat), + shapefile_geometry_notes(&merc, "merc-4326.shp", Crs::LonLat).iter().map(crate::loss::Note::as_str).collect::>(), [ "merc-4326.shp: 1 vertex with a missing or infinite coordinate was left out of the Shapefile", "merc-4326.shp: 2 line parts were left out of the Shapefile, with fewer than 2 drawable vertices", @@ -7804,6 +7924,40 @@ mod tests { assert_eq!(write_bytes(&ds, "gpx").unwrap().1, 2); } + /// Each writer's notice of what a file can't hold carries the code of its loss, and the + /// notices that say nothing was lost carry none. + #[test] + fn export_notices_carry_their_loss_codes() { + use crate::loss::LossCode::*; + let date = |name: &str| Field::new(name, FieldType::DateTime); + let code = |n: Option| n.and_then(|n| n.loss); + assert_eq!(code(fine_dates_note(&[date("at")], &[2], "t.gpkg")), Some(ChangedRounded)); + assert_eq!(code(utc_dates_note(&[date("at")], &[2], "t.gpkg")), Some(DroppedValue)); + assert_eq!(code(text_in_dates_note(&[date("at")], &[2], "t.gpkg")), Some(DroppedValue)); + assert_eq!(code(left_out_note("t.shp", "shp", 3)), Some(DroppedFeature)); + assert_eq!(code(left_out_note("t.kml", "kml", 3)), Some(DroppedFeature)); + assert_eq!(code(csv_system_note("t.csv", GeometryType::Point, Crs::WebMercator)), Some(DroppedCrsName)); + let long = [Field::new("population_2020", FieldType::Integer)]; + assert_eq!(code(shapefile_names_note(&long, "t.shp")), Some(ChangedFieldName)); + let cased = [Field::new("Name", FieldType::Text), Field::new("name", FieldType::Text)]; + assert_eq!(code(geopackage_names_note(&cased, "t.gpkg")), Some(ChangedFieldName)); + assert_eq!(code(crate::unplaced_note("t", "lines", 1)), Some(DroppedGeometry)); + // GPX: fields with values aren't written, a lost value; fields empty everywhere aren't + // either, and lose nothing. Polygons go as their outlines, losing only their holes. + let mut ds = text_layer(&["name", "note"], &[&[Some("a"), Some("kept")]]); + let gpx = |ds: &Dataset| gpx_notes(ds, name_field(ds), "t").unwrap().into_iter().map(|n| n.loss).collect::>(); + assert_eq!(gpx(&ds), [Some(DroppedValue)]); + ds.features[0].attrs[1] = Value::Null; + assert_eq!(gpx(&ds), [None]); + let mut area = Dataset::new("a", GeometryType::Polygon, vec![]); + let ring = vec![Coord::new(0.0, 0.0), Coord::new(4.0, 0.0), Coord::new(4.0, 4.0), Coord::new(0.0, 0.0)]; + let hole = vec![Coord::new(1.0, 1.0), Coord::new(2.0, 1.0), Coord::new(2.0, 2.0), Coord::new(1.0, 1.0)]; + area.push(Some(Geometry::Polygon(vec![vec![ring.clone()]])), vec![]); + assert_eq!(gpx(&area), [None]); + area.push(Some(Geometry::Polygon(vec![vec![ring, hole]])), vec![]); + assert_eq!(gpx(&area), [Some(DroppedRing)]); + } + /// A text layer for [`TextLosses`]: point features with `rows` of text values, and one without /// geometry holding blanks and padded text, which KML, GPX and Shapefile don't write. fn text_layer(names: &[&str], rows: &[&[Option<&str>]]) -> Dataset { @@ -7818,7 +7972,11 @@ mod tests { } fn text_notes(ds: &Dataset, ext: &str) -> Vec { - TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, ext, name_field(ds)).notes(&ds.fields, "t") + TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, ext, name_field(ds)) + .notes(&ds.fields, "t") + .into_iter() + .map(|n| n.text) + .collect() } #[test] @@ -7903,7 +8061,7 @@ mod tests { fn kml_says_fields_with_a_blank_name() { let ds = text_layer(&["name", "", " ", "\t"], &[&[Some("a"), Some("x"), Some("y"), None], &[Some("b"), Some("z"), None, None]]); let notes = export_losses_notes(&ds, "kml", name_field(&ds), "t").unwrap(); - let blank: Vec<&String> = notes.iter().filter(|n| n.contains("blank name")).collect(); + let blank: Vec<&str> = notes.iter().filter(|n| n.contains("blank name")).map(crate::loss::Note::as_str).collect(); assert_eq!( blank, ["t: 2 fields with a blank name, and 3 values in them, won't read back: reading KML drops extended data without a name"], @@ -7962,12 +8120,13 @@ mod tests { ); // GPX writes only names: one notice says the other fields, with a value first. assert_eq!( - gpx_notes(&ds, name_field(&ds), "t"), + gpx_notes(&ds, name_field(&ds), "t").unwrap().iter().map(crate::loss::Note::as_str).collect::>(), ["t: GPX holds a name for each feature, so fields weren't written: 'note', 'gone', 'ele'"] ); + assert!(gpx_notes(&ds, name_field(&ds), "t").unwrap().iter().all(|n| n.loss == Some(crate::loss::LossCode::DroppedValue))); let clean = text_layer(&["name"], &[&[Some("a")], &[None]]); assert!(text_notes(&clean, "gpx").is_empty()); - assert!(gpx_notes(&clean, name_field(&clean), "t").is_empty()); + assert!(gpx_notes(&clean, name_field(&clean), "t").unwrap().is_empty()); assert!(text_notes(&ds, "geojson").is_empty()); } @@ -8012,7 +8171,7 @@ mod tests { // In the name, " a" is trimmed and "" null; in 'title', a text column, " a" is trimmed too, // the same value. assert_eq!( - losses(&ds), + losses(&ds).iter().map(crate::loss::Note::as_str).collect::>(), [ "t: 1 text value starts or ends with spaces, tabs or line breaks, which reading the file back drops, in 'title'", "t: 1 blank text value reads back as empty (null), in 'title'", @@ -8035,7 +8194,7 @@ mod tests { let ds = text_layer(&["code"], &[&[Some(" 5")], &[Some("6")]]); let losses = |ds: &Dataset| TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, "kml", Some(0)).notes(&ds.fields, "t"); assert_eq!( - losses(&ds), + losses(&ds).iter().map(crate::loss::Note::as_str).collect::>(), ["t: 1 text value starts or ends with spaces, tabs or line breaks, which reading the file back drops, in 'code'"] ); let back = crate::interop::to_kml(&ds, Some(0)).unwrap(); @@ -8187,10 +8346,17 @@ mod tests { } assert_eq!(sum, whole, "chunks of {size}"); } - assert_eq!(whole.notes(&ds.fields, "t"), ["t: 5 blank text values read back as empty (null), in 'note', 'code'"]); + assert_eq!( + whole.notes(&ds.fields, "t").iter().map(crate::loss::Note::as_str).collect::>(), + ["t: 5 blank text values read back as empty (null), in 'note', 'code'"] + ); + assert!(whole.notes(&ds.fields, "t").iter().all(|n| n.loss == Some(crate::loss::LossCode::DroppedValue))); // Alone, the first chunk's 'code' is text, which keeps its spaces. let first = TextLosses::of(&ds.features[..1], &ds.fields, ds.geometry_type, "csv", None); - assert_eq!(first.notes(&ds.fields, "t"), ["t: 1 blank text value reads back as empty (null), in 'note'"]); + assert_eq!( + first.notes(&ds.fields, "t").iter().map(crate::loss::Note::as_str).collect::>(), + ["t: 1 blank text value reads back as empty (null), in 'note'"] + ); // A column that is Text skips the values after, and chunks still add up to the whole: a // whole number past a Double's digits, alone a chunk's Integer, is Text after text. let wide = text_layer(&["id"], &[&[Some("abc")], &[Some("9007199254740993")], &[Some(" ")]]); @@ -8231,7 +8397,7 @@ mod tests { let mut attrs = vec![Value::Null; 5]; attrs.push(Value::Int(7)); ds.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), attrs); - let notes = gpx_notes(&ds, None, "t.gpx"); + let notes = gpx_notes(&ds, None, "t.gpx").unwrap(); assert!(notes[0].contains("written: 'population', 'empty1'") && notes[0].ends_with("and 1 more"), "{notes:?}"); } @@ -8254,6 +8420,20 @@ mod tests { } ds.push(Some(Geometry::Point(Coord::new(3.0, 4.0))), vec![Value::Int(3), Value::Text("present".into())]); assert!(export_losses_notes(&ds, "kml", None, "parcels.kml").unwrap().is_empty()); + // Held in a projected system, its places are checked in the longitude/latitude the file + // holds: none is out of range there, so none is said not to read back. + let mut held = ds.clone(); + held.hold_in(Crs::Epsg(32631)).unwrap(); + for ext in ["kml", "gpx"] { + let notes = export_losses_notes(&held, ext, None, &format!("parcels.{ext}")).unwrap(); + assert!(notes.iter().all(|n| n.loss != Some(crate::loss::LossCode::DroppedFeature)), "{ext}: {notes:?}"); + } + // A feature with no place in longitude/latitude is written without its geometry, so no + // placemark holds its value: 'empty' still has none in the placemarks written. + held.push(Some(Geometry::Point(Coord::new(1e12, 0.0))), vec![Value::Int(4), Value::Text("lost".into())]); + held.features[2].attrs[1] = Value::Null; + let notes = export_losses_notes(&held, "kml", None, "parcels.kml").unwrap(); + assert!(notes.iter().any(|n| n.contains("KML omitted 1 field with no values in the placemarks written ('empty')")), "{notes:?}"); } /// A point layer's fields named like coordinates keep their values when its CSV is read back: @@ -9554,12 +9734,14 @@ mod tests { let mut ds = Dataset::new("d", GeometryType::Point, fields); ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text("x".repeat(300)), Value::Text("soon".into())]); assert_eq!( - shapefile_values_notes(&ds, "a.shp"), + shapefile_values_notes(&ds, "a.shp").iter().map(crate::loss::Note::as_str).collect::>(), [ "a.shp: 1 text value was cut to at most 254 bytes, in 'ts'", "a.shp: 1 value couldn't be written to its dBase field and was left empty, in 'issued'" ] ); + use crate::loss::LossCode::{ChangedCut, DroppedValue}; + assert_eq!(shapefile_values_notes(&ds, "a.shp").iter().map(|n| n.loss).collect::>(), [Some(ChangedCut), Some(DroppedValue)]); } /// A Shapefile's date fields are written as `.dbf` dates and read back as dates, whole and @@ -9641,7 +9823,7 @@ mod tests { let back = written(&long); assert_eq!(back, ["population", "POPULATI_1", "kept", "ééééé"], "premise: the writer's names"); assert_eq!( - shapefile_names_note(&long.fields, "out.zip").as_deref(), + shapefile_names_note(&long.fields, "out.zip").as_ref().map(crate::loss::Note::as_str), Some( "out.zip: 3 field names were changed to fit a Shapefile (10 bytes at most, unique ignoring case): \ 'population_2020' → 'population', 'POPULATION_2021' → 'POPULATI_1', 'éééééé' → 'ééééé'" @@ -9649,29 +9831,29 @@ mod tests { ); // One: singular. A name of spaces is written FIELD, and padding is trimmed. assert_eq!( - shapefile_names_note(&layer(&[" "]).fields, "a.shp").as_deref(), + shapefile_names_note(&layer(&[" "]).fields, "a.shp").as_ref().map(crate::loss::Note::as_str), Some("a.shp: 1 field name was changed to fit a Shapefile (10 bytes at most, unique ignoring case): ' ' → 'FIELD'") ); assert!(shapefile_names_note(&layer(&[" id"]).fields, "a.shp").is_some_and(|n| n.ends_with("' id' → 'id'"))); // Past five, the rest are counted; a very long name shows its start. let many: Vec = (0..8).map(|i| format!("measurement_{i}")).collect(); - let note = shapefile_names_note(&layer(&many.iter().map(String::as_str).collect::>()).fields, "m.shp").unwrap(); + let note = shapefile_names_note(&layer(&many.iter().map(String::as_str).collect::>()).fields, "m.shp").unwrap().text; assert!(note.starts_with("m.shp: 8 field names were changed"), "{note}"); assert!(note.ends_with("'measurement_4' → 'measurem_4' and 3 more"), "{note}"); // Line breaks and other control characters in a name show as spaces: one line. - let note = shapefile_names_note(&layer(&["a\nb\r\tc\u{2028}d\u{2029}e_long_name"]).fields, "c.shp").unwrap(); + let note = shapefile_names_note(&layer(&["a\nb\r\tc\u{2028}d\u{2029}e_long_name"]).fields, "c.shp").unwrap().text; assert!(!note.contains(['\n', '\r', '\t', '\u{2028}', '\u{2029}']), "{note:?}"); // U+2028 is three bytes: the ten-byte name ends at d. assert!(note.ends_with("'a b c d e_long_name' → 'a b c d'"), "{note:?}"); // So does the target, a path or layer name given by the user or read from a file. - let note = shapefile_names_note(&layer(&["population_2020"]).fields, "out\nput\r\u{2029}.shp").unwrap(); + let note = shapefile_names_note(&layer(&["population_2020"]).fields, "out\nput\r\u{2029}.shp").unwrap().text; assert!(note.starts_with("out put .shp: 1 field name"), "{note:?}"); // Characters that reorder text (a right-to-left override, isolates, direction marks) show // as spaces too, so the notice reads 'old' → 'new' in that order; a zero-width joiner // stays, as emoji sequences use it. // The override and the isolate are three bytes each: the ten-byte name ends at d. let bidi = "a\u{202E}bc\u{2066}d\u{2069}e\u{200E}f\u{200F}g\u{061C}h_longer"; - let note = shapefile_names_note(&layer(&[bidi]).fields, "r\u{202E}tl.shp").unwrap(); + let note = shapefile_names_note(&layer(&[bidi]).fields, "r\u{202E}tl.shp").unwrap().text; assert!(!note.contains(['\u{202E}', '\u{2066}', '\u{2069}', '\u{200E}', '\u{200F}', '\u{061C}']), "{note:?}"); assert!(note.starts_with("r tl.shp: ") && note.ends_with("'a bc d e f g h_longer' → 'a bc d'"), "{note:?}"); let joined = "a\u{200D}b_long_name"; @@ -9682,7 +9864,7 @@ mod tests { let wide = format!("{}é_long", "z".repeat(39)); assert!(shapefile_names_note(&layer(&[&wide]).fields, "w.shp").unwrap().contains(&format!("'{}…' →", "z".repeat(39)))); let huge = "x".repeat(5000); - let note = shapefile_names_note(&layer(&[&huge]).fields, "h.shp").unwrap(); + let note = shapefile_names_note(&layer(&[&huge]).fields, "h.shp").unwrap().text; assert!(note.len() < 200 && note.contains(&format!("'{}…' → 'xxxxxxxxxx'", "x".repeat(40))), "{note}"); } diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index a05e98c395..e9319f24c3 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -815,9 +815,12 @@ fn layer_list(names: &[&str]) -> String { /// What `what` (an export to a file, a copy, a package: "{target}") says of the `n` features of /// `layer` it took without their geometry, as a place of each can't be given in /// longitude/latitude ([`Dataset::in_lonlat_leaving_out`]). `None` for none. -pub fn unplaced_note(target: &str, layer: &str, n: usize) -> Option { +pub fn unplaced_note(target: &str, layer: &str, n: usize) -> Option { (n > 0).then(|| { - format!("{target}: {n} feature(s) of {layer} have a place that can't be given in longitude/latitude, so their geometry is left out (and the feature, where only features with geometry are kept)") + loss::Note::loss( + loss::LossCode::DroppedGeometry, + format!("{target}: {n} feature(s) of {layer} have a place that can't be given in longitude/latitude, so their geometry is left out (and the feature, where only features with geometry are kept)"), + ) }) } diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 58e7ba2fcb..a781eb61e2 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -60,7 +60,7 @@ macro_rules! loss_codes { loss_codes! { DroppedLegend => ("dropped.legend", Dropped, "Use a service with short HTTP or HTTPS addresses for its legend pictures."), - DroppedRing => ("dropped.ring", Dropped, "Correct the unreadable polygon ring in the source."), + DroppedRing => ("dropped.ring", Dropped, "Correct the unreadable polygon ring in the source, or write to a format that holds holes, such as GeoPackage."), DroppedExtraAttributes => ( "dropped.extra-attributes", Dropped, @@ -81,7 +81,7 @@ loss_codes! { DroppedCrsName => ( "dropped.crs-name", Dropped, - "Keep the source file's coordinate system definition with the export." + "Keep the source file's coordinate system definition with the export, or export in WGS 84, which every format can name." ), DroppedFeature => ( "dropped.feature", @@ -99,6 +99,16 @@ loss_codes! { "Read less at once, such as by filtering or clipping the source first." ), ChangedTruncated => ("changed.truncated", Changed, "Use a decimal field to keep the fractional part."), + ChangedFieldName => ( + "changed.field-name", + Changed, + "Use field names the format holds: at most 10 bytes and unique ignoring case for a Shapefile, unique ignoring case for a GeoPackage." + ), + ChangedCut => ( + "changed.cut", + Changed, + "Shorten the text to what the format holds (254 bytes for a Shapefile; nothing past a NUL character), or write to a format without the limit, such as GeoPackage." + ), ChangedBody => ("changed.body", Changed, "Export in the layer's own coordinate system, which keeps its body."), ChangedEncoding => ( "changed.encoding", @@ -108,7 +118,7 @@ loss_codes! { ChangedRounded => ( "changed.rounded", Changed, - "Keep the source file where times finer than a microsecond matter." + "Keep the source file where finer values matter, or write to a format that holds them (times finer than the format keeps, or numbers past a dBase field's precision)." ), ChangedPosition => ( "changed.position", diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index c5a0cc3d05..5bc8085bde 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -288,7 +288,7 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result Vec { + /// An offset left out is a value lost; ISO text keeps the value. + fn notes(&self, fields: &[Field], target: &str) -> Vec { let target: String = target.chars().map(crate::io::dbf_notice_char).collect(); let target = if target.is_empty() { String::new() } else { format!("{target}: ") }; let mut notes = Vec::new(); let utc: Vec = self.offsets.iter().enumerate().map(|(k, &n)| if self.modes.get(k) == Some(&2) { n } else { 0 }).collect(); let text: Vec = self.counts.iter().enumerate().map(|(k, &n)| if self.modes.get(k) == Some(&3) { n } else { 0 }).collect(); - for (counts, what) in [ - (&utc, "date-times were written in UTC without their original offsets"), - (&text, "date-times were written as ISO text because their column mixes zoned and unzoned values"), + for (counts, what, lost) in [ + (&utc, "date-times were written in UTC without their original offsets", true), + (&text, "date-times were written as ISO text because their column mixes zoned and unzoned values", false), ] { let n: usize = counts.iter().sum(); if n > 0 { - notes.push(format!("{target}{n} {what}, in {}", crate::io::named_fields(fields, counts))); + let text = format!("{target}{n} {what}, in {}", crate::io::named_fields(fields, counts)); + notes.push(if lost { + crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, text) + } else { + crate::loss::Note::plain(text) + }); } } notes @@ -1789,7 +1795,7 @@ fn unfit(ty: FieldType, value: &Value) -> bool { /// The notice for values a GeoParquet export wrote as null because their column's type couldn't /// hold them, given the count per field (as `write_features` returns); `None` when there are /// none. Names the first five fields. -pub fn unfit_note(fields: &[Field], counts: &[usize], target: &str) -> Option { +pub fn unfit_note(fields: &[Field], counts: &[usize], target: &str) -> Option { let total = counts.iter().fold(0usize, |a, n| a.saturating_add(*n)); if total == 0 { return None; @@ -1804,12 +1810,15 @@ pub fn unfit_note(fields: &[Field], counts: &[usize], target: &str) -> Option Option { +pub fn values_note(ds: &crate::Dataset, target: &str) -> Option { let mut counts = vec![0usize; ds.fields.len()]; let mut layout = DateLayout::default(); for chunk in ds.features.chunks(BATCH) { @@ -1824,9 +1833,18 @@ pub fn values_note(ds: &crate::Dataset, target: &str) -> Option { } } } - let mut notes: Vec = unfit_note(&ds.fields, &counts, target).into_iter().collect(); - notes.extend(layout.notes(&ds.fields, target)); - if notes.is_empty() { None } else { Some(notes.join("; ")) } + // One notice: the values written as null, then how date-times are written; coded when either + // loses a value. + let said: Vec = + unfit_note(&ds.fields, &counts, target).into_iter().chain(layout.notes(&ds.fields, target)).collect(); + let loss = said.iter().find_map(|n| n.loss); + (!said.is_empty()).then(|| { + let text = said.iter().map(|n| n.text.as_str()).collect::>().join("; "); + match loss { + Some(code) => crate::loss::Note::loss(code, text), + None => crate::loss::Note::plain(text), + } + }) } /// Writes GeoParquet to `out`: the features `feed` hands to the function it is given, a run at @@ -1844,7 +1862,7 @@ pub(crate) fn write_features( crs: Crs, out: W, feed: &mut dyn FnMut(&mut dyn FnMut(&[Feature]) -> Result<()>) -> Result<()>, -) -> Result<(W, Vec, Vec)> { +) -> Result<(W, Vec, Vec)> { use parquet::basic::{Compression, Encoding, Repetition, ZstdLevel}; use parquet::data_type::{BoolType, ByteArray, ByteArrayType, DoubleType, Int32Type, Int64Type}; use parquet::file::metadata::KeyValue; diff --git a/crates/data/src/source/postgis.rs b/crates/data/src/source/postgis.rs index 790413c391..a2d002a4f4 100644 --- a/crates/data/src/source/postgis.rs +++ b/crates/data/src/source/postgis.rs @@ -1354,26 +1354,31 @@ fn count_offset(saved: &mut Saved, field: usize, column: &str, v: &Value) { /// What saving to `table` says of the date-times its columns didn't keep as they were /// ([`Saved::utc_dates`], [`Saved::zoneless_dates`], [`Saved::assumed_utc`]), naming the fields /// of `fields` they were in. -pub fn saved_dates_notes(fields: &[Field], saved: &Saved, table: &str) -> Vec { +pub fn saved_dates_notes(fields: &[Field], saved: &Saved, table: &str) -> Vec { let table: String = table.chars().map(crate::io::dbf_notice_char).collect(); - let kinds: [(&[usize], &str, &str); 3] = [ - (&saved.utc_dates, "1 date-time was saved in UTC, without its offset", "date-times were saved in UTC, without their offsets"), + // An offset left out is a value lost; a date-time without one saved as UTC keeps its clock time. + let kinds: [(&[usize], &str, &str, bool); 3] = [ + (&saved.utc_dates, "1 date-time was saved in UTC, without its offset", "date-times were saved in UTC, without their offsets", true), ( &saved.zoneless_dates, "1 date-time was saved at the clock time shown, without its offset", "date-times were saved at the clock time shown, without their offsets", + true, ), - (&saved.assumed_utc, "1 date-time without a time zone was saved as UTC", "date-times without a time zone were saved as UTC"), + (&saved.assumed_utc, "1 date-time without a time zone was saved as UTC", "date-times without a time zone were saved as UTC", false), ]; let why = ["(a timestamptz column holds only the moment)", "(a timestamp column has no time zone)", "(a timestamptz column holds a moment)"]; kinds .iter() .zip(why) - .filter_map(|((counts, one, many), why)| { + .filter_map(|((counts, one, many, lost), why)| { let total: usize = counts.iter().sum(); let what = if total == 1 { (*one).to_string() } else { format!("{total} {many}") }; - (total > 0).then(|| format!("{table}: {what} {why}, in {}", crate::io::named_fields(fields, counts))) + (total > 0).then(|| { + let text = format!("{table}: {what} {why}, in {}", crate::io::named_fields(fields, counts)); + if *lost { crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, text) } else { crate::loss::Note::plain(text) } + }) }) .collect() } @@ -2185,12 +2190,21 @@ mod tests { (&[0, 1][..], &[0, 2][..], &[0, 2][..]) ); let fields = [Field::new("id", FieldType::Integer), Field::new("seen", FieldType::DateTime)]; + use crate::loss::LossCode::DroppedValue; + let notes = saved_dates_notes(&fields, &saved, "wells"); assert_eq!( - saved_dates_notes(&fields, &saved, "wells"), + notes.iter().map(|n| (n.text.as_str(), n.loss)).collect::>(), [ - "wells: 1 date-time was saved in UTC, without its offset (a timestamptz column holds only the moment), in 'seen'", - "wells: 2 date-times were saved at the clock time shown, without their offsets (a timestamp column has no time zone), in 'seen'", - "wells: 2 date-times without a time zone were saved as UTC (a timestamptz column holds a moment), in 'seen'" + ( + "wells: 1 date-time was saved in UTC, without its offset (a timestamptz column holds only the moment), in 'seen'", + Some(DroppedValue) + ), + ( + "wells: 2 date-times were saved at the clock time shown, without their offsets (a timestamp column has no time zone), in 'seen'", + Some(DroppedValue) + ), + // Its clock time is kept, read as UTC. + ("wells: 2 date-times without a time zone were saved as UTC (a timestamptz column holds a moment), in 'seen'", None) ] ); assert!(saved_dates_notes(&fields, &Saved::default(), "wells").is_empty()); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 5eeed7bb43..7fb0d4625f 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -2146,7 +2146,7 @@ fn writes_points_lines_kmz_and_zipped_shapefiles() { // And the export says so, as the file has it; names kept (an id or geometry column moves // aside for a field) say nothing. assert_eq!( - crate::io::geopackage_names_note(&cased.fields, "c.gpkg").as_deref(), + crate::io::geopackage_names_note(&cased.fields, "c.gpkg").as_ref().map(crate::loss::Note::as_str), Some("c.gpkg: 1 field name was changed to fit a GeoPackage (unique ignoring case): 'a' → 'a_1'") ); let kept: Vec = ["fid", "geom", "a"].iter().map(|n| Field::new(*n, FieldType::Integer)).collect(); @@ -2154,7 +2154,7 @@ fn writes_points_lines_kmz_and_zipped_shapefiles() { // A long name shows its start and the ending that makes it unique. let long: Vec = ["Ab", "ab", "Bb", "bb"].iter().map(|n| Field::new(format!("{n}{}", "x".repeat(50)), FieldType::Integer)).collect(); - let note = crate::io::geopackage_names_note(&long, "l.gpkg").unwrap(); + let note = crate::io::geopackage_names_note(&long, "l.gpkg").unwrap().text; let x = |n| "x".repeat(n); assert!( note.ends_with(&format!( @@ -2172,7 +2172,7 @@ fn writes_points_lines_kmz_and_zipped_shapefiles() { ); // So does one that fits until it is made unique. let edge: Vec = ["A".repeat(40), "a".repeat(40)].iter().map(|n| Field::new(n, FieldType::Integer)).collect(); - let note = crate::io::geopackage_names_note(&edge, "e.gpkg").unwrap(); + let note = crate::io::geopackage_names_note(&edge, "e.gpkg").unwrap().text; assert!(note.ends_with(&format!("'{}' → '{}…{}_1'", "a".repeat(40), "a".repeat(20), "a".repeat(18))), "{note}"); // An empty layer writes too. let empty = Dataset::new("e", GeometryType::Point, vec![]); @@ -3336,7 +3336,7 @@ fn a_csv_export_takes_x_and_y_in_a_system_asked_for() { }; assert!((pt(&back_lonlat).x - pt(&ds_lonlat).x).abs() < 1e-9 && (pt(&back_lonlat).y - pt(&ds_lonlat).y).abs() < 1e-9); // The file can't say its system, so that is said. - let note = crate::io::csv_system_note("pts.csv", ds.geometry_type, lv95).unwrap(); + let note = crate::io::csv_system_note("pts.csv", ds.geometry_type, lv95).unwrap().text; assert!(note.contains("EPSG:2056") && note.contains("can't say"), "{note}"); assert_eq!(crate::io::csv_system_note("pts.gpkg", ds.geometry_type, lv95), None); // Fields named x and y push the columns to easting and northing; every name taken is said. @@ -4018,7 +4018,8 @@ fn geopackage_dates_are_written_and_read_as_dates() { crate::io::write_path(&permits, &path).unwrap(); assert_eq!( crate::io::utc_dates_note(&permits.fields, &crate::io::offset_dates(permits.features.iter(), &permits.fields), "permits.gpkg") - .as_deref(), + .as_ref() + .map(crate::loss::Note::as_str), Some("permits.gpkg: 1 date-time was written in UTC, as GeoPackage stores them, without their own offsets, in 'seen'") ); // Milliseconds are all a DATETIME holds: finer digits are rounded, and said; none lost, none said. @@ -4028,7 +4029,9 @@ fn geopackage_dates_are_written_and_read_as_dates() { fine.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Null, at(t)]); } assert_eq!( - crate::io::fine_dates_note(&fine.fields, &crate::io::fine_dates(fine.features.iter(), &fine.fields), "fine.gpkg").as_deref(), + crate::io::fine_dates_note(&fine.fields, &crate::io::fine_dates(fine.features.iter(), &fine.fields), "fine.gpkg") + .as_ref() + .map(crate::loss::Note::as_str), Some("fine.gpkg: 3 date-times were rounded to the millisecond, as GeoPackage stores them, in 'seen'") ); let rounded = workspace.path().join("fine.gpkg"); @@ -4083,7 +4086,7 @@ fn geopackage_dates_are_written_and_read_as_dates() { assert_eq!(crate::io::text_in_dates(moment.features.iter(), &moment.fields), [1, 1]); let text = crate::io::text_in_dates(permits.features.iter(), &permits.fields); assert_eq!( - crate::io::text_in_dates_note(&permits.fields, &text, "permits.gpkg").as_deref(), + crate::io::text_in_dates_note(&permits.fields, &text, "permits.gpkg").as_ref().map(crate::loss::Note::as_str), Some("permits.gpkg: 2 values aren't dates and were written as they are, and read back empty, in 'issued', 'seen'") ); // Dates by a declared type's own name, not a part of another. @@ -4431,6 +4434,9 @@ fn native_file_dates_preserve_zone_policy_and_fractional_seconds() { assert_eq!(back.features[0].attrs[2].to_string(), "2026-03-05T12:30:00.123456Z"); assert_eq!(back.features[1].attrs[3], Value::Text("2026-01-01T00:00:00Z".into())); let note = parquet::values_note(&ds, "out.parquet").unwrap(); + // No value is unfit, but the offsets left out are lost. + assert_eq!(note.loss, Some(crate::loss::LossCode::DroppedValue)); + let note = note.text; assert!(note.contains("2 date-times were written in UTC") && note.contains("2 date-times were written as ISO text"), "{note}"); // A replayable source feed chooses the same schema as an in-memory export. let input = fgb::write(&ds).unwrap(); @@ -4441,17 +4447,17 @@ fn native_file_dates_preserve_zone_policy_and_fractional_seconds() { assert_eq!(summary.written, 2); // Without a label of their own: the export adds its path once. assert_eq!( - summary.date_messages, + summary.date_messages.iter().map(|n| (n.text.as_str(), n.loss)).collect::>(), [ - "2 date-times were written in UTC without their original offsets, in 'instant'", - "2 date-times were written as ISO text because their column mixes zoned and unzoned values, in 'mixed'" + ("2 date-times were written in UTC without their original offsets, in 'instant'", Some(crate::loss::LossCode::DroppedValue)), + ("2 date-times were written as ISO text because their column mixes zoned and unzoned values, in 'mixed'", None) ] ); let (streamed, _) = crate::io::read_path(&path).unwrap(); assert_eq!(streamed.fields, back.fields); ds.features[0].attrs[0] = Value::Text("2026-02-30".into()); assert!(fgb::write(&ds).unwrap_err().to_string().contains("invalid date")); - let note = parquet::values_note(&ds, "bad.parquet").unwrap(); + let note = parquet::values_note(&ds, "bad.parquet").unwrap().text; assert!(note.contains("1 value couldn't be written")); let (bad, _) = crate::io::read_bytes("bad.parquet", &parquet::write(&ds).unwrap()).unwrap(); assert!(bad.features[0].attrs[0].is_null()); diff --git a/crates/data/src/unplaced_out_tests.rs b/crates/data/src/unplaced_out_tests.rs index 9e8316a018..d06f6d0938 100644 --- a/crates/data/src/unplaced_out_tests.rs +++ b/crates/data/src/unplaced_out_tests.rs @@ -58,7 +58,7 @@ fn an_export_writes_a_feature_it_cant_place_without_its_geometry_and_says_so() { let path = d.join("lines.geojson"); let (left_out, _, notes) = crate::io::write_path_to(&lines(true), &path, Crs::LonLat, &Default::default()).unwrap(); assert_eq!(left_out, 0); - assert_eq!(notes, [format!("{}: {lonlat_note}", path.display())]); + assert_eq!(notes.iter().map(crate::loss::Note::as_str).collect::>(), [format!("{}: {lonlat_note}", path.display())]); let (back, _) = crate::io::read_path(&path).unwrap(); assert_eq!(back.features.len(), 2); assert!(back.features[1].geometry.is_none()); @@ -69,7 +69,7 @@ fn an_export_writes_a_feature_it_cant_place_without_its_geometry_and_says_so() { // In its own system nothing is converted: the feature is written whole, and nothing said. let path = d.join("lines-utm.fgb"); let (left_out, _, notes) = crate::io::write_path_to(&lines(true), &path, utm31(), &Default::default()).unwrap(); - assert_eq!((left_out, notes), (0, Vec::::new())); + assert_eq!((left_out, notes.len()), (0, 0), "{notes:?}"); // A layer whose places all convert says nothing. let (_, _, notes) = crate::io::write_path_to(&lines(false), &d.join("clean.geojson"), Crs::LonLat, &Default::default()).unwrap(); assert!(notes.is_empty(), "{notes:?}"); @@ -87,7 +87,8 @@ fn a_download_writes_a_feature_it_cant_place_without_its_geometry_and_says_so() let (bytes, left_out, notes, _) = crate::io::write_bytes_noted(&lines(true), "geojson", Crs::LonLat, "lines.geojson").unwrap(); assert_eq!(left_out, 0); assert_eq!(notes.len(), 1, "{notes:?}"); - assert!(notes[0].starts_with("lines.geojson: 1 feature(s) of lines have a place"), "{}", notes[0]); + assert!(notes[0].as_str().starts_with("lines.geojson: 1 feature(s) of lines have a place"), "{:?}", notes[0]); + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::DroppedGeometry)); let (back, _) = crate::io::read_geojson(std::str::from_utf8(&bytes).unwrap(), "lines").unwrap(); assert_eq!(back.features.len(), 2); assert!(back.features[1].geometry.is_none()); diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 3034ab4563..a0c8e75373 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -84,7 +84,7 @@ fn copy(s: &mut Session) -> CmdResult { s.clipboard = Some(Clipboard { data }); s.notify(format!("Copied {n} features from {layer}"), false); if let Some(note) = rustgis_data::unplaced_note("Copied text", &layer, unplaced) { - s.notify(note, false); + s.say(note); } Ok(json!({"copied": n, "layer": layer, "text": text})) } diff --git a/crates/engine/src/cmd/gpkg.rs b/crates/engine/src/cmd/gpkg.rs index 2a5adaedaa..71f94a2cc1 100644 --- a/crates/engine/src/cmd/gpkg.rs +++ b/crates/engine/src/cmd/gpkg.rs @@ -323,10 +323,14 @@ fn save_edits(s: &mut Session, p: &Value) -> CmdResult { false, ); if !saved.skipped_fields.is_empty() { - s.notify(format!("{name}: {table} has no column for {}, so it wasn't saved", saved.skipped_fields.join(", ")), false); + // Their values aren't in the table: lost from the save. + s.say(rustgis_data::loss::Note::loss( + rustgis_data::loss::LossCode::DroppedValue, + format!("{name}: {table} has no column for {}, so it wasn't saved", saved.skipped_fields.join(", ")), + )); } if let Some(note) = rustgis_data::io::fine_dates_note(&fields, &fine_dates, &super::saved_target(&name, table)) { - s.notify(note, false); + s.say(note); } if let Some(note) = rustgis_data::source::unread_dates_note(&fields, &unread_dates) { s.say(note.map_text(|note| format!("{}: {note}, when read back after the save", super::saved_target(&name, table)))); @@ -335,7 +339,7 @@ fn save_edits(s: &mut Session, p: &Value) -> CmdResult { s.say(note.map_text(|note| format!("{}: {note}, when read back after the save", super::saved_target(&name, table)))); } if let Some(note) = rustgis_data::io::utc_dates_note(&fields, &utc_dates, &super::saved_target(&name, table)) { - s.notify(note, false); + s.say(note); } s.retain_written_notices(written); Ok(json!({"saved": true, "inserted": saved.inserted.len(), "updated": saved.updated, "deleted": saved.deleted, diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 7400cc3f17..142b0ba1e8 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -966,7 +966,7 @@ fn package_map(s: &mut Session, mobile: bool, tol: f64, linked: &mut rustgis_dat s.notify(said, false); } if let Some(said) = rustgis_data::unplaced_note("Mobile map package", &unplaced.1.join(", "), unplaced.0) { - s.notify(said, false); + s.say(said); } Ok(archive) } @@ -1002,7 +1002,7 @@ fn package_gp(s: &mut Session) -> Result, String> { } let archive = rustgis_data::zip::write(&entries)?; if let Some(said) = rustgis_data::unplaced_note("Geoprocessing package", &unplaced.1.join(", "), unplaced.0) { - s.notify(said, false); + s.say(said); } Ok(archive) } @@ -1652,7 +1652,7 @@ fn mesh_notices(s: &mut Session, mesh: &Mesh) { s.notify(format!("Skipped {} line part(s) with a single vertex", mesh.short_lines), false); } if let Some(note) = rustgis_data::unplaced_note("The 3D model", &mesh.layer, mesh.unplaced) { - s.notify(note, false); + s.say(note); } if mesh.default_heights > 0 { s.notify(format!("{} feature(s) without a numeric height used the default height instead", mesh.default_heights), false); diff --git a/crates/engine/src/cmd/pg.rs b/crates/engine/src/cmd/pg.rs index 98230f836b..6d20c3e219 100644 --- a/crates/engine/src/cmd/pg.rs +++ b/crates/engine/src/cmd/pg.rs @@ -169,10 +169,14 @@ fn save_edits(s: &mut Session, p: &Value) -> CmdResult { false, ); if !saved.skipped_fields.is_empty() { - s.notify(format!("{name}: {table} has no column for {}, so it wasn't saved", saved.skipped_fields.join(", ")), false); + // Their values aren't in the table: lost from the save, as a GeoPackage save says. + s.say(rustgis_data::loss::Note::loss( + rustgis_data::loss::LossCode::DroppedValue, + format!("{name}: {table} has no column for {}, so it wasn't saved", saved.skipped_fields.join(", ")), + )); } for note in postgis::saved_dates_notes(&fields, &saved, &super::saved_target(&name, &table)) { - s.notify(note, false); + s.say(note); } s.retain_written_notices(written); Ok(json!({ diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 236c37e0d3..4d0a400a9d 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -667,10 +667,11 @@ pub fn coalesce_read_zm(notes: &mut rustgis_data::loss::Notes, file: &str, ds: & /// What a GeoPackage export of `ds` says of its dates: date-times written in UTC, and text in /// date fields that isn't a date, and rounded to the millisecond; for a FlatGeobuf, its date fields with no values. Nothing for /// another format, or when there was none. -pub fn gpkg_dates_note(ds: &rustgis_data::Dataset, ext: &str, path: &str) -> Vec { +pub fn gpkg_dates_note(ds: &rustgis_data::Dataset, ext: &str, path: &str) -> Vec { use rustgis_data::io::{fine_dates, fine_dates_note, offset_dates, text_in_dates, text_in_dates_note, utc_dates_note}; if ext == "fgb" { return rustgis_data::io::fgb_empty_dates_note(&ds.fields, &rustgis_data::io::written_values(ds.features.iter(), &ds.fields), path) + .map(rustgis_data::loss::Note::plain) .into_iter() .collect(); } @@ -753,11 +754,11 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: if ext == "fgb" { dates.extend(rustgis_data::io::fgb_empty_dates_note(&layer.fields, &e.written_values, path)); } - dates.extend(e.date_messages.iter().map(|n| format!("{path}: {n}"))); + dates.extend(e.date_messages.iter().map(|n| n.clone().map_text(|t| format!("{path}: {t}")))); dates.extend( e.read_notes.iter().map(|n| n.clone().map_text(|t| format!("{path}: {}: {t} when read for the export", layer.name))), ); - let mut format_notes = e.csv.notes(&ds.fields, path); + let mut format_notes: rustgis_data::loss::Notes = e.csv.notes(&ds.fields, path).into(); format_notes.extend(e.csv.coordinates_note_in(&ds.fields, path, crs)); format_notes.extend(rustgis_data::io::unplaced_export_note(path, &layer.name, e.unplaced, crs)); // Text that reading the file back changes: CSV reads a blank cell as null; KML and GPX trim @@ -795,7 +796,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: notes.extend(moved); // A Shapefile (`.shp`, or zipped to `.zip`) cuts field names to dBase's. let shapefile = matches!(ext.as_str(), "shp" | "zip"); - let mut dbf_notes = Vec::new(); + let mut dbf_notes = rustgis_data::loss::Notes::new(); if shapefile { dbf_notes.extend(rustgis_data::io::shapefile_names_note(&ds.fields, path)); dbf_notes.extend(rustgis_data::io::shapefile_values_notes(ds, path)); @@ -811,14 +812,17 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, project: said.extend(rustgis_data::io::left_out_note(path, &ext, left_out)); said.extend(format_notes); if skipped > 0 { - said.push(format!("{path}: {skipped} rows couldn't be read and were left out")); + said.push(super::whole::unread_note(path, skipped)); } said.extend(notes); said.extend(dbf_notes); said.extend(unfit); said.extend(dates); if shapefile && rustgis_data::raster::wkt::to_wkt(crs).is_none() { - said.push(format!("{path}: no .prj written, as {} has no WKT form", crs.label())); + said.push(rustgis_data::loss::Note::loss( + rustgis_data::loss::LossCode::DroppedCrsName, + format!("{path}: no .prj written, as {} has no WKT form", crs.label()), + )); } said.push(format!("Exported {path}")); let answer = json!({"path": path, "features": written, "leftOut": left_out, "crs": crs.label()}); @@ -901,7 +905,8 @@ pub(crate) fn query_export_note( pub(crate) fn notify_null_numbers(s: &mut Session, path: &str, count: usize) { if let Some(note) = null_numbers_note(path, count) { let mark = s.notice_mark(); - s.notify_text(note, false); + // Each such value is lost from the file. + s.notify_loss(rustgis_data::loss::LossCode::DroppedValue, note); s.retain_written_notices(mark); } } diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index d7d0370aef..dfae39f803 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -256,7 +256,7 @@ impl Unplaced { fn say(self, s: &mut Session, what: &str) { if let Some(note) = rustgis_data::unplaced_note(what, &self.layers.join(", "), self.n) { - s.notify(note, false); + s.say(note); } } } diff --git a/crates/engine/src/cmd/whole.rs b/crates/engine/src/cmd/whole.rs index 7aebf28322..ceba213e48 100644 --- a/crates/engine/src/cmd/whole.rs +++ b/crates/engine/src/cmd/whole.rs @@ -81,7 +81,7 @@ impl Unread { /// date-times rounded to the microsecond (nothing when there were none). pub(crate) fn say(&self, s: &mut Session) { if self.rows > 0 { - s.warn(unread_notice(&self.layer, self.rows)); + s.say(unread_note(&self.layer, self.rows)); } for note in [&self.dates, &self.rounded].into_iter().flatten() { s.say(note.clone().prefixed(&self.layer)); @@ -93,7 +93,7 @@ impl Unread { /// What [`Unread::say`] says, as lines: for a tool's messages. pub(crate) fn lines(&self) -> rustgis_data::loss::Notes { - let rows = (self.rows > 0).then(|| rustgis_data::loss::Note::plain(unread_notice(&self.layer, self.rows))); + let rows = (self.rows > 0).then(|| unread_note(&self.layer, self.rows)); let dates = [&self.dates, &self.rounded].into_iter().flatten().map(|n| n.clone().prefixed(&self.layer)); let mut lines: rustgis_data::loss::Notes = rows.into_iter().chain(dates).collect(); lines.extend(self.messages.iter().cloned()); @@ -163,7 +163,13 @@ pub(crate) fn load_into(l: &mut Layer) -> Result { Ok(Unread::of(name, unread)) } -/// The notice for `unread` rows of `layer`'s source that couldn't be read. +/// The notice, with its code, that `unread` rows of `layer`'s source couldn't be read and are left +/// out. [`unread_notice`] gives the same text for an error that names it. +pub fn unread_note(layer: &str, unread: usize) -> rustgis_data::loss::Note { + rustgis_data::loss::Note::loss(rustgis_data::loss::LossCode::DroppedFeature, unread_notice(layer, unread)) +} + +/// The text of [`unread_note`]. pub fn unread_notice(layer: &str, unread: usize) -> String { match unread { 1 => format!("{layer}: 1 row couldn't be read and was left out"), diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index b621a4cc6e..5be2dcdbc4 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -2675,7 +2675,7 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result 0 { - notes.push(format!("{path}: {} rows couldn't be read and were left out", result.skipped)); + notes.push(super::whole::unread_note(&path, result.skipped)); } notes.extend(rustgis_data::io::unplaced_export_note(&path, &ds.name, result.unplaced, rustgis_data::raster::Crs::LonLat)); notes.extend( @@ -2712,7 +2712,7 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result 0 { - notes.push(format!("{path}: {} rows couldn't be read and were left out", unreadable.rows)); + notes.push(super::whole::unread_note(&path, unreadable.rows)); } notes.extend(super::share::read_notes(&path, &ds.name, &unreadable)); (notes, rustgis_data::export::numbers_written_as_null(&ds.features, &ds.fields, format), report) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e0169b007a..d3eae32df3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -47198,8 +47198,13 @@ fn a_streamed_export_counts_the_rows_it_could_not_read() { let mark = s.notice_mark(); let exported = s.run("share.exportLayer", &json!({"layer": id, "path": fixture.dir.join(format!("out.{ext}"))})).unwrap(); assert_eq!(exported["features"].as_u64(), Some(3), "{ext}"); - let notices: Vec<_> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert!(notices.iter().any(|n| n.contains("1 rows couldn't be read")), "{ext}: {notices:?}"); + let notices: Vec<_> = s.notices_since(mark).iter().map(|n| (n.text.clone(), n.loss())).collect(); + assert!( + notices + .iter() + .any(|(n, loss)| n.contains("1 row couldn't be read") && *loss == Some(rustgis_data::loss::LossCode::DroppedFeature)), + "{ext}: {notices:?}" + ); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b5f8fa0d35..55c5770cb1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5626,17 +5626,19 @@ impl RustGisApp { dbf_notes.extend(io::dates_as_text_note(&ds.fields, &name)); dbf_notes.extend(rustgis_engine::cmd::share::gpkg_dates_note(&ds, &ext, &name)); if lost.rows > 0 { - dbf_notes.push(rustgis_engine::cmd::whole::unread_notice(&name, lost.rows)); + dbf_notes.push(rustgis_engine::cmd::whole::unread_note(&name, lost.rows)); } dbf_notes.extend(rustgis_engine::cmd::share::read_notes(&name, &l.name, &lost)); // CSV holds a point a row, GPX a name for each feature and no areas; reading text back, CSV reads blanks as null and KML and GPX trim it. dbf_notes.extend(io::export_losses_notes(&ds, &ext, io::name_field(&ds), &name).map_err(|e| e.to_string())?); drop(ds); - if let Some(note) = io::left_out_note(&name, &ext, left_out) { - self.session.notify(note, false); - } + // Said only once the download is taken, as the other notes are. + dbf_notes.extend(io::left_out_note(&name, &ext, left_out)); if ext == "zip" && rustgis_engine::data::raster::wkt::to_wkt(crs).is_none() { - self.session.notify(format!("{name}: no .prj written, as {} has no WKT form", crs.label()), false); + dbf_notes.push(rustgis_engine::data::loss::Note::loss( + rustgis_engine::data::loss::LossCode::DroppedCrsName, + format!("{name}: no .prj written, as {} has no WKT form", crs.label()), + )); } if self.download(&name, bytes) { rustgis_engine::cmd::share::notify_export_query(&mut self.session, &name, &layer_name, &query_report); diff --git a/docs/cli.md b/docs/cli.md index 08674c5006..f9e48c7cba 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -157,20 +157,22 @@ An `--allow` that names no kind or code is refused with status 2, as is `--allow | Code | What to do | |---|---| | `dropped.legend` | Use a service with short HTTP or HTTPS addresses for its legend pictures. | -| `dropped.ring` | Correct the unreadable polygon ring in the source. | +| `dropped.ring` | Correct the unreadable polygon ring in the source, or write to a format that holds holes, such as GeoPackage. | | `dropped.extra-attributes` | Add fields for the extra attribute values or remove those values from the input. | | `dropped.time` | Write to a date-time field to keep the time of day. | | `dropped.value` | Correct the value or use a destination field that can hold it. | | `dropped.calculation-result` | Correct the expression or check the input rows named in the notice. | | `dropped.zm` | Keep the source file where heights or measures matter: RustGIS keeps x and y only. | -| `dropped.crs-name` | Keep the source file's coordinate system definition with the export. | +| `dropped.crs-name` | Keep the source file's coordinate system definition with the export, or export in WGS 84, which every format can name. | | `dropped.feature` | Correct those features in the source, or read the source in the way the notice suggests. | | `dropped.geometry` | Correct the geometry in the source, or give the coordinate system its coordinates are in. | | `dropped.over-limit` | Read less at once, such as by filtering or clipping the source first. | | `changed.truncated` | Use a decimal field to keep the fractional part. | +| `changed.field-name` | Use field names the format holds: at most 10 bytes and unique ignoring case for a Shapefile, unique ignoring case for a GeoPackage. | +| `changed.cut` | Shorten the text to what the format holds (254 bytes for a Shapefile; nothing past a NUL character), or write to a format without the limit, such as GeoPackage. | | `changed.body` | Export in the layer's own coordinate system, which keeps its body. | | `changed.encoding` | Put a .cpg file naming the file's own encoding beside it. | -| `changed.rounded` | Keep the source file where times finer than a microsecond matter. | +| `changed.rounded` | Keep the source file where finer values matter, or write to a format that holds them (times finer than the format keeps, or numbers past a dBase field's precision). | | `changed.position` | Export in a coordinate system that holds the positions, such as WGS 84. | | `approximated.datum` | Export in the layer's own coordinate system, or give that system with a known transformation to WGS 84. | | `approximated.curve` | Keep the source file where exact curves matter: RustGIS draws curves as straight segments. |