Save an XLSX opened under an unknown extension back to its own file as XLSX (#878)

This commit is contained in:
Marco Arnulfo 2026-10-13 05:14:30 +02:00
parent 9bb85ab9af
commit 522ede0fca
4 changed files with 57 additions and 4 deletions

View File

@ -75,7 +75,11 @@ fn open(s: &mut Session, p: &Json) -> Result<Json> {
{
s.close_document(0);
}
let i = s.add_document(DocState::new(wb, path, title));
let mut doc = DocState::new(wb, path, title);
if crate::io::FileKind::from_path(&name).is_none() && gridcraft_xlsx::sniff(&bytes) == gridcraft_xlsx::Format::Xlsx {
doc.content_kind = Some(crate::io::FileKind::Xlsx);
}
let i = s.add_document(doc);
// The decrypted-workbook notice is for the info bar, not a message box.
let shown: Vec<&str> = warnings.iter().map(String::as_str).filter(|w| *w != crate::io::DECRYPTED_NOTICE).collect();
if !shown.is_empty() {
@ -105,10 +109,16 @@ fn save(s: &mut Session, p: &Json) -> Result<Json> {
return super::print::export_pdf(s, &json!({"path": path}));
}
let d = s.doc_mut()?;
let bytes = crate::io::save_bytes(&d.wb, &path)?;
// The document's own file keeps the format its content had when opened; any other path
// goes by its extension.
let kind = crate::io::FileKind::from_path(&path).or(d.content_kind.filter(|_| d.path.as_deref() == Some(path.as_str())));
let bytes = match kind {
Some(kind) => crate::io::save_bytes_as(&d.wb, &path, kind)?,
None => crate::io::save_bytes(&d.wb, &path)?,
};
crate::io::write_file(&path, &bytes)?;
// Only a full-fidelity format clears the dirty flag and becomes the document's file.
if matches!(crate::io::FileKind::from_path(&path), Some(crate::io::FileKind::Xlsx | crate::io::FileKind::Json)) {
if matches!(kind, Some(crate::io::FileKind::Xlsx | crate::io::FileKind::Json)) {
d.saved = d.wb.clone();
d.path = Some(path.clone());
}

View File

@ -153,13 +153,18 @@ fn rename_first_sheet(wb: &mut Workbook, path: &str) {
/// Encodes a workbook in the format chosen by `path`'s extension.
pub fn save_bytes(wb: &Workbook, path: &str) -> Result<Vec<u8>> {
let sheet = wb.active_sheet;
// An unknown or missing extension is refused rather than written as an XLSX under that name:
// a typo like `.cvs` would otherwise produce a file no other app recognises.
let Some(kind) = FileKind::from_path(path) else {
let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path);
return Err(EngineError::Other(format!("{name}: unknown file format. Save as .xlsx, .csv, .tsv, .json or .html.")));
};
save_bytes_as(wb, path, kind)
}
/// Encodes a workbook as `kind`, whatever `path`'s extension says.
pub fn save_bytes_as(wb: &Workbook, path: &str, kind: FileKind) -> Result<Vec<u8>> {
let sheet = wb.active_sheet;
match kind {
// The extension picks the package kind; only the macro-enabled kinds (.xlsm, .xltm) carry
// the VBA project, so any other name saves without it, as Excel does.

View File

@ -108,6 +108,9 @@ pub struct DocState {
pub sheet_selections: Vec<Selection>,
/// Allow Edit Ranges unlocked with their password in this session: (sheet name, title).
pub unlocked_ranges: Vec<(String, String)>,
/// The format `path`'s content was recognised as when its extension doesn't name one (an
/// XLSX called `budget.dat`): Save writes it back in that format.
pub content_kind: Option<io::FileKind>,
}
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
@ -132,6 +135,7 @@ impl DocState {
title,
sheet_selections: vec![],
unlocked_ranges: vec![],
content_kind: None,
}
}
pub fn is_dirty(&self) -> bool {

View File

@ -1544,6 +1544,40 @@ fn saving_to_an_unknown_extension_is_refused() {
std::fs::remove_dir_all(dir).unwrap();
}
/// An XLSX opened by its content under an unknown extension (`budget.dat`) saves back to its own
/// file as XLSX; a Save As to another unknown extension is still refused.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn an_xlsx_opened_under_an_unknown_extension_saves_back_as_xlsx() {
#[allow(clippy::disallowed_methods)] // native-only test: a unique temp dir name
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("gridcraft-dat-{}-{nonce}", std::process::id()));
std::fs::create_dir(&dir).unwrap();
let path = dir.join("budget.dat");
let mut src = s();
src.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
std::fs::write(&path, crate::io::save_bytes(&src.doc().unwrap().wb, "book.xlsx").unwrap()).unwrap();
let mut s = s();
s.execute("file.open", json!({"path": path})).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": "2"})).unwrap();
s.execute("file.save", json!({})).unwrap();
assert!(!s.doc().unwrap().is_dirty());
let bytes = std::fs::read(&path).unwrap();
assert_eq!(gridcraft_xlsx::sniff(&bytes), gridcraft_xlsx::Format::Xlsx);
let (wb, _) = crate::io::open_bytes("book.xlsx", &bytes).unwrap();
assert_eq!(wb.active().unwrap().value(CellRef::parse("A1").unwrap()), Value::Number(2.0));
assert!(s.execute("file.saveAs", json!({"path": dir.join("copy.foo")})).is_err());
assert!(!dir.join("copy.foo").exists());
// A text file under an unknown extension opens as CSV: Save doesn't turn it into an XLSX.
let notes = dir.join("notes.dat");
std::fs::write(&notes, "a,b\r\n").unwrap();
s.execute("file.open", json!({"path": notes})).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": "c"})).unwrap();
assert!(s.execute("file.save", json!({})).is_err());
assert_eq!(std::fs::read_to_string(&notes).unwrap(), "a,b\r\n");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn validation_formulas_are_relative_and_see_the_new_value() {
let mut s = s();