Skip to content

Commit 2f18c32

Browse files
authored
fix(data): report spreadsheet error cells read as empty (#2670)
* fix(data): report spreadsheet error cells read as empty * fix(data): report error headings and omitted spreadsheet rows
1 parent 8265123 commit 2f18c32

4 files changed

Lines changed: 129 additions & 12 deletions

File tree

‎ROADMAP.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ A result is right, or RustGIS says what it lost or assumed
7373
nodes or ways the file doesn't hold, and inner rings outside every outer one; and the text
7474
readers' losses listed as `Silent` in `crates/engine/tests/integration/never_silent_reading.rs`, among them
7575
each vertex's Z in DXF and unreadable coordinates, holes and parts in KML, GeoRSS, MapInfo and
76-
DXF, plus geometry-collection members in XLSX/ODS/XLS/XLSB, error-valued attribute cells in XLSX,
76+
DXF, plus geometry-collection members in XLSX/ODS/XLS/XLSB,
7777
and attribute fields/values in XLSB short-cell workbooks (the original SheetJS 0.18.5 clean
7878
workbook retains its point but no attributes, without a notice). A fix makes
7979
its case `Said` _(open)_.

‎crates/data/src/sheets.rs‎

Lines changed: 117 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,33 @@ pub fn read(bytes: &[u8], name: &str, sheet: Option<&str>, opts: &CsvOptions) ->
5252
let g = grid(bytes, sheet)?;
5353
let title = if g.names.len() > 1 { format!("{name} {}", g.pick) } else { name.to_string() };
5454
let (ds, mut report) = read_rows(&g.headers, &g.rows, 0, &title, opts, Some((&g.dates, &g.phantom_dates)))?;
55+
let errors: usize = g.error_cells.iter().sum();
5556
let rounded: usize = g.rounded_dates.iter().sum();
57+
let fields: Vec<Field> =
58+
if errors > 0 || rounded > 0 { g.headers.iter().map(|h| Field::new(h, FieldType::Text)).collect() } else { vec![] };
59+
if errors > 0 {
60+
let what = if errors == 1 { "1 spreadsheet error cell was".to_string() } else { format!("{errors} spreadsheet error cells were") };
61+
let mut message = format!("{what} read as empty, in {}", crate::io::named_fields(&fields, &g.error_cells));
62+
let headings: usize = g.header_error_cells.iter().sum();
63+
if headings > 0 {
64+
let what = if headings == 1 {
65+
"1 erroneous heading was named by its column letter".to_string()
66+
} else {
67+
format!("{headings} erroneous headings were named by their column letters")
68+
};
69+
message.push_str(&format!("; {what}, {}", crate::io::named_fields(&fields, &g.header_error_cells)));
70+
}
71+
if g.empty_error_rows > 0 {
72+
let what = if g.empty_error_rows == 1 {
73+
"1 otherwise empty row with error cells was omitted".to_string()
74+
} else {
75+
format!("{} otherwise empty rows with error cells were omitted", g.empty_error_rows)
76+
};
77+
message.push_str(&format!("; {what}"));
78+
}
79+
report.messages.push(message);
80+
}
5681
if rounded > 0 {
57-
let fields: Vec<Field> = g.headers.iter().map(|h| Field::new(h, FieldType::Text)).collect();
5882
report.messages.push(format!(
5983
"{rounded} serial date values were rounded to the nearest microsecond, in {}",
6084
crate::io::named_fields(&fields, &g.rounded_dates)
@@ -82,6 +106,12 @@ struct Grid {
82106
rows: Vec<Vec<String>>,
83107
dates: Vec<Option<FieldType>>,
84108
rounded_dates: Vec<usize>,
109+
/// Source cells whose spreadsheet error value became empty text, per source column.
110+
error_cells: Vec<usize>,
111+
/// Error-valued headings replaced with column letters, per source column.
112+
header_error_cells: Vec<usize>,
113+
/// Otherwise empty rows with errors, omitted by the existing blank-row rule.
114+
empty_error_rows: usize,
85115
/// Per column that isn't one of dates, the serial-60 cells read as empty.
86116
phantom_dates: Vec<usize>,
87117
}
@@ -173,10 +203,20 @@ fn grid_unguarded(mut wb: Sheets<Cursor<&[u8]>>, sheet: Option<&str>) -> Result<
173203
// as one that isn't a date (null, and counted); in a column of other things it is read as
174204
// empty and counted here, as it would not be text of a day.
175205
let mut phantom_dates = vec![0usize; w];
176-
let mut rows = range.rows().map(|r| {
177-
r.iter()
206+
let mut error_cells = vec![0usize; w];
207+
let mut rows = range.rows().enumerate().map(|(row, r)| {
208+
let mut had_error = false;
209+
let cells = r
210+
.iter()
178211
.enumerate()
179212
.map(|(k, d)| match (d, dates.get(k)) {
213+
(Data::Error(_), _) => {
214+
had_error = true;
215+
if let Some(n) = error_cells.get_mut(k) {
216+
*n += 1;
217+
}
218+
String::new()
219+
}
180220
(Data::DateTime(t), Some(None)) if is_phantom_day(t) => {
181221
if let Some(n) = phantom_dates.get_mut(k) {
182222
*n += 1;
@@ -185,23 +225,41 @@ fn grid_unguarded(mut wb: Sheets<Cursor<&[u8]>>, sheet: Option<&str>) -> Result<
185225
}
186226
_ => cell(d),
187227
})
188-
.collect::<Vec<String>>()
228+
.collect::<Vec<String>>();
229+
(row, cells, had_error)
189230
});
231+
let mut empty_error_rows = 0;
232+
let mut keep = |(_, cells, had_error): &(usize, Vec<String>, bool)| {
233+
let nonempty = cells.iter().any(|c| !c.trim().is_empty());
234+
if !nonempty && *had_error {
235+
empty_error_rows += 1;
236+
}
237+
nonempty
238+
};
190239
// The first row with anything in it names the columns.
191-
let headers: Vec<String> = rows.by_ref().find(|r| r.iter().any(|c| !c.trim().is_empty())).unwrap_or_default();
240+
let (header_row, headers, _) = rows.by_ref().find(&mut keep).unwrap_or_default();
192241
if headers.is_empty() {
193242
return Err(DataError::Format(format!("sheet '{pick}' is empty")));
194243
}
195244
// Columns without a heading are named by their letter, as the spreadsheet shows them (the
196245
// range starts at its first column with anything in it).
197246
let first_col = range.start().map(|(_, c)| c as usize).unwrap_or(0);
247+
let source_header = range.rows().nth(header_row);
248+
let mut header_error_cells = vec![0usize; w];
198249
let headers: Vec<String> = headers
199250
.into_iter()
200251
.enumerate()
201-
.map(|(i, h)| if h.trim().is_empty() { column_letter(first_col + i) } else { h.trim().to_string() })
252+
.map(|(i, h)| {
253+
if matches!(source_header.and_then(|r| r.get(i)), Some(Data::Error(_)))
254+
&& let Some(n) = header_error_cells.get_mut(i)
255+
{
256+
*n = 1;
257+
}
258+
if h.trim().is_empty() { column_letter(first_col + i) } else { h.trim().to_string() }
259+
})
202260
.collect();
203-
let rows: Vec<Vec<String>> = rows.filter(|r| r.iter().any(|c| !c.trim().is_empty())).collect();
204-
Ok(Grid { names, pick, headers, rows, dates, rounded_dates, phantom_dates })
261+
let rows = rows.filter(keep).map(|(_, cells, _)| cells).collect();
262+
Ok(Grid { names, pick, headers, rows, dates, rounded_dates, error_cells, header_error_cells, empty_error_rows, phantom_dates })
205263
}
206264

207265
/// Check every ZIP member before calamine opens it, without suffix or case filters. ODS
@@ -747,6 +805,57 @@ mod tests {
747805
assert!(!report.messages.iter().any(|m| m.contains("isn't a date")), "{:?}", report.messages);
748806
}
749807

808+
/// Multiple errors in one column and another column count once each; blank cells don't.
809+
#[test]
810+
fn error_cells_are_counted_without_changing_other_values() {
811+
let error = r#"<c t="e"><v>#DIV/0!</v></c>"#;
812+
let book = xlsx(&[("S", &[&["id", "note", "other"], &["7", error, "kept"], &["8", error, error], &["9", "", ""]])]);
813+
let (ds, report) = read(&book, "book", None, &CsvOptions::default()).unwrap();
814+
assert_eq!(report.messages, ["3 spreadsheet error cells were read as empty, in 'note', 'other'"]);
815+
assert_eq!(report.skipped, 0);
816+
let attrs: Vec<_> = ds.features.iter().map(|f| f.attrs.clone()).collect();
817+
use crate::Value::{Int, Null, Text};
818+
assert_eq!(attrs, [vec![Int(7), Null, Text("kept".into())], vec![Int(8), Null, Null], vec![Int(9), Null, Null]]);
819+
}
820+
821+
/// Error headings still use column letters, with the lost heading counted separately.
822+
#[test]
823+
fn spreadsheet_error_headings_are_reported() {
824+
let error = r#"<c t="e"><v>#REF!</v></c>"#;
825+
for heading in ["", error] {
826+
let book = xlsx(&[("S", &[&["id", heading], &["7", "kept"]])]);
827+
let (ds, report) = read(&book, "book", None, &CsvOptions::default()).unwrap();
828+
assert_eq!(ds.fields.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["id", "B"]);
829+
assert_eq!(ds.features[0].attrs, [crate::Value::Int(7), crate::Value::Text("kept".into())]);
830+
let expected = if heading.is_empty() {
831+
vec![]
832+
} else {
833+
vec!["1 spreadsheet error cell was read as empty, in 'B'; 1 erroneous heading was named by its column letter, 'B'"]
834+
};
835+
assert_eq!(report.messages, expected);
836+
}
837+
}
838+
839+
/// Error-only rows and genuinely blank rows keep their omission behavior, but only the
840+
/// former lose source content and need a counted notice.
841+
#[test]
842+
fn spreadsheet_error_only_rows_are_counted_when_omitted() {
843+
let error = r#"<c t="e"><v>#N/A</v></c>"#;
844+
for cell in ["", error] {
845+
let book = xlsx(&[("S", &[&["id", "note"], &["7", "kept"], &[cell, cell], &["", ""], &["8", ""]])]);
846+
let (ds, report) = read(&book, "book", None, &CsvOptions::default()).unwrap();
847+
let attrs: Vec<_> = ds.features.iter().map(|f| f.attrs.clone()).collect();
848+
use crate::Value::{Int, Null, Text};
849+
assert_eq!(attrs, [vec![Int(7), Text("kept".into())], vec![Int(8), Null]]);
850+
let expected = if cell.is_empty() {
851+
vec![]
852+
} else {
853+
vec!["2 spreadsheet error cells were read as empty, in 'id', 'note'; 1 otherwise empty row with error cells was omitted"]
854+
};
855+
assert_eq!(report.messages, expected);
856+
}
857+
}
858+
750859
#[test]
751860
fn reads_sheets() {
752861
let book = xlsx(&[

‎crates/engine/testdata/reading-losses/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ exercise coordinate-system assumptions.
5858
| `book-clean.xlsx` | `POINT(1 2)` | absent | None; no command notice |
5959
| `book-z.xlsx` | `POINT Z(1 2 3)` | absent | Imports with a Z/M-loss notice |
6060
| `book-collection.xlsx` | `GEOMETRYCOLLECTION(POINT(1 2),POINT(3 4))` | absent | Silent: only the first member remains |
61-
| `book-error.xlsx` | `POINT(1 2)` | error cell (`t="e"`, value `#DIV/0!`) | Silent: the error becomes Null |
61+
| `book-error.xlsx` | `POINT(1 2)` | error cell (`t="e"`, value `#DIV/0!`) | Imports with a counted notice naming `note`; the error becomes Null |
6262

6363
The clean workbook is shared by all three pairs. All four must retain exactly one point
6464
at (1, 2), integer `id=7` and text `note=Null`, through both `sheets::read` and

‎crates/engine/tests/integration/never_silent_reading.rs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -424,7 +424,7 @@ fn cases(fixture_dir: &std::path::Path) -> Vec<Case> {
424424
"a.xlsx",
425425
include_bytes!("../../testdata/reading-losses/book-clean.xlsx"),
426426
include_bytes!("../../testdata/reading-losses/book-error.xlsx"),
427-
Silent("the error-valued note cell is read as Null"),
427+
Imported("1 spreadsheet error cell was read as empty, in 'note'"),
428428
),
429429
]);
430430

@@ -762,9 +762,17 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec<
762762
|| content == include_bytes!("../../testdata/reading-losses/book-z.ods")
763763
|| content == include_bytes!("../../testdata/reading-losses/book-z.xls")
764764
|| content == include_bytes!("../../testdata/reading-losses/book-z.xlsb");
765+
let errors = content == include_bytes!("../../testdata/reading-losses/book-error.xlsx");
766+
if errors && report.messages != ["1 spreadsheet error cell was read as empty, in 'note'"] {
767+
return Err(std::io::Error::other(format!("native spreadsheet error notice: {report:?}")));
768+
}
765769
if report.skipped != 0
766770
|| native.zm_dropped != height
767-
|| if height { report.messages.len() != 1 || !report.messages[0].contains("Z or M") } else { !report.messages.is_empty() }
771+
|| if height {
772+
report.messages.len() != 1 || !report.messages[0].contains("Z or M")
773+
} else {
774+
!errors && !report.messages.is_empty()
775+
}
768776
{
769777
return Err(std::io::Error::other(format!("native spreadsheet fixture has the wrong loss report: {report:?}")));
770778
}

0 commit comments

Comments
 (0)