From 5514a3a099ee4e30fa0a6bf9f6ae999438e66b37 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:10:52 +0700 Subject: [PATCH] xlsx: fix main after the ODS cutover (clippy, empty first sheet, values, package checks) (#4518) * xlsx: clear the two clippy errors the ODS cutover left on main SheetNames::insert lost its only caller when the ODS reader moved to craft-ods, and craft_ods::Value::Text already holds an Arc. * xlsx: ODS import keeps only the ODS tables, with unique valid names The craft-ods cutover (#4513) built the workbook with Workbook::new(), which already holds an empty Sheet1, and appended the ODS tables after it. Opening an ODS file therefore showed an empty first sheet, and ods_import_keeps_cached_values_and_reports_limits (plus the reader's own sheets[0] tests) failed. It also stopped making sheet names unique and valid, so two tables named Data and data became two sheets with clashing names. Clear the default sheet as the XLSX, XLS and XLSB readers do, and name sheets through SheetNames again, as the reader did before the cutover. That restores SheetNames::insert, which the previous commit removed while it was unused. Co-Authored-By: Claude Opus 5.5 * xlsx: ODS import keeps unreadable values as text and the exact mimetype check Three more behaviours the craft-ods cutover (#4513) dropped, each covered by an ods_tests case that has failed since: - A cell whose typed value cannot be read (an unparsable number or date, a calcext error cache, a formula without a result) was skipped or marked unavailable. It keeps its displayed text again, else its raw value, with the same warning as before. - Number formats are the old ones again: [h]:mm:ss.000 for durations and yyyy-mm-dd hh:mm:ss.000 for dates with a time. They are applied only when the typed value was read. - read_ods checks the exact mimetype first, as sniff does; craft-ods alone accepted one with a trailing space. The encryption case now writes its encryption-data inside the content.xml file entry, where LibreOffice puts it and where craft-odf looks for it. A bare one under the manifest root encrypts nothing. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: FredApps Co-authored-by: Claude Opus 5.5 --- crates/xlsx/src/ods.rs | 59 +++++++++++++++++++++--------- crates/xlsx/src/tests/ods_tests.rs | 17 ++++++++- 2 files changed, 57 insertions(+), 19 deletions(-) diff --git a/crates/xlsx/src/ods.rs b/crates/xlsx/src/ods.rs index e208bc6ce..cdf2dff54 100644 --- a/crates/xlsx/src/ods.rs +++ b/crates/xlsx/src/ods.rs @@ -8,6 +8,7 @@ use gridcraft_core::{CellError, CellRef, RangeRef, Value}; use gridcraft_model::{Cell, NumFmt, Sheet, StyleId, Workbook}; use crate::package::MAX_ENTRIES; +use crate::read::SheetNames; use crate::{IoError, ReadReport}; const MIME: &[u8] = b"application/vnd.oasis.opendocument.spreadsheet"; @@ -32,6 +33,10 @@ pub(crate) fn has_mimetype(bytes: &[u8]) -> bool { /// imported as constants, so editing their inputs does not recalculate the original formula. /// Always inspect the returned warnings. Saving to ODS is not supported. pub fn read_ods(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { + // The exact mimetype, as `sniff` requires: craft-ods alone accepts some near misses. + if !has_mimetype(bytes) { + return Err(IoError::Format("missing or invalid ODS mimetype".into())); + } let book = craft_ods::read(bytes, &craft_ods::Options::default()).map_err(map_error)?; if book.sheets.is_empty() { return Err(IoError::Format("ODS contains no worksheets".into())); @@ -40,7 +45,10 @@ pub fn read_ods(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { return Err(IoError::TooLarge("ODS contains more than 1024 sheets".into())); } + // `Workbook::new` starts with an empty Sheet1; the ODS tables are the only sheets. let mut wb = Workbook::new(); + wb.sheets.clear(); + let mut names = SheetNames::default(); let mut report = ReadReport::default(); report.warn("ODS data-only import: formulas become their saved results and will not recalculate. Source formatting, charts, images and other features are not imported. Save a new .xlsx file; ODS saving is not supported."); @@ -48,32 +56,49 @@ pub fn read_ods(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { let mut warned_unavailable = false; for src_sheet in book.sheets { - let mut sheet = Sheet::new(&src_sheet.name); + let mut name = names.unique(src_sheet.name.trim_matches('\''), wb.sheets.len()); + if wb.check_sheet_name(&name, None).is_err() { + name = wb.next_sheet_name(); + names.insert(&name); + } + let mut sheet = Sheet::new(name); if !warned_rename && sheet.name != src_sheet.name { warned_rename = true; report.warn("Some ODS sheet names were shortened or renamed to valid, unique XLSX sheet names."); } for (coord, src_cell) in src_sheet.cells { - let value = match src_cell.value() { - Some(v) => map_value(v), - None if src_cell.formula.is_some() => { - if !warned_unavailable { - warned_unavailable = true; - report.warn("Some ODS values or formula caches were unsupported or missing; their displayed text (or raw value) was kept as text. A formula without either is marked [Unavailable ODS formula result]."); - } - Value::Text(Arc::from("[Unavailable ODS formula result]")) + // A typed value that cannot be read (an unparsable number or date, an error cache, + // a formula without a result) keeps what the cell showed, else its raw value. + let Some(value) = src_cell.value().map(map_value) else { + if !warned_unavailable { + warned_unavailable = true; + report.warn("Some ODS values or formula caches were unsupported or missing; their displayed text (or raw value) was kept as text. A formula without either is marked [Unavailable ODS formula result]."); } - None => continue, + let text = if !src_cell.text.is_empty() { + src_cell.text.as_str() + } else if let Some(raw) = src_cell.raw.as_deref() { + raw + } else if src_cell.formula.is_some() { + "[Unavailable ODS formula result]" + } else { + "[Unsupported ODS value]" + }; + sheet.set_cell(CellRef::new(coord.row, coord.col), Cell::styled(Value::Text(Arc::from(text)), StyleId::DEFAULT)); + continue; }; - let style_id = match src_cell.value_type { - Some(craft_ods::ValueType::Date) => wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new("yyyy-mm-dd")), - Some(craft_ods::ValueType::Time) => wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new("[h]:mm:ss")), - Some(craft_ods::ValueType::Percentage) => wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new("0.00%")), - Some(craft_ods::ValueType::Currency) => wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new("#,##0.00")), - _ => StyleId::DEFAULT, + let format = match src_cell.value_type { + Some(craft_ods::ValueType::Date) => { + let with_time = src_cell.raw.as_deref().and_then(craft_ods::date_serial).is_some_and(|(_, time)| time); + Some(if with_time { "yyyy-mm-dd hh:mm:ss.000" } else { "yyyy-mm-dd" }) + } + Some(craft_ods::ValueType::Time) => Some("[h]:mm:ss.000"), + Some(craft_ods::ValueType::Percentage) => Some("0.00%"), + Some(craft_ods::ValueType::Currency) => Some("#,##0.00"), + _ => None, }; + let style_id = format.map_or(StyleId::DEFAULT, |code| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code))); let target_coord = CellRef::new(coord.row, coord.col); sheet.set_cell(target_coord, Cell::styled(value, style_id)); @@ -103,7 +128,7 @@ fn map_value(v: craft_ods::Value) -> Value { match v { craft_ods::Value::Empty => Value::Empty, craft_ods::Value::Number(n) => Value::Number(n), - craft_ods::Value::Text(s) => Value::Text(Arc::from(s)), + craft_ods::Value::Text(s) => Value::Text(s), craft_ods::Value::Bool(b) => Value::Bool(b), craft_ods::Value::Error(e) => Value::Error(map_cell_error(e)), } diff --git a/crates/xlsx/src/tests/ods_tests.rs b/crates/xlsx/src/tests/ods_tests.rs index bac55efeb..fff81ca16 100644 --- a/crates/xlsx/src/tests/ods_tests.rs +++ b/crates/xlsx/src/tests/ods_tests.rs @@ -111,6 +111,19 @@ fn ods_repeats_merges_sheet_names_and_empty_tail_remain_sparse() { assert_eq!(wb.sheets[1].value(CellRef::new(0, 0)), text("second sheet")); } +#[test] +fn ods_tables_are_the_only_sheets_with_unique_valid_names() { + let cell = r#""#; + let bytes = ods(&format!( + r#"{cell}{cell}{cell}"# + )); + let (wb, report) = read_ods(&bytes).unwrap(); + let names: Vec<&str> = wb.sheets.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["Data", "data (2)", "ab"]); + assert!(wb.sheets.iter().all(|s| s.value(CellRef::new(0, 0)) == Value::Number(1.0))); + assert!(report.warnings.iter().any(|w| w.contains("renamed"))); +} + #[test] fn ods_dates_and_durations_use_formats_and_unsupported_values_stay_text() { let bytes = row(r#" @@ -158,8 +171,8 @@ fn ods_rejects_bad_packages_encryption_and_truncated_xml() { for mime in [b"application/zip".as_slice(), b"application/vnd.oasis.opendocument.spreadsheet "] { assert!(read_ods(&make_zip(&[("mimetype", mime), ("content.xml", xml.as_bytes())])).is_err()); } - let encrypted = - br#""#; + // As LibreOffice writes it: the encryption data belongs to the encrypted file's entry. + let encrypted = br#""#; assert!( read_ods(&make_zip(&[("mimetype", MIME), ("META-INF/manifest.xml", encrypted), ("content.xml", xml.as_bytes())])) .unwrap_err()