From 0d524a49f4429cb14c2ea8bfb9ab01f821f1ffcf Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:27:45 -0600 Subject: [PATCH 1/9] fix(data): publishing to an upper-case Shapefile writes its .SHX and .PRJ back under their own names (#1958) Found reviewing #1958. Publishing edits to ROADS.SHP on a case-sensitive file system wrote a new ROADS.shx beside the stale ROADS.SHX, and for a projected layer a second ROADS.prj with a false note that its .prj now names the layer's system. Publish only looked for the lower-case .shx and .prj, though the reader finds .PRJ and any case of .dbf. Save As had the same problem. Now a Shapefile's parts are found once per read, publish or save, from one listing of its folder, and the reader, the streamed reader, publish, save and sync all use that. Each part is written back under the name it has; a new one takes the case of the .shp (ROADS.PRJ). Where the disk ignores case, a project naming roads.shp finds ROADS.* and keeps those names. When two spellings of a part are there, lower case wins as before, the other is kept, and reading, publishing and saving say so. Saving is refused, with nothing written, beside another .shp of the same name in another case, and in a system no .prj can describe while an old .prj is there. Publish looks at the folder again before placing the files. Sync matches names regardless of case and compares the bytes; a record from before this change that missed ROADS.SHX still publishes, and one that missed ROADS.PRJ is refused once. --- crates/data/src/dbf.rs | 32 +-- crates/data/src/io.rs | 97 +++++--- crates/data/src/lib.rs | 1 + crates/data/src/publish.rs | 430 +++++++++++++++++++++++++++++---- crates/data/src/raster/mod.rs | 20 +- crates/data/src/sidecar.rs | 365 ++++++++++++++++++++++++++++ crates/data/src/source/shp.rs | 9 +- crates/data/src/sync.rs | 147 +++++++++-- crates/engine/src/cmd/share.rs | 4 + 9 files changed, 967 insertions(+), 138 deletions(-) create mode 100644 crates/data/src/sidecar.rs diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 55492a986f..a1531c37f5 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -307,8 +307,8 @@ pub(crate) fn date(field: &[u8]) -> std::result::Result) -> Option> { - match try_read_cpg(path) { +pub(crate) fn read_cpg(cpg: Option<&std::path::Path>, notes: &mut Vec) -> Option> { + match try_read_cpg(cpg?) { Ok(bytes) => bytes, Err(e) => { notes.push(format!("Shapefile: could not read .cpg ({e}); using the .dbf code page, or UTF-8 if unavailable")); @@ -317,27 +317,21 @@ pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut Vec) -> Optio } } -/// Every ASCII case of the `.cpg` extension, the conventional spellings first: tried in turn, -/// without scanning a potentially large directory, and the first there wins. -pub(crate) const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"]; - -fn try_read_cpg(path: &std::path::Path) -> std::io::Result>> { +/// The `.cpg` at `cpg`, as [`crate::sidecar::Sidecars`] finds it beside a table. +fn try_read_cpg(cpg: &std::path::Path) -> std::io::Result>> { use std::io::Read; - for ext in CPG_SPELLINGS { - match crate::provenance::open(path.with_extension(ext)) { - Ok(file) => { - let mut bytes = Vec::new(); - (&file).take(MAX_CPG_BYTES as u64 + 1).read_to_end(&mut bytes)?; - if bytes.len() <= MAX_CPG_BYTES { - crate::provenance::buffer(&path.with_extension(ext), &file, &bytes); - } - return Ok(Some(bytes)); + match crate::provenance::open(cpg) { + Ok(file) => { + let mut bytes = Vec::new(); + (&file).take(MAX_CPG_BYTES as u64 + 1).read_to_end(&mut bytes)?; + if bytes.len() <= MAX_CPG_BYTES { + crate::provenance::buffer(cpg, &file, &bytes); } - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => return Err(e), + Ok(Some(bytes)) } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e), } - Ok(None) } #[cfg(test)] diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index caf0f8b1a2..84428f913a 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -386,7 +386,7 @@ pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> { "dbf" => { check_size(path)?; let mut notes = Vec::new(); - let cpg = crate::dbf::read_cpg(path, &mut notes); + let cpg = crate::dbf::read_cpg(crate::sidecar::find_one(path, "cpg").as_deref(), &mut notes); let (ds, mut report) = read_dbf(std::fs::read(path)?, cpg.as_deref(), &name, &mut csv_memory_budget())?; report.messages.extend(notes); (ds, report) @@ -688,10 +688,34 @@ pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> R } } "shp" => { + // Each part under the name it has (`ROADS.DBF`), a new one in the case of the `.shp`. + let files = crate::sidecar::Sidecars::shapefile(path); + if let Some(other) = files.other_shp() { + return Err(DataError::Format(format!( + "{}: {} is there too, a Shapefile of the same name in another case whose parts can't be told from this one's; rename one of them; nothing was written", + path.display(), + other.display() + ))); + } crate::progress::begin(ds.features.len()); 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(); - place_shapefile(path, &stage_shapefile(&parts)?)?; + // A system no `.prj` can describe: the old file's `.prj` would say another one. + if !parts.iter().any(|(e, _)| *e == "prj") + && let Some(prj) = files.existing("prj") + { + return Err(DataError::Format(format!( + "{}: {} has no .prj form, and {} would go on saying the old file's system; remove it or save to another name; nothing was written", + path.display(), + crs.label(), + prj.display() + ))); + } + // Its spatial indexes would no longer match; another spelling of a part stays, as + // [`shapefile_spellings_note`] says. + let stale: Vec = + crate::sidecar::SHAPEFILE_INDEXES.iter().flat_map(|e| files.spellings(e)).map(Path::to_path_buf).collect(); + let parts: Vec<(std::path::PathBuf, Vec)> = parts.into_iter().map(|(e, bytes)| (files.path(e), bytes)).collect(); + place_shapefile(files.file(), &stage_shapefile(&parts)?, &stale)?; Ok((left_out, None)) } _ if crs != Crs::LonLat && !PROJECTED_FORMATS.contains(&ext.as_str()) => { @@ -705,12 +729,6 @@ pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> R } } -/// The path of the part with extension `ext` of the Shapefile at `path`: the `.shp` keeps the -/// name given (`Roads.SHP` stays so); the others take its stem. -pub(crate) fn shapefile_part(path: &Path, ext: &str) -> std::path::PathBuf { - if ext == "shp" { path.to_path_buf() } else { path.with_extension(ext) } -} - /// Writes each of a Shapefile's parts (its path and bytes) to a temporary file beside it, synced /// to the disk; returns each temporary file with the part it becomes. Nothing is left behind /// when one fails or the run is cancelled (see [`place_shapefile`]). @@ -742,9 +760,14 @@ pub(crate) fn unstage(staged: &[(std::path::PathBuf, std::path::PathBuf)]) { /// Renames each staged part of the Shapefile at `path` ([`stage_shapefile`]) into place, the /// `.shp` last, so a failed write leaves the old Shapefile whole: each old part is moved aside /// first and put back if any new part fails to land, and a Cancel before the last part lands -/// rolls back the same way. Once all have landed, the old parts and the spatial indexes that -/// would no longer match (`.qix`, `.sbn`, `.sbx`) are removed. -pub(crate) fn place_shapefile(path: &Path, staged: &[(std::path::PathBuf, std::path::PathBuf)]) -> Result<()> { +/// rolls back the same way. Once all have landed, the old parts and the `stale` files (the +/// spatial indexes that would no longer match, `.qix`, `.sbn`, `.sbx`, and any other the caller +/// replaces) are removed. +pub(crate) fn place_shapefile( + path: &Path, + staged: &[(std::path::PathBuf, std::path::PathBuf)], + stale: &[std::path::PathBuf], +) -> Result<()> { let mut written: Vec<&(std::path::PathBuf, std::path::PathBuf)> = staged.iter().collect(); written.sort_by_key(|(_, target)| target == path); let mut backups: Vec<(std::path::PathBuf, std::path::PathBuf)> = Vec::new(); @@ -808,16 +831,8 @@ pub(crate) fn place_shapefile(path: &Path, staged: &[(std::path::PathBuf, std::p let _ = std::fs::remove_file(bak); } // A spatial index left from an older file of the same name would no longer match. - for stale in ["qix", "sbn", "sbx"] { - // Sidecars may use any letter case, even beside a lowercase `.shp`. - for capitals in 0..8 { - let extension: String = stale - .bytes() - .enumerate() - .map(|(i, b)| char::from(if capitals & (1 << i) == 0 { b } else { b.to_ascii_uppercase() })) - .collect(); - let _ = std::fs::remove_file(path.with_extension(extension)); - } + for p in stale { + let _ = std::fs::remove_file(p); } // Every part is renamed within `path`'s folder. sync_folder(path); @@ -2515,48 +2530,50 @@ impl CsvWriter { // --------------------------------------------------------------------------------------------- // Shapefile -/// A DBF picked by its path opens the Shapefile beside it when present. Try every ASCII -/// spelling of the extension without scanning a directory; standalone tables return `None`. +/// A DBF picked by its path opens the Shapefile beside it when present, its `.shp` in whichever +/// ASCII case it is spelled; standalone tables return `None`. pub fn shapefile_for_dbf(path: &Path) -> Option { if !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("dbf")) { return None; } - ["shp", "SHP", "Shp", "sHp", "shP", "SHp", "ShP", "sHP"].iter().map(|e| path.with_extension(e)).find(|p| p.is_file()) + crate::sidecar::find_one(path, "shp") } -/// Finds the attributes beside a Shapefile, accepting every ASCII case of `.dbf` in whole -/// and streamed reads. A missing sidecar keeps the usual lowercase path for the error. -pub(crate) fn dbf_sidecar(path: &Path) -> std::path::PathBuf { - ["dbf", "DBF", "Dbf", "dBf", "dbF", "DBf", "DbF", "dBF"] - .iter() - .map(|e| path.with_extension(e)) - .find(|p| p.is_file()) - .unwrap_or_else(|| path.with_extension("dbf")) +/// The note for a Shapefile at `path` with a part there under more than one spelling +/// (`ROADS.dbf` and `ROADS.DBF`, where case is told apart): the one read and written, and that +/// the others are left as they are. For an export over such a file to say. +pub fn shapefile_spellings_note(path: &Path) -> Option { + crate::sidecar::Sidecars::shapefile(path).duplicates_note() } /// Reads a Shapefile with an optional source CRS replacing its `.prj`, before any geometry is /// converted. This changes only interpretation; the files on disk are never modified. pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(Dataset, ReadReport)> { check_size_with(path, shapefile_size_error)?; - let dbf = dbf_sidecar(path); + let files = crate::sidecar::Sidecars::shapefile(path); + let dbf = files.path("dbf"); if !dbf.is_file() { return Err(DataError::Format(format!("Shapefile: {} is missing", dbf.display()))); } check_size_with(&dbf, shapefile_size_error)?; - let shx = path.with_extension("shx"); - if shx.is_file() { - check_size_with(&shx, shapefile_size_error)?; + let shx = files.existing("shx"); + if let Some(shx) = shx { + check_size_with(shx, shapefile_size_error)?; } let mut notes = Vec::new(); let parts = ShapefileParts { shp: crate::provenance::read(path)?, - shx: if shx.is_file() { Some(crate::provenance::read(shx)?) } else { None }, + shx: match shx { + Some(shx) => Some(crate::provenance::read(shx)?), + None => None, + }, dbf: crate::provenance::read(dbf)?, - prj: crate::raster::read_prj(path), - cpg: crate::dbf::read_cpg(path, &mut notes), + prj: files.existing("prj").and_then(crate::raster::read_prj_file), + cpg: crate::dbf::read_cpg(files.existing("cpg"), &mut notes), }; let (ds, mut report) = read_shapefile_parts(parts, name, crs)?; report.messages.extend(notes); + report.messages.extend(files.duplicates_note()); Ok((ds, report)) } diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index ca574655f8..bfe899a908 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -46,6 +46,7 @@ pub mod raster; pub mod s3_address; pub mod secrets; pub mod sheets; +mod sidecar; pub mod source; pub mod source_layers; pub mod sqlite; diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 48e72c1073..338b2000dd 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -25,6 +25,7 @@ use crate::dbf::{Column, RawTable}; use crate::io::{DbfStyle, ShapefileParts}; use crate::raster::Crs; +use crate::sidecar::Sidecars; use crate::sync::{FileSync, Synced}; use crate::{DataError, Dataset, Feature, FieldType, Geometry, Result, Value}; use std::path::{Path, PathBuf}; @@ -134,13 +135,12 @@ fn source_lock(path: &Path) -> Result { Ok(SourceLock(file)) } -/// The Shapefile at `path`'s parts as they are, read into memory, with its `.cpg`'s path. +/// A Shapefile's parts as they are, read into memory, with its `.cpg`'s path. Where each part +/// is written back is where it was found ([`Sidecars::path`]). struct Original { shp: Vec, shx: Option>, dbf: Vec, - /// Where its table is, in whichever case the reader found it, so it is written back there. - dbf_path: PathBuf, prj: Option>, cpg: Option<(PathBuf, Vec)>, } @@ -156,25 +156,19 @@ fn read_part(p: &Path, size_error: fn(&str, u64) -> String) -> Result Result { + /// Reads the parts of the Shapefile `files` found: its `.shp` and `.dbf` must be there; its + /// `.shx`, `.prj` and `.cpg` may be. + fn read(files: &Sidecars) -> Result { + let path = files.file(); let read = |part: &Path| read_part(part, crate::io::shapefile_size_error); let missing = |ext: &str| refused(path, format!("its .{ext} isn't there")); let shp = read(path)?.ok_or_else(|| missing("shp"))?; - let dbf_path = crate::io::dbf_sidecar(path); - let dbf = read(&dbf_path)?.ok_or_else(|| missing("dbf"))?; - let shx = read(&path.with_extension("shx"))?; - let prj = read(&path.with_extension("prj"))?; - let mut cpg = None; - for ext in crate::dbf::CPG_SPELLINGS { - let p = path.with_extension(ext); - if let Some(bytes) = read(&p)? { - cpg = Some((p, bytes)); - break; - } - } - Ok(Original { shp, shx, dbf, dbf_path, prj, cpg }) + let dbf = read(&files.path("dbf"))?.ok_or_else(|| missing("dbf"))?; + let shx = read(&files.path("shx"))?; + let prj = read(&files.path("prj"))?; + let cpg_path = files.path("cpg"); + let cpg = read(&cpg_path)?.map(|bytes| (cpg_path, bytes)); + Ok(Original { shp, shx, dbf, prj, cpg }) } /// Its parts as the reader takes them. @@ -206,23 +200,38 @@ impl Original { /// and writing/syncing each staged part likewise run as single steps. pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result { let _lock = source_lock(path)?; - let unchanged = |when: &str| -> Result<()> { - refuse_link(path, path)?; - for ext in ["shx", "dbf", "prj"].into_iter().chain(crate::dbf::CPG_SPELLINGS) { - refuse_link(path, &path.with_extension(ext))?; + // Its parts, found once: each is read from and written back to the name it has. + let files = Sidecars::shapefile(path); + if let Some(other) = files.other_shp() { + return Err(refused( + path, + format!( + "{} is there too, a Shapefile of the same name in another case whose parts can't be told from this one's", + other.display() + ), + )); + } + let now = FileSync::parts_of(&files); + // The files as `found`, each as the record has it, and none a link. + let unchanged = |found: &Sidecars, when: &str| -> Result<()> { + // The file, every spelling there of each part, and the name a part not there yet takes. + refuse_link(path, found.file())?; + for ext in crate::sidecar::SHAPEFILE_COMPANIONS { + for part in found.spellings(ext).into_iter().map(Path::to_path_buf).chain([found.path(ext)]) { + refuse_link(path, &part)?; + } } - refuse_link(path, &crate::io::dbf_sidecar(path))?; - let changed = synced.files.changed(path)?; + let changed = synced.files.changed_among(&FileSync::parts_of(found))?; if changed.is_empty() { return Ok(()); } Err(refused(path, format!("{} changed {when}, and writing the layer would overwrite that", changed.join(", ")))) }; - unchanged("since the layer was read")?; - let original = Original::read(path)?; + unchanged(&files, "since the layer was read")?; + let original = Original::read(&files)?; let crs = ds.crs.filter(|c| *c != Crs::LonLat); let written_crs = crs.unwrap_or(Crs::LonLat); - let mut notes = Vec::new(); + let mut notes: Vec = files.duplicates_note().into_iter().collect(); let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let Some(table) = crate::dbf::raw_table(&original.dbf) else { @@ -371,34 +380,39 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result)> = parts - .into_iter() - .map(|(e, bytes)| (if e == "dbf" { original.dbf_path.clone() } else { crate::io::shapefile_part(path, e) }, bytes)) - .collect(); + let mut targets: Vec<(PathBuf, Vec)> = parts.into_iter().map(|(e, bytes)| (files.path(e), bytes)).collect(); if let Some((cpg, bytes)) = &original.cpg { targets.push((cpg.clone(), bytes.clone())); } let rows = crate::sync::rows_digest(&read_back)?; // The record of the files as they will be, made before any is placed: once they are, the // publish has happened, whatever comes after. - let files = FileSync::of_written(path, &targets)?; + let record = FileSync::of_written_among(&now, &targets)?; // Written beside the old parts, checked, and placed. let staged = crate::io::stage_shapefile(&targets)?; - let checked = (|| -> Result<()> { + let checked = (|| -> Result { for ((tmp, _), (_, bytes)) in staged.iter().zip(&targets) { if std::fs::read(tmp)? != *bytes { return Err(refused(path, format!("{} didn't read back as written", tmp.display()))); } } - unchanged("while the layer was written") + // Found again: a part or link put there under another spelling meanwhile is seen. + let again = Sidecars::shapefile(path); + unchanged(&again, "while the layer was written")?; + Ok(again) })(); - if let Err(e) = checked { - crate::io::unstage(&staged); - return Err(e); - } - crate::io::place_shapefile(path, &staged)?; - Ok(Published { files, read: read_back, rows, features: ds.features.len(), notes }) + let again = match checked { + Ok(again) => again, + Err(e) => { + crate::io::unstage(&staged); + return Err(e); + } + }; + // Its spatial indexes would no longer match; its other spellings of a part stay, as said. + let stale: Vec = crate::sidecar::SHAPEFILE_INDEXES.iter().flat_map(|e| again.spellings(e)).map(Path::to_path_buf).collect(); + crate::io::place_shapefile(files.file(), &staged, &stale)?; + Ok(Published { files: record, read: read_back, rows, features: ds.features.len(), notes }) } /// `ds` in the file's coordinate system `crs` (`None`: longitude/latitude, as it is held). Given @@ -865,6 +879,336 @@ mod tests { assert_eq!(published.files.changed(&path).unwrap(), ["parcels.DBF"]); } + /// A Shapefile spelled all in upper case (`ROADS.SHP`, `.SHX`, `.DBF`, `.PRJ`) gets each + /// part written back under its own name: no lower-case `.shx` or `.prj` beside the old + /// ones, an index that matches the records, and no note of a new system when the system is + /// the same. One spelled in lower case keeps its names too. Meaningful where the file system + /// tells cases apart; elsewhere it checks the names the parts keep. + #[test] + fn an_upper_case_shapefile_is_published_under_its_own_names() { + for (stem, ext) in [("ROADS", "SHP"), ("roads", "shp")] { + for code in [None, Some("EPSG:32616")] { + let dir = tempfile::tempdir().unwrap(); + let lower = dir.path().join(format!("{stem}.shp")); + let mut ds = parcels(); + ds.crs = code.map(|c| Crs::parse(c).unwrap()); + crate::io::write_path_in(&ds, &lower, ds.crs.unwrap_or(Crs::LonLat)).unwrap(); + let path = dir.path().join(format!("{stem}.{ext}")); + for name in file_names(dir.path()) { + let (base, part) = name.rsplit_once('.').unwrap(); + let spelled = if ext == "SHP" { part.to_ascii_uppercase() } else { part.to_ascii_lowercase() }; + std::fs::rename(dir.path().join(&name), dir.path().join(format!("{base}.{spelled}"))).unwrap(); + } + let before = file_names(dir.path()); + assert!( + ["SHX", "DBF", "PRJ"] + .iter() + .all(|e| before.contains(&format!("{stem}.{}", if ext == "SHP" { e.to_string() } else { e.to_ascii_lowercase() }))), + "{before:?}" + ); + let (mut ds, sync) = read(&path); + // One record fewer: the index must be written again to match. + let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); + ds.features = rows.into(); + let published = shapefile(&ds, &path, &sync).unwrap(); + assert!(published.notes.iter().all(|n| !n.contains("now says")), "{stem} {code:?}: {:?}", published.notes); + assert_eq!(file_names(dir.path()), before, "{stem} {code:?}"); + let shx = dir.path().join(format!("{stem}.{}", if ext == "SHP" { "SHX" } else { "shx" })); + assert_eq!(std::fs::read(&shx).unwrap().len(), 100 + 8, "{stem} {code:?}"); + let (back, _) = crate::io::read_path(&path).unwrap(); + assert_eq!(back.features.len(), 1, "{stem} {code:?}"); + assert_eq!(back.crs, ds.crs, "{stem} {code:?}"); + assert!(published.files.changed(&path).unwrap().is_empty(), "{stem} {code:?}"); + } + } + } + + /// The names of the files in `dir`, but for hidden ones (the publisher's lock). + fn file_names(dir: &Path) -> std::collections::BTreeSet { + std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).filter(|n| !n.starts_with('.')).collect() + } + + /// Writes `parcels()` as `ROADS.SHP` in `dir` with its other parts' extensions spelled by + /// `spell`, and returns the `.shp`'s path. + fn roads(dir: &Path, crs: Option, spell: fn(&str) -> String) -> PathBuf { + let lower = dir.join("ROADS.shp"); + let mut ds = parcels(); + ds.crs = crs; + crate::io::write_path_in(&ds, &lower, crs.unwrap_or(Crs::LonLat)).unwrap(); + for name in file_names(dir) { + let (base, ext) = name.rsplit_once('.').unwrap(); + let ext = if ext.eq_ignore_ascii_case("shp") { "SHP".to_string() } else { spell(ext) }; + std::fs::rename(dir.join(&name), dir.join(format!("{base}.{ext}"))).unwrap(); + } + dir.join("ROADS.SHP") + } + + /// A record made before parts were found in any case, or where the file system ignores case, + /// names `ROADS.shx` for `ROADS.SHX`: the same file by its size and hash, so the layer still + /// publishes, under the names the files have. + #[test] + fn a_record_naming_its_parts_in_another_case_still_publishes() { + let dir = tempfile::tempdir().unwrap(); + let path = roads(dir.path(), Some(Crs::parse("EPSG:32616").unwrap()), |e| e.to_ascii_uppercase()); + let before = file_names(dir.path()); + let (mut ds, mut sync) = read(&path); + for (name, _) in &mut sync.files.files { + if let Some((base, ext)) = name.rsplit_once('.') + && ext != "SHP" + { + *name = format!("{base}.{}", ext.to_ascii_lowercase()); + } + } + assert!(sync.files.changed(&path).unwrap().is_empty()); + assert!(sync.files.resized(&path).is_empty()); + let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); + ds.features = rows.into(); + let published = shapefile(&ds, &path, &sync).unwrap(); + assert!(published.notes.is_empty(), "{:?}", published.notes); + assert_eq!(file_names(dir.path()), before); + } + + /// Beside `ROADS.SHP`, parts spelled in lower case keep their names when published, also + /// where the file system ignores case (where `ROADS.SHX` would find `ROADS.shx` too). + #[test] + fn lower_case_parts_beside_an_upper_case_shp_keep_their_names() { + let dir = tempfile::tempdir().unwrap(); + let path = roads(dir.path(), None, |e| e.to_ascii_lowercase()); + let before = file_names(dir.path()); + assert!(before.contains("ROADS.shx") && before.contains("ROADS.cpg"), "{before:?}"); + let (mut ds, sync) = read(&path); + let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); + ds.features = rows.into(); + shapefile(&ds, &path, &sync).unwrap(); + assert_eq!(file_names(dir.path()), before); + assert_eq!(std::fs::read(dir.path().join("ROADS.shx")).unwrap().len(), 100 + 8); + } + + /// Saving over an upper-case Shapefile writes each part under its own name, with no + /// lower-case copy beside it, and removes its spatial index, which would no longer match. + #[test] + fn saving_over_an_upper_case_shapefile_leaves_no_lower_case_parts() { + let dir = tempfile::tempdir().unwrap(); + let path = roads(dir.path(), None, |e| e.to_ascii_uppercase()); + let before = file_names(dir.path()); + std::fs::write(dir.path().join("ROADS.QIX"), b"old index").unwrap(); + let mut ds = parcels(); + let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); + ds.features = rows.into(); + crate::io::write_path(&ds, &path).unwrap(); + assert_eq!(file_names(dir.path()), before); + assert_eq!(std::fs::read(dir.path().join("ROADS.SHX")).unwrap().len(), 100 + 8); + assert_eq!(crate::io::read_path(&path).unwrap().0.features.len(), 1); + assert_eq!(crate::io::shapefile_spellings_note(&path), None); + } + + /// Where case is told apart, a part there under two spellings (`ROADS.dbf` beside + /// `ROADS.DBF`) is saved over as the reader reads it, lower case first, and the other is + /// kept, as the note the export gives says. + #[test] + fn saving_over_a_part_spelled_twice_keeps_the_other_and_says_so() { + let dir = tempfile::tempdir().unwrap(); + let path = roads(dir.path(), None, |e| e.to_ascii_uppercase()); + if crate::sidecar::tests::ignores_case(dir.path()) { + return; + } + let upper = std::fs::read(dir.path().join("ROADS.DBF")).unwrap(); + std::fs::copy(dir.path().join("ROADS.DBF"), dir.path().join("ROADS.dbf")).unwrap(); + let before = file_names(dir.path()); + let mut ds = parcels(); + let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); + ds.features = rows.into(); + crate::io::write_path(&ds, &path).unwrap(); + assert_eq!(file_names(dir.path()), before); + assert_eq!(std::fs::read(dir.path().join("ROADS.DBF")).unwrap(), upper); + let (back, report) = crate::io::read_path(&path).unwrap(); + assert_eq!(back.features.len(), 1); + let note = crate::io::shapefile_spellings_note(&path).unwrap(); + assert!(note.contains("ROADS.dbf (not ROADS.DBF)") && note.contains("leaves the others as they are"), "{note}"); + assert!(report.messages.contains(¬e), "{:?}", report.messages); + } + + /// Where case is told apart, saving to `roads.shp` beside another Shapefile `roads.SHP` (whose + /// parts are `roads.SHX`, `roads.DBF`, `roads.PRJ`) is refused before anything is written, + /// naming the other file. + #[test] + fn saving_beside_a_shp_of_the_name_in_another_case_is_refused() { + let dir = tempfile::tempdir().unwrap(); + if crate::sidecar::tests::ignores_case(dir.path()) { + return; + } + roads(dir.path(), None, |e| e.to_ascii_uppercase()); + for ext in ["SHP", "SHX", "DBF", "PRJ"] { + std::fs::rename(dir.path().join(format!("ROADS.{ext}")), dir.path().join(format!("roads.{ext}"))).unwrap(); + } + std::fs::remove_file(dir.path().join("ROADS.CPG")).unwrap(); + let bytes = |names: &std::collections::BTreeSet| -> Vec> { + names.iter().map(|n| std::fs::read(dir.path().join(n)).unwrap()).collect() + }; + let before = file_names(dir.path()); + assert_eq!(before.len(), 4, "{before:?}"); + let was = bytes(&before); + let e = crate::io::write_path(&parcels(), &dir.path().join("roads.shp")).unwrap_err().to_string(); + assert!(e.contains("roads.SHP is there too") && e.contains("nothing was written"), "{e}"); + assert_eq!(file_names(dir.path()), before); + assert_eq!(bytes(&before), was); + } + + /// Saving over a Shapefile in a system no `.prj` can describe is refused while its `.prj` + /// (in any case) is there: kept, it would say the old file's system. + #[test] + fn saving_in_a_system_without_a_prj_over_one_with_a_prj_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = roads(dir.path(), None, |e| e.to_ascii_uppercase()); + let before = file_names(dir.path()); + let shp = std::fs::read(&path).unwrap(); + let gnomonic = Crs::parse("+proj=gnom +lat_0=35 +lon_0=-90 +datum=WGS84 +units=m +no_defs").unwrap(); + assert!(crate::raster::wkt::to_wkt(gnomonic).is_none()); + let e = crate::io::write_path_in(&parcels(), &path, gnomonic).unwrap_err().to_string(); + assert!(e.contains("has no .prj form") && e.contains("ROADS.PRJ") && e.contains("nothing was written"), "{e}"); + assert_eq!(file_names(dir.path()), before); + assert_eq!(std::fs::read(&path).unwrap(), shp); + // Without a `.prj` there, it is written, with none. + std::fs::remove_file(dir.path().join("ROADS.PRJ")).unwrap(); + crate::io::write_path_in(&parcels(), &path, gnomonic).unwrap(); + assert!(!file_names(dir.path()).iter().any(|n| n.to_ascii_lowercase().ends_with(".prj"))); + } + + /// A record from before #1958 of `ROADS.SHP` names `ROADS.shx` missing, as its lower-case + /// lookup missed `ROADS.SHX`: the layer still publishes, its index written again from the + /// `.shp`. Its `ROADS.prj`, recorded missing the same way, is a change (a publish reads in + /// the layer's system, so a `.PRJ` changed since would be written over unseen), and so is a + /// missing `.dbf`. + #[test] + fn a_record_from_an_older_lookup_still_publishes_and_still_guards() { + let older = |sync: &mut Synced, part: &str| { + let entry = sync.files.files.iter_mut().find(|(n, _)| *n == format!("ROADS.{part}")).unwrap(); + *entry = (format!("ROADS.{}", part.to_ascii_lowercase()), None); + }; + let dir = tempfile::tempdir().unwrap(); + let path = roads(dir.path(), Some(Crs::parse("EPSG:32616").unwrap()), |e| e.to_ascii_uppercase()); + let (mut ds, mut sync) = read(&path); + older(&mut sync, "SHX"); + assert!(sync.files.changed(&path).unwrap().is_empty()); + assert!(sync.files.resized(&path).is_empty()); + let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); + ds.features = rows.into(); + shapefile(&ds, &path, &sync).unwrap(); + assert_eq!(std::fs::read(dir.path().join("ROADS.SHX")).unwrap().len(), 100 + 8); + for part in ["PRJ", "DBF"] { + let (ds, mut sync) = read(&path); + older(&mut sync, "SHX"); + older(&mut sync, part); + assert_eq!(sync.files.changed(&path).unwrap(), [format!("ROADS.{part}")]); + let e = shapefile(&ds, &path, &sync).err().expect("a part recorded missing that is there is a change").to_string(); + assert!(e.contains(&format!("ROADS.{part} changed since the layer was read")), "{e}"); + } + } + + /// A part put there under another spelling while the layer is written (`ROADS.cpg`, between + /// staging the parts and placing them) is seen by the check before they are placed. + #[test] + fn a_part_spelled_otherwise_that_appears_while_writing_is_refused() { + struct Plant(PathBuf, std::sync::atomic::AtomicBool); + impl crate::progress::Probe for Plant { + fn cancelled(&self) -> bool { + use std::sync::atomic::Ordering; + let staged = std::fs::read_dir(&self.0).unwrap().any(|e| e.unwrap().file_name().to_string_lossy().ends_with(".tmp")); + if staged && !self.1.swap(true, Ordering::SeqCst) { + std::fs::write(self.0.join("ROADS.cpg"), "UTF-8").unwrap(); + } + false + } + fn begin(&self, _: u64) {} + fn advance(&self, _: u64) {} + } + let dir = tempfile::tempdir().unwrap(); + let path = roads(dir.path(), None, |e| e.to_ascii_uppercase()); + std::fs::remove_file(dir.path().join("ROADS.CPG")).unwrap(); + let shp = std::fs::read(&path).unwrap(); + let (mut ds, sync) = read(&path); + let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); + ds.features = rows.into(); + let planted = std::sync::Arc::new(Plant(dir.path().to_path_buf(), std::sync::atomic::AtomicBool::new(false))); + let e = { + let _probe = crate::progress::install(Some(planted.clone())); + shapefile(&ds, &path, &sync).err().expect("a part planted while writing is refused").to_string() + }; + assert!(planted.1.load(std::sync::atomic::Ordering::SeqCst)); + assert!(e.contains("changed while the layer was written"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), shp); + assert!(!file_names(dir.path()).iter().any(|n| n.ends_with(".tmp"))); + } + + /// Where the file system ignores case, a project naming `roads.shp` for `ROADS.SHP` and its + /// parts publishes to them under the names they have. + #[test] + fn a_path_in_another_case_publishes_under_the_names_on_disk() { + let dir = tempfile::tempdir().unwrap(); + roads(dir.path(), Some(Crs::parse("EPSG:32616").unwrap()), |e| e.to_ascii_uppercase()); + let path = dir.path().join("roads.shp"); + if !path.exists() { + return; // The folder tells cases apart: `roads.shp` is another file. + } + let before = file_names(dir.path()); + let (mut ds, sync) = read(&path); + let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); + ds.features = rows.into(); + let published = shapefile(&ds, &path, &sync).unwrap(); + assert!(published.notes.is_empty(), "{:?}", published.notes); + assert_eq!(file_names(dir.path()), before); + assert!(published.files.changed(&path).unwrap().is_empty()); + } + + /// A part written for the first time (the `.prj` a defined projection gives) takes the case + /// of the `.shp`'s extension: `ROADS.PRJ`. + #[test] + fn a_new_part_beside_an_upper_case_shp_is_upper_case() { + let dir = tempfile::tempdir().unwrap(); + let path = roads(dir.path(), None, |e| e.to_ascii_uppercase()); + std::fs::remove_file(dir.path().join("ROADS.PRJ")).unwrap(); + let (ds, sync) = read(&path); + let defined = crate::io::define_projection(&ds, Crs::WebMercator).unwrap(); + let published = shapefile(&defined, &path, &sync).unwrap(); + assert!(published.notes.iter().any(|n| n.contains(".prj now says")), "{:?}", published.notes); + let names = file_names(dir.path()); + assert!(names.contains("ROADS.PRJ") && !names.contains("ROADS.prj"), "{names:?}"); + assert!(published.files.changed(&path).unwrap().is_empty()); + } + + /// Two `.cpg` files spelled differently, where the file system tells them apart: the reader + /// and the publisher take the same one (lower case first), say that the other is there, and + /// leave both as they were. + #[test] + fn the_reader_and_the_publisher_take_the_same_cpg() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("parcels.shp"); + let mut ds = parcels(); + let mut rows: Vec<_> = ds.features.iter().cloned().collect(); + rows[0].attrs[0] = Value::Text("Café".into()); + ds.features = rows.into(); + crate::io::write_path(&ds, &path).unwrap(); + let other = path.with_extension("CPG"); + std::fs::write(&other, "1252").unwrap(); + if std::fs::read(path.with_extension("cpg")).unwrap() == b"1252" { + return; // One file under both names: a file system that ignores case. + } + let (read_ds, report) = crate::io::read_path(&path).unwrap(); + assert_eq!(read_ds.features.iter().next().unwrap().attrs[0], Value::Text("Café".into())); + assert!(report.messages.iter().any(|m| m.contains("parcels.cpg (not parcels.CPG)")), "{:?}", report.messages); + let (mut ds, sync) = read(&path); + let mut rows: Vec<_> = ds.features.iter().cloned().collect(); + rows[1].attrs[0] = Value::Text("Jonés".into()); + ds.features = rows.into(); + let published = shapefile(&ds, &path, &sync).unwrap(); + assert!(published.notes.iter().any(|n| n.contains("parcels.cpg (not parcels.CPG)")), "{:?}", published.notes); + let (back, _) = crate::io::read_path(&path).unwrap(); + let texts: Vec<_> = back.features.iter().map(|f| f.attrs[0].clone()).collect(); + assert_eq!(texts, [Value::Text("Café".into()), Value::Text("Jonés".into())]); + assert_eq!(std::fs::read(path.with_extension("cpg")).unwrap(), b"UTF-8"); + assert_eq!(std::fs::read(&other).unwrap(), b"1252"); + } + /// Reads follow symlinks, but replacement would sever them and leave the target stale. #[cfg(unix)] #[test] @@ -924,7 +1268,7 @@ mod tests { written(&parcels(), &path); std::fs::OpenOptions::new().write(true).open(&dbf).unwrap().set_len(MAX_BYTES + 1).unwrap(); - let error = Original::read(&path).err().unwrap().to_string(); + let error = Original::read(&Sidecars::shapefile(&path)).err().unwrap().to_string(); let limit = (MAX_BYTES >> 20).to_string(); assert_eq!(file_size_error_args(&error), Some((dbf.to_str().unwrap(), limit.as_str(), FileSizeAdvice::Shapefile))); assert_eq!(std::fs::metadata(&dbf).unwrap().len(), MAX_BYTES + 1); @@ -1069,7 +1413,7 @@ mod tests { } assert!(published.notes.iter().any(|n| n.contains(".prj now says")), "{:?}", published.notes); let (back, next) = read(&path); - assert_eq!(Original::read(&path).unwrap().crs(), Some(crs)); + assert_eq!(Original::read(&Sidecars::shapefile(&path)).unwrap().crs(), Some(crs)); assert_eq!(back.crs, (crs != Crs::LonLat).then_some(crs)); assert!(same_rows(&defined, &back, PROJECTED_TOLERANCE).is_none()); assert_eq!(next.rows, published.rows); diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 7face55b6e..4d461ae86e 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1712,10 +1712,10 @@ fn read_ascii(path: &Path, text: &str, name: &str, nodata: Option) -> Resul /// doesn't understand is an error instead, because the grid would land in the wrong place as /// longitude/latitude. fn sidecar_crs(path: &Path) -> Result<(Option, Option)> { - let Some(prj) = read_prj(path) else { + let found = prj_path(path); + let Some(prj) = found.as_deref().and_then(read_prj_file) else { // One that is there but can't be read as text (not UTF-8, too large to be one) is said too. - let there = prj_path(path).is_some(); - return Ok((None, there.then(|| "it can't be read as text".to_string()))); + return Ok((None, found.is_some().then(|| "it can't be read as text".to_string()))); }; match wkt::read_wkt(&prj) { Ok((crs, note)) => { @@ -1774,16 +1774,20 @@ fn world_placement( Ok((affine, transformer)) } -/// The `.prj` next to a file, in lower or upper case (`.PRJ`, beside an `IMAGE.TFW`), for file -/// systems that tell them apart. +/// The `.prj` next to a file, in whichever case it is spelled (`.PRJ`, beside an `IMAGE.TFW`), +/// for file systems that tell them apart. fn prj_path(path: &Path) -> Option { - ["prj", "PRJ"].into_iter().map(|e| path.with_extension(e)).find(|p| std::fs::metadata(p).is_ok_and(|m| m.is_file())) + crate::sidecar::find_one(path, "prj") } /// The text of the `.prj` next to a file (`None` when there's none, or it's too large to be one). pub fn read_prj(path: &Path) -> Option { - let prj = prj_path(path)?; - let meta = std::fs::metadata(&prj).ok()?; + read_prj_file(&prj_path(path)?) +} + +/// The text of the `.prj` at `prj` (`None` when it isn't a file, or it's too large to be one). +pub(crate) fn read_prj_file(prj: &Path) -> Option { + let meta = std::fs::metadata(prj).ok()?; if !meta.is_file() || meta.len() > 1 << 20 { return None; } diff --git a/crates/data/src/sidecar.rs b/crates/data/src/sidecar.rs new file mode 100644 index 0000000000..32488b799c --- /dev/null +++ b/crates/data/src/sidecar.rs @@ -0,0 +1,365 @@ +//! The files that go with a file, in whichever ASCII case the folder spells them. A whole +//! Shapefile is found once per read, publish or save from one listing of its folder +//! ([`Sidecars`]), so every reader and writer picks the same file and writes each part back +//! under the name it has; one file of one extension is found by trying its spellings +//! ([`find_one`]), without listing the folder. + +use std::path::{Path, PathBuf}; + +/// A Shapefile's files by their extensions in lower case: its shapes, index, table, coordinate +/// system and code page, then the spatial indexes a rewrite leaves stale. +pub(crate) const SHAPEFILE: [&str; 8] = ["shp", "shx", "dbf", "prj", "cpg", "qix", "sbn", "sbx"]; + +/// The parts of a Shapefile besides its `.shp` that are read and written. +pub(crate) const SHAPEFILE_COMPANIONS: [&str; 4] = ["shx", "dbf", "prj", "cpg"]; + +/// The spatial indexes beside a Shapefile, which no longer match once it is written again. +pub(crate) const SHAPEFILE_INDEXES: [&str; 3] = ["qix", "sbn", "sbx"]; + +/// The most folder entries one listing reads; a larger folder has each spelling tried instead. +const LISTING_LIMIT: usize = 100_000; + +/// Every ASCII case of `ext` (given in lower case): the lower-case one first, then the others in +/// byte order, the order a part's spellings are taken in. +pub(crate) fn case_spellings(ext: &str) -> Vec { + let letters = ext.len().min(8); + let mut spellings: Vec = (0u32..1 << letters) + .map(|mask| ext.chars().enumerate().map(|(i, c)| if i < 8 && mask & (1 << i) != 0 { c.to_ascii_uppercase() } else { c }).collect()) + .collect(); + spellings.sort_by(|a, b| (a != ext, a).cmp(&(b != ext, b))); + spellings.dedup(); + spellings +} + +/// The file with extension `ext` (in lower case) beside `path`: the first of its +/// [`case_spellings`] that is a file (following a link), each tried with one look at the disk, +/// at most eight. Where the file system ignores case, the name returned is the one asked for. +pub(crate) fn find_one(path: &Path, ext: &str) -> Option { + case_spellings(ext).into_iter().map(|e| path.with_extension(e)).find(|p| p.is_file()) +} + +/// One extension's entries beside the file. +#[derive(Debug, Clone)] +struct Part { + ext: &'static str, + /// Its entries (any but folders, so a dangling link too), the lower-case spelling first and + /// then the others in byte order, each with whether it is a file (following a link). + found: Vec<(PathBuf, bool)>, +} + +impl Part { + /// The entry taken: the first that is a file. + fn taken(&self) -> Option<&Path> { + self.found.iter().find(|(_, file)| *file).map(|(p, _)| p.as_path()) + } +} + +/// A Shapefile's files, each extension with every entry its folder has for it. +#[derive(Debug, Clone)] +pub(crate) struct Sidecars { + /// The `.shp`, as its folder spells it (as given when it isn't there). + file: PathBuf, + /// Whether a part written for the first time is named in upper case: the `.shp`'s extension is. + upper: bool, + parts: Vec, +} + +/// What tells two entries for one file apart from two files: device and inode on Unix, else the +/// path the system resolves the entry to (its name as the disk has it), or the entry's own path +/// when it resolves to nothing (a dangling link). +#[derive(PartialEq)] +enum Identity { + #[cfg(unix)] + Inode(u64, u64), + #[cfg(not(unix))] + Path(PathBuf), +} + +fn identity(path: &Path, meta: &std::fs::Metadata) -> Identity { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let _ = path; + Identity::Inode(meta.dev(), meta.ino()) + } + #[cfg(not(unix))] + { + let _ = meta; + Identity::Path(std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())) + } +} + +impl Sidecars { + /// The parts of the Shapefile whose `.shp` is at `path` ([`SHAPEFILE`]), named its stem and + /// an extension in any ASCII case, from one listing of its folder. Where the folder ignores + /// case, a stem in another case (`roads.shp` for `ROADS.SHP`) names the same files and they + /// keep the names they have; where it tells cases apart, only the stem as the file has it + /// counts. When the folder can't be listed or holds more than [`LISTING_LIMIT`] entries, + /// each spelling of each part is tried instead, keeping every one there but for spellings + /// that reach a file already kept. + pub(crate) fn shapefile(path: &Path) -> Sidecars { + let upper_of = |p: &Path| p.extension().is_some_and(|e| !e.is_empty() && !e.as_encoded_bytes().iter().any(u8::is_ascii_lowercase)); + let mut found: Vec<(&'static str, Vec)> = SHAPEFILE.iter().map(|&e| (e, Vec::new())).collect(); + let file = match (path.file_name(), list(path)) { + (Some(name), Some(entries)) => { + let name = name.as_encoded_bytes(); + let exact = entries.iter().any(|(n, _)| n.as_encoded_bytes() == name); + let other = entries.iter().find(|(n, _)| n.as_encoded_bytes() != name && n.as_encoded_bytes().eq_ignore_ascii_case(name)); + // Whether the folder ignores case: the file is there under another spelling, or + // its name in the opposite case, not listed, still reaches a file. + let ignores_case = if exact { + let flipped: Vec = + name.iter().map(|b| if b.is_ascii_lowercase() { b.to_ascii_uppercase() } else { b.to_ascii_lowercase() }).collect(); + flipped != name + && !entries.iter().any(|(n, _)| n.as_encoded_bytes() == flipped.as_slice()) + && std::str::from_utf8(&flipped).is_ok_and(|f| path.with_file_name(f).symlink_metadata().is_ok()) + } else { + other.is_some() && path.symlink_metadata().is_ok() + }; + let file = match other { + Some((n, _)) if !exact && ignores_case => path.with_file_name(n), + _ => path.to_path_buf(), + }; + let stem = file.file_stem().map(|s| s.as_encoded_bytes().to_vec()).unwrap_or_default(); + for (n, is_dir) in &entries { + let bytes = n.as_encoded_bytes(); + let Some(dot) = bytes.iter().rposition(|&b| b == b'.') else { continue }; + let (base, ext) = (bytes.get(..dot).unwrap_or_default(), bytes.get(dot + 1..).unwrap_or_default()); + if *is_dir || !(base == stem.as_slice() || (ignores_case && base.eq_ignore_ascii_case(&stem))) { + continue; + } + if let Some((_, part)) = found.iter_mut().find(|(e, _)| e.as_bytes().eq_ignore_ascii_case(ext)) { + part.push(path.with_file_name(n)); + } + } + file + } + _ => { + for (ext, part) in &mut found { + let mut seen: Vec = Vec::new(); + for spelling in case_spellings(ext) { + let p = path.with_extension(&spelling); + let Ok(meta) = p.symlink_metadata() else { continue }; + let id = identity(&p, &meta); + if meta.is_dir() || seen.contains(&id) { + continue; + } + seen.push(id); + part.push(p); + } + } + path.to_path_buf() + } + }; + let parts = found + .into_iter() + .map(|(ext, mut entries)| { + entries.sort_by_key(|p| { + let e = p.extension().map(|e| e.as_encoded_bytes().to_vec()).unwrap_or_default(); + (e != ext.as_bytes(), e, p.as_os_str().as_encoded_bytes().to_vec()) + }); + let found = entries + .into_iter() + .map(|p| { + let file = p.is_file(); + (p, file) + }) + .collect(); + Part { ext, found } + }) + .collect(); + Sidecars { upper: upper_of(&file), file, parts } + } + + fn part(&self, ext: &str) -> Option<&Part> { + self.parts.iter().find(|p| p.ext == ext) + } + + /// The `.shp`, as its folder spells it. + pub(crate) fn file(&self) -> &Path { + &self.file + } + + /// Every entry for `ext`, in the order they are taken in (none when it isn't a Shapefile's). + pub(crate) fn spellings(&self, ext: &str) -> Vec<&Path> { + self.part(ext).map(|p| p.found.iter().map(|(p, _)| p.as_path()).collect()).unwrap_or_default() + } + + /// The part `ext`: the first of its spellings that is a file. + pub(crate) fn existing(&self, ext: &str) -> Option<&Path> { + self.part(ext).and_then(Part::taken) + } + + /// Where the part `ext` is read from and written to: the `.shp` itself; else the part as + /// [`Sidecars::existing`] finds it, else the name a new one takes, in upper case beside a + /// `.shp` whose extension is (`ROADS.SHP` gets `ROADS.PRJ`), as + /// [`crate::io::shapefile_part_urls`] names them, else in lower case. + pub(crate) fn path(&self, ext: &str) -> PathBuf { + if ext == "shp" { + return self.file.clone(); + } + match self.existing(ext) { + Some(p) => p.to_path_buf(), + None => self.file.with_extension(if self.upper { ext.to_ascii_uppercase() } else { ext.to_string() }), + } + } + + /// The files of `ext` there besides the one taken: other spellings, on a file system that + /// tells cases apart. + pub(crate) fn others(&self, ext: &str) -> Vec<&Path> { + let Some(part) = self.part(ext) else { return Vec::new() }; + let taken = part.taken(); + part.found.iter().filter(|(p, file)| *file && Some(p.as_path()) != taken).map(|(p, _)| p.as_path()).collect() + } + + /// Another `.shp` of this name in another case (`roads.SHP` beside `roads.shp`, where case is + /// told apart): a second Shapefile whose parts can't be told from this one's. + pub(crate) fn other_shp(&self) -> Option<&Path> { + self.spellings("shp").into_iter().find(|p| *p != self.file.as_path()) + } + + /// A note naming each part there under more than one spelling (`roads.dbf` and + /// `roads.DBF`): which one is read and written, and that the others are left as they are. + pub(crate) fn duplicates_note(&self) -> Option { + let name = |p: &Path| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let twice: Vec = SHAPEFILE_COMPANIONS + .iter() + .filter_map(|ext| { + let others = self.others(ext); + let taken = self.existing(ext).filter(|_| !others.is_empty())?; + Some(format!("{} (not {})", name(taken), others.iter().map(|p| name(p)).collect::>().join(", "))) + }) + .collect(); + if twice.is_empty() { + return None; + } + Some(format!( + "Shapefile: {}: {} {} there under more than one spelling; RustGIS uses {}, and leaves the others as they are", + self.file.display(), + twice.len(), + if twice.len() == 1 { "part is" } else { "parts are" }, + twice.join(", ") + )) + } +} + +/// The names in `path`'s folder, each with whether it is a folder; `None` when the folder can't +/// be listed or holds more than [`LISTING_LIMIT`] entries. +fn list(path: &Path) -> Option> { + let dir = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")); + let mut entries = Vec::new(); + for entry in std::fs::read_dir(dir).ok()? { + if entries.len() >= LISTING_LIMIT { + return None; + } + let entry = entry.ok()?; + let is_dir = entry.file_type().is_ok_and(|t| t.is_dir()); + entries.push((entry.file_name(), is_dir)); + } + Some(entries) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// Whether the folder ignores case, as the default file systems of macOS and Windows do. + pub(crate) fn ignores_case(dir: &Path) -> bool { + std::fs::write(dir.join("probe.txt"), "").unwrap(); + let ignores = dir.join("PROBE.TXT").exists(); + std::fs::remove_file(dir.join("probe.txt")).unwrap(); + ignores + } + + #[test] + fn spellings_are_lower_case_first() { + assert_eq!(case_spellings("cpg"), ["cpg", "CPG", "CPg", "CpG", "Cpg", "cPG", "cPg", "cpG"]); + assert_eq!(case_spellings("7z"), ["7z", "7Z"]); + } + + /// One extension's file is found by its spellings, in that order. + #[test] + fn one_file_is_found_by_its_spellings() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("a.PRJ"), "GEOGCS").unwrap(); + let found = find_one(&dir.path().join("a.tfw"), "prj").unwrap(); + assert_eq!(std::fs::read_to_string(found).unwrap(), "GEOGCS"); + assert_eq!(find_one(&dir.path().join("a.tfw"), "cpg"), None); + } + + /// On a file system that ignores case, a project naming `roads.shp` finds `ROADS.*` and + /// keeps their names. + #[test] + fn a_stem_in_another_case_finds_the_files_where_case_is_ignored() { + let dir = tempfile::tempdir().unwrap(); + if !ignores_case(dir.path()) { + return; + } + for ext in ["SHP", "SHX", "DBF", "prj"] { + std::fs::write(dir.path().join(format!("ROADS.{ext}")), ext).unwrap(); + } + let files = Sidecars::shapefile(&dir.path().join("roads.shp")); + assert_eq!(files.file(), dir.path().join("ROADS.SHP")); + assert_eq!(files.path("shp"), dir.path().join("ROADS.SHP")); + assert_eq!(files.existing("shx"), Some(dir.path().join("ROADS.SHX").as_path())); + assert_eq!(files.existing("prj"), Some(dir.path().join("ROADS.prj").as_path())); + assert_eq!(files.path("cpg"), dir.path().join("ROADS.CPG")); + assert_eq!(files.other_shp(), None); + assert!(files.duplicates_note().is_none()); + } + + /// Where case is told apart, only the stem as the file has it counts, and another `.shp` of + /// the name in another case is said. + #[test] + fn a_stem_in_another_case_is_another_file_where_case_is_told_apart() { + let dir = tempfile::tempdir().unwrap(); + if ignores_case(dir.path()) { + return; + } + for name in ["roads.shp", "ROADS.dbf", "roads.SHP"] { + std::fs::write(dir.path().join(name), "").unwrap(); + } + let files = Sidecars::shapefile(&dir.path().join("roads.shp")); + assert_eq!(files.existing("dbf"), None); + assert_eq!(files.path("dbf"), dir.path().join("roads.dbf")); + assert_eq!(files.other_shp(), Some(dir.path().join("roads.SHP").as_path())); + } + + /// Trying each spelling (a folder that can't be listed): a dangling `roads.prj` doesn't hide + /// the real `roads.PRJ`, and a folder named like a part isn't one. + #[cfg(unix)] + #[test] + fn trying_each_spelling_finds_every_one_there() { + let dir = tempfile::tempdir().unwrap(); + let d = dir.path(); + std::fs::write(d.join("roads.shp"), "").unwrap(); + std::fs::write(d.join("roads.PRJ"), "GEOGCS").unwrap(); + // A file system that ignores case can't hold both: the link replaces nothing there. + let both = !ignores_case(d); + if both { + std::os::unix::fs::symlink(d.join("gone.prj"), d.join("roads.prj")).unwrap(); + } + std::fs::create_dir(d.join("roads.dbf")).unwrap(); + // Unlisted: the folder can't be read, but its files can. + let mut perms = std::fs::metadata(d).unwrap().permissions(); + std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o300); + std::fs::set_permissions(d, perms.clone()).unwrap(); + let listed = std::fs::read_dir(d).is_ok(); + let files = Sidecars::shapefile(&d.join("roads.shp")); + std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o700); + std::fs::set_permissions(d, perms).unwrap(); + if listed { + return; // Running as a user who reads any folder (root). + } + if both { + assert_eq!(files.spellings("prj"), [d.join("roads.prj"), d.join("roads.PRJ")]); + assert_eq!(files.existing("prj"), Some(d.join("roads.PRJ").as_path())); + } else { + // Without a listing, the spelling can't be told there: the file is found all the same. + assert_eq!(files.spellings("prj").len(), 1); + assert_eq!(std::fs::read_to_string(files.existing("prj").unwrap()).unwrap(), "GEOGCS"); + } + assert_eq!(files.existing("dbf"), None); + assert!(files.spellings("dbf").is_empty()); + } +} diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 116c4e801e..6cff93034e 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -30,7 +30,7 @@ fn bad(msg: impl std::fmt::Display) -> DataError { /// The number of records a Shapefile holds, from the size of its `.shx` (without reading it). pub fn record_count(path: &Path) -> Option { - let len = std::fs::metadata(path.with_extension("shx")).ok()?.len(); + let len = std::fs::metadata(crate::sidecar::find_one(path, "shx")?).ok()?.len(); Some(len.checked_sub(100)? / 8) } @@ -89,13 +89,14 @@ impl ShpSource { if let Some(c) = crs { c.transformer().map_err(DataError::Format)?; } - let dbf = crate::io::dbf_sidecar(path); + let files = crate::sidecar::Sidecars::shapefile(path); + let dbf = files.path("dbf"); if !dbf.is_file() { return Err(bad(format!("{} is missing", dbf.display()))); } let mut notes = Vec::new(); let table = read_table(&dbf)?; - let cpg = crate::dbf::read_cpg(path, &mut notes); + let cpg = crate::dbf::read_cpg(files.existing("cpg"), &mut notes); let encoding = crate::dbf::encoding(cpg.as_deref(), table.ldid, &mut notes); let shp_len = std::fs::metadata(path)?.len(); if shp_len > u64::from(u32::MAX) { @@ -127,7 +128,7 @@ impl ShpSource { } let reproject = match crs { Some(c) => Reproject::from_crs(c, &mut notes), - None => shp_reproject(crate::raster::read_prj(path).as_deref(), &mut notes)?, + None => shp_reproject(files.existing("prj").and_then(crate::raster::read_prj_file).as_deref(), &mut notes)?, }; // The records' own boxes frame the layer, as the index holds them (rounded outward to f32); // with none (no records, or every shape null, empty or not a number) it has no extent, diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs index 0661cd277c..532fbbc771 100644 --- a/crates/data/src/sync.rs +++ b/crates/data/src/sync.rs @@ -94,27 +94,60 @@ pub fn is_syncable(path: &str) -> bool { #[cfg(not(target_arch = "wasm32"))] mod native { use super::{FileStamp, FileSync}; + use crate::sidecar::Sidecars; use crate::{DataError, Result}; use std::path::{Path, PathBuf}; /// The files of the source at `path`, each as a name beside it and its path: for a - /// Shapefile the companions its reader opens (the `.cpg` in whichever case is there, else - /// `.cpg`), otherwise the file alone. + /// Shapefile the parts [`FileSync::parts_of`] names, otherwise the file alone. fn parts(path: &Path) -> Vec<(String, PathBuf)> { - let mut paths = vec![path.to_path_buf()]; if path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("shp")) { - // The table in whichever case the reader finds it. - paths.extend([path.with_extension("shx"), crate::io::dbf_sidecar(path), path.with_extension("prj")]); - let cpg = crate::dbf::CPG_SPELLINGS - .iter() - .map(|e| path.with_extension(e)) - .find(|p| p.is_file()) - .unwrap_or_else(|| path.with_extension("cpg")); - paths.push(cpg); + return FileSync::parts_of(&Sidecars::shapefile(path)); } + named(vec![path.to_path_buf()]) + } + + /// Each path with its file name. + fn named(paths: Vec) -> Vec<(String, PathBuf)> { paths.into_iter().map(|p| (p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), p)).collect() } + /// The part of `now` that a recorded `name` is: the one of that name, else the one whose name + /// differs from it only in ASCII case. A record made where the file system ignores case, or + /// before parts were found in any case, can name `ROADS.shx` for what is `ROADS.SHX` now; the + /// two are taken for one file, unchanged only when its size and hash are those recorded. + fn part_named<'a>(now: &'a [(String, PathBuf)], name: &str) -> Option<&'a (String, PathBuf)> { + now.iter().find(|(n, _)| n == name).or_else(|| now.iter().find(|(n, _)| n.eq_ignore_ascii_case(name))) + } + + /// Whether the record's `name`, recorded missing, is an index an older RustGIS couldn't see: + /// before #1958 a record of `ROADS.SHP` looked for its `.shx` in lower case only, so + /// `ROADS.shx` was recorded missing while `ROADS.SHX` was there. This RustGIS names a missing + /// part of an upper-case `.SHP` in upper case, so such an entry only comes from an older one, + /// and says nothing of the file there now (`now`). It isn't counted as a change: a `.shx` + /// holds only where each record of the `.shp` is, which a publish writes again from the + /// `.shp`, so writing over it loses nothing. Its `.prj` was recorded the same way, but isn't + /// taken so: a publish reads the file in the layer's system, so a `.prj` changed since would + /// be written over unseen; such a layer is refused once, and publishes once added again. + fn missed_by_an_older_lookup( + files: &[(String, Option)], + name: &str, + was: &Option, + now: &(String, PathBuf), + ) -> bool { + let upper_set = files + .first() + .and_then(|(n, _)| n.rsplit_once('.')) + .is_some_and(|(_, e)| !e.is_empty() && !e.bytes().any(|b| b.is_ascii_lowercase())); + was.is_none() && upper_set && name.ends_with(".shx") && now.0 != name && now.1.exists() + } + + /// The name a differing file is reported under: the one it has now when it is there (a part + /// added as `a.CPG` where `a.cpg` was recorded missing), else the one recorded. + fn shown(recorded: &str, now: &(String, PathBuf)) -> String { + if now.1.exists() { now.0.clone() } else { recorded.to_string() } + } + /// The file's size, or `None` when it isn't there. fn len(path: &Path) -> Result> { match std::fs::metadata(path) { @@ -173,9 +206,23 @@ mod native { /// the bytes written to it) by those bytes, so a write made since by someone else isn't /// taken for this one; any other part as it is on the disk. pub fn of_written(path: &Path, written: &[(PathBuf, Vec)]) -> Result { + FileSync::of_written_among(&parts(path), written) + } + + /// The parts of a Shapefile a record keeps, each as a name and its path, as `files` found + /// them: the `.shp`, then its `.shx`, `.dbf`, `.prj` and `.cpg` each in whichever case is + /// there, else as a new one would be named. + pub(crate) fn parts_of(files: &Sidecars) -> Vec<(String, PathBuf)> { + let mut paths = vec![files.file().to_path_buf()]; + paths.extend(crate::sidecar::SHAPEFILE_COMPANIONS.map(|ext| files.path(ext))); + named(paths) + } + + /// As [`FileSync::of_written`], with the source's parts as [`FileSync::parts_of`] gives them. + pub(crate) fn of_written_among(now: &[(String, PathBuf)], written: &[(PathBuf, Vec)]) -> Result { use sha2::Digest; let mut files = Vec::new(); - for (name, p) in parts(path) { + for (name, p) in now.iter().cloned() { let stamp = match written.iter().find(|(w, _)| *w == p) { Some((_, bytes)) => Some(FileStamp { len: bytes.len() as u64, @@ -212,25 +259,33 @@ mod native { /// whole and hashed, so its work grows with the file: a caller on the desktop's UI /// thread does it on a thread of its own. Errs only when the run is cancelled. pub fn changed(&self, path: &Path) -> Result> { - let now = parts(path); + self.changed_among(&parts(path)) + } + + /// As [`FileSync::changed`], with the source's parts as [`FileSync::parts_of`] gives them. + pub(crate) fn changed_among(&self, now: &[(String, PathBuf)]) -> Result> { let mut changed = Vec::new(); - // Files there now that the record lacks (a `.cpg` added in another case); not the - // `.cpg` name `parts` falls back to when there is none. - for (name, p) in &now { - if !self.files.iter().any(|(n, _)| n == name) && p.exists() { + // Files there now under a name the record has in no case; not a name `parts` gives + // for a part that isn't there. + for (name, p) in now { + if !self.files.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) && p.exists() { changed.push(name.clone()); } } let total = self.files.iter().filter_map(|(_, s)| s.as_ref()).map(|s| s.len).sum(); crate::progress::begin(count(total)); for (name, was) in &self.files { - let Some((_, p)) = now.iter().find(|(n, _)| n == name) else { + let Some(part) = part_named(now, name) else { // Out of the set now: changed if it held anything. if was.is_some() { changed.push(name.clone()); } continue; }; + if missed_by_an_older_lookup(&self.files, name, was, part) { + continue; + } + let p = &part.1; let same = match (was, len(p)) { (None, Ok(None)) => true, (Some(was), Ok(Some(len))) if len == was.len => match sha256(p) { @@ -241,7 +296,7 @@ mod native { _ => false, }; if !same { - changed.push(name.clone()); + changed.push(shown(name, part)); } } Ok(changed) @@ -252,17 +307,23 @@ mod native { /// isn't seen; [`FileSync::changed`] hashes them. An unreadable file counts as differing. pub fn resized(&self, path: &Path) -> Vec { let now = parts(path); - let mut differ: Vec = - now.iter().filter(|(name, p)| !self.files.iter().any(|(n, _)| n == name) && p.exists()).map(|(n, _)| n.clone()).collect(); + let mut differ: Vec = now + .iter() + .filter(|(name, p)| !self.files.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) && p.exists()) + .map(|(n, _)| n.clone()) + .collect(); for (name, was) in &self.files { - let is = now.iter().find(|(n, _)| n == name).map(|(_, p)| len(p)); - let same = match (was, is) { + let part = part_named(&now, name); + if part.is_some_and(|part| missed_by_an_older_lookup(&self.files, name, was, part)) { + continue; + } + let same = match (was, part.map(|(_, p)| len(p))) { (None, None | Some(Ok(None))) => true, (Some(was), Some(Ok(Some(len)))) => len == was.len, _ => false, }; if !same { - differ.push(name.clone()); + differ.push(part.map_or_else(|| name.clone(), |part| shown(name, part))); } } differ @@ -353,6 +414,44 @@ mod tests { assert_eq!(sync.changed(&path).unwrap(), ["a.CPG"]); } + /// A record naming `a.shx` for what is `a.SHX` now is the same file when its size and hash + /// are those recorded, and changed when they aren't, said under the name it has now. + #[test] + fn a_part_recorded_in_another_case_is_compared_by_its_bytes() { + let dir = tempfile::tempdir().unwrap(); + let d = dir.path(); + for ext in ["shp", "SHX", "dbf"] { + std::fs::write(d.join(format!("a.{ext}")), ext.to_ascii_lowercase()).unwrap(); + } + let path = d.join("a.shp"); + let mut sync = FileSync::read(&path).unwrap(); + let shx = sync.files.iter_mut().find(|(n, _)| n.eq_ignore_ascii_case("a.shx")).unwrap(); + assert_eq!(shx.0, "a.SHX"); + shx.0 = "a.shx".into(); + assert!(sync.changed(&path).unwrap().is_empty()); + assert!(sync.resized(&path).is_empty()); + std::fs::write(d.join("a.SHX"), "SHX").unwrap(); + assert_eq!(sync.changed(&path).unwrap(), ["a.SHX"]); + std::fs::write(d.join("a.SHX"), "shx!").unwrap(); + assert_eq!(sync.resized(&path), ["a.SHX"]); + } + + /// A `.cpg` added in another case than the one recorded missing is said under its own name. + #[test] + fn a_part_added_in_another_case_is_named_as_it_is_spelled() { + let dir = tempfile::tempdir().unwrap(); + let d = dir.path(); + for ext in ["shp", "shx", "dbf"] { + std::fs::write(d.join(format!("a.{ext}")), ext).unwrap(); + } + let path = d.join("a.shp"); + let sync = FileSync::read(&path).unwrap(); + assert!(sync.files.iter().any(|(n, s)| n == "a.cpg" && s.is_none())); + std::fs::write(d.join("a.CPG"), "UTF-8").unwrap(); + assert_eq!(sync.changed(&path).unwrap(), ["a.CPG"]); + assert_eq!(sync.resized(&path), ["a.CPG"]); + } + #[test] fn a_write_while_reading_shows_as_a_change() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 7dcfc9563a..b12b96f44d 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -762,6 +762,10 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk let mut dbf_notes = Vec::new(); if shapefile { dbf_notes.extend(rustgis_data::io::shapefile_names_note(&ds.fields, path)); + // A part there under another spelling too (`ROADS.dbf` beside `ROADS.DBF`) is kept. + if ext == "shp" { + dbf_notes.extend(rustgis_data::io::shapefile_spellings_note(Path::new(path))); + } dbf_notes.extend(rustgis_data::io::shapefile_values_notes(ds, path)); dbf_notes.extend(rustgis_data::io::shapefile_geometry_notes(ds, path, crs)); } From b120b68fd08863ca5e8c10a802e6f85939a06586 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:53:17 -0600 Subject: [PATCH 2/9] fix(data): tell Shapefile part spellings apart only where the disk does (#1958) Follow-up to the last commit, from review. - A folder that can't be listed no longer takes another spelling of ROADS.SHP for a second Shapefile, so saving and publishing there work again. - Where the disk tells cases apart, a part under a new spelling (ROADS.dbf beside the recorded ROADS.DBF) is a new file, so publish refuses. Publish also refuses when the reader would now take a different file for a part. - Saving in a system no .prj can describe removes the old .prj, and the export says which one. - Reading ROADS.SHP beside another ROADS.shp takes the parts spelled in its own case and says the other is there. - The desktop's check on a source stats the recorded names and only lists the folder when something differs; a listing keeps only the Shapefile's names and stops at the limit. --- crates/data/src/io.rs | 42 +++++++---- crates/data/src/publish.rs | 119 +++++++++++++++++++++++++----- crates/data/src/sidecar.rs | 112 ++++++++++++++++++++++++---- crates/data/src/source/shp.rs | 2 + crates/data/src/sync.rs | 129 +++++++++++++++++++++++++-------- crates/engine/src/cmd/share.rs | 9 ++- 6 files changed, 332 insertions(+), 81 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 84428f913a..251f5e0a6b 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -697,23 +697,17 @@ pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> R other.display() ))); } - crate::progress::begin(ds.features.len()); - let (parts, left_out) = shapefile_parts_in(ds, crs)?; - // A system no `.prj` can describe: the old file's `.prj` would say another one. - if !parts.iter().any(|(e, _)| *e == "prj") - && let Some(prj) = files.existing("prj") - { - return Err(DataError::Format(format!( - "{}: {} has no .prj form, and {} would go on saying the old file's system; remove it or save to another name; nothing was written", - path.display(), - crs.label(), - prj.display() - ))); - } // Its spatial indexes would no longer match; another spelling of a part stays, as - // [`shapefile_spellings_note`] says. - let stale: Vec = + // [`shapefile_spellings_note`] says. In a system no `.prj` can describe, none is + // written, and the old file's (in any spelling) goes too, as + // [`shapefile_stale_prj`] says: it would go on saying another system. + let mut stale: Vec = crate::sidecar::SHAPEFILE_INDEXES.iter().flat_map(|e| files.spellings(e)).map(Path::to_path_buf).collect(); + if shapefile_prj(crs).is_none() { + stale.extend(files.spellings("prj").into_iter().map(Path::to_path_buf)); + } + crate::progress::begin(ds.features.len()); + let (parts, left_out) = shapefile_parts_in(ds, crs)?; let parts: Vec<(std::path::PathBuf, Vec)> = parts.into_iter().map(|(e, bytes)| (files.path(e), bytes)).collect(); place_shapefile(files.file(), &stage_shapefile(&parts)?, &stale)?; Ok((left_out, None)) @@ -2539,6 +2533,21 @@ pub fn shapefile_for_dbf(path: &Path) -> Option { crate::sidecar::find_one(path, "shp") } +/// The `.prj` a Shapefile in `crs` is written with: `None` for a system WKT can't describe. +fn shapefile_prj(crs: Crs) -> Option { + if crs == Crs::LonLat { Some(WGS84_PRJ.to_string()) } else { crate::raster::wkt::to_wkt(crs) } +} + +/// The `.prj` beside the Shapefile at `path` that saving it in `crs` removes: one is there (in +/// any spelling) and `crs` has no `.prj` form, so none is written and the old one would go on +/// saying another system. For the export to say; checked before the save. +pub fn shapefile_stale_prj(path: &Path, crs: Crs) -> Option { + if shapefile_prj(crs).is_some() { + return None; + } + crate::sidecar::find_one(path, "prj") +} + /// The note for a Shapefile at `path` with a part there under more than one spelling /// (`ROADS.dbf` and `ROADS.DBF`, where case is told apart): the one read and written, and that /// the others are left as they are. For an export over such a file to say. @@ -2573,6 +2582,7 @@ pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(D }; let (ds, mut report) = read_shapefile_parts(parts, name, crs)?; report.messages.extend(notes); + report.messages.extend(files.other_shp_note()); report.messages.extend(files.duplicates_note()); Ok((ds, report)) } @@ -4398,7 +4408,7 @@ pub(crate) fn shapefile_parts_styled( return Err(DataError::Unsupported(format!("{what} as a Shapefile"))); } } - let prj = if crs == Crs::LonLat { Some(WGS84_PRJ.to_string()) } else { crate::raster::wkt::to_wkt(crs) }; + let prj = shapefile_prj(crs); let mut dbf = dbf.into_inner(); if let Some(style) = style { // The file's language driver, whatever `dbase` takes the encoding for, and its float diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 338b2000dd..7c7d84b571 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -397,9 +397,19 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result = ds.features.iter().skip(1).cloned().collect(); ds.features = rows.into(); + if !crate::sidecar::tests::ignores_case(dir.path()) { + assert!(!sync.files.changed(&path).unwrap().is_empty()); + assert!(shapefile(&ds, &path, &sync).is_err()); + assert_eq!(file_names(dir.path()), before); + return; + } + assert!(sync.files.changed(&path).unwrap().is_empty()); + assert!(sync.files.resized(&path).is_empty()); let published = shapefile(&ds, &path, &sync).unwrap(); assert!(published.notes.is_empty(), "{:?}", published.notes); assert_eq!(file_names(dir.path()), before); } + /// Where case is told apart, a part that appears under a new spelling beside the one + /// recorded (`ROADS.dbf` beside `ROADS.DBF`, even with the same bytes) is a new file the + /// reader would take: refused when there before the publish, and when it appears while the + /// layer is written. + #[test] + fn a_new_spelling_of_a_part_is_refused_where_case_is_told_apart() { + struct Plant(PathBuf, std::sync::atomic::AtomicBool); + impl crate::progress::Probe for Plant { + fn cancelled(&self) -> bool { + use std::sync::atomic::Ordering; + let staged = std::fs::read_dir(&self.0).unwrap().any(|e| e.unwrap().file_name().to_string_lossy().ends_with(".tmp")); + if staged && !self.1.swap(true, Ordering::SeqCst) { + std::fs::copy(self.0.join("ROADS.DBF"), self.0.join("ROADS.dbf")).unwrap(); + } + false + } + fn begin(&self, _: u64) {} + fn advance(&self, _: u64) {} + } + let dir = tempfile::tempdir().unwrap(); + if crate::sidecar::tests::ignores_case(dir.path()) { + return; + } + let path = roads(dir.path(), None, |e| e.to_ascii_uppercase()); + let (mut ds, sync) = read(&path); + let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); + ds.features = rows.into(); + std::fs::copy(dir.path().join("ROADS.DBF"), dir.path().join("ROADS.dbf")).unwrap(); + let e = shapefile(&ds, &path, &sync).err().expect("a new spelling is a change").to_string(); + assert!(e.contains("ROADS.dbf") && e.contains("changed since the layer was read"), "{e}"); + std::fs::remove_file(dir.path().join("ROADS.dbf")).unwrap(); + let shp = std::fs::read(&path).unwrap(); + let planted = std::sync::Arc::new(Plant(dir.path().to_path_buf(), std::sync::atomic::AtomicBool::new(false))); + let e = { + let _probe = crate::progress::install(Some(planted.clone())); + shapefile(&ds, &path, &sync).err().expect("a new spelling while writing is refused").to_string() + }; + assert!(planted.1.load(std::sync::atomic::Ordering::SeqCst)); + assert!(e.contains("while the layer was written") || e.contains("would be read instead"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), shp); + } + + /// Where case is told apart, reading `ROADS.SHP` beside another Shapefile `ROADS.shp` takes + /// the parts spelled in its own case (`ROADS.DBF`, not `ROADS.dbf`) and says the other is + /// there. + #[test] + fn reading_beside_a_shp_of_the_name_in_another_case_says_so() { + let dir = tempfile::tempdir().unwrap(); + if crate::sidecar::tests::ignores_case(dir.path()) { + return; + } + let path = roads(dir.path(), None, |e| e.to_ascii_uppercase()); + let other = tempfile::tempdir().unwrap(); + let mut one = parcels(); + let rows: Vec<_> = one.features.iter().skip(1).cloned().collect(); + one.features = rows.into(); + crate::io::write_path(&one, &other.path().join("x.shp")).unwrap(); + for ext in ["shp", "shx", "dbf"] { + std::fs::copy(other.path().join(format!("x.{ext}")), dir.path().join(format!("ROADS.{ext}"))).unwrap(); + } + let (ds, report) = crate::io::read_path(&path).unwrap(); + let owners: Vec<_> = ds.features.iter().map(|f| f.attrs[0].clone()).collect(); + assert_eq!(owners, [Value::Text("Smith".into()), Value::Text("Jones".into())]); + assert!(report.messages.iter().any(|m| m.contains("ROADS.shp is there too") && m.contains("ROADS.DBF")), "{:?}", report.messages); + let source = crate::source::shp::ShpSource::open_path(&path, "roads").unwrap(); + let notes = &crate::source::FeatureSource::info(&source).notes; + assert!(notes.iter().any(|m| m.contains("ROADS.shp is there too")), "{notes:?}"); + } + /// Beside `ROADS.SHP`, parts spelled in lower case keep their names when published, also /// where the file system ignores case (where `ROADS.SHX` would find `ROADS.shx` too). #[test] @@ -1054,24 +1139,22 @@ mod tests { assert_eq!(bytes(&before), was); } - /// Saving over a Shapefile in a system no `.prj` can describe is refused while its `.prj` - /// (in any case) is there: kept, it would say the old file's system. + /// Saving over a Shapefile in a system no `.prj` can describe writes none and removes the + /// old file's `.prj` (in any case), which would say another system; the export is told + /// which one beforehand ([`crate::io::shapefile_stale_prj`]) to say so. #[test] - fn saving_in_a_system_without_a_prj_over_one_with_a_prj_is_refused() { + fn saving_in_a_system_without_a_prj_removes_the_old_prj() { let dir = tempfile::tempdir().unwrap(); let path = roads(dir.path(), None, |e| e.to_ascii_uppercase()); - let before = file_names(dir.path()); - let shp = std::fs::read(&path).unwrap(); let gnomonic = Crs::parse("+proj=gnom +lat_0=35 +lon_0=-90 +datum=WGS84 +units=m +no_defs").unwrap(); assert!(crate::raster::wkt::to_wkt(gnomonic).is_none()); - let e = crate::io::write_path_in(&parcels(), &path, gnomonic).unwrap_err().to_string(); - assert!(e.contains("has no .prj form") && e.contains("ROADS.PRJ") && e.contains("nothing was written"), "{e}"); - assert_eq!(file_names(dir.path()), before); - assert_eq!(std::fs::read(&path).unwrap(), shp); - // Without a `.prj` there, it is written, with none. - std::fs::remove_file(dir.path().join("ROADS.PRJ")).unwrap(); + let stale = crate::io::shapefile_stale_prj(&path, gnomonic).unwrap(); + assert_eq!(std::fs::read(&stale).unwrap(), std::fs::read(dir.path().join("ROADS.PRJ")).unwrap()); + assert_eq!(crate::io::shapefile_stale_prj(&path, Crs::LonLat), None); crate::io::write_path_in(&parcels(), &path, gnomonic).unwrap(); - assert!(!file_names(dir.path()).iter().any(|n| n.to_ascii_lowercase().ends_with(".prj"))); + assert!(!file_names(dir.path()).iter().any(|n| n.to_ascii_lowercase().ends_with(".prj")), "{:?}", file_names(dir.path())); + assert_eq!(crate::io::shapefile_stale_prj(&path, gnomonic), None); + assert_eq!(crate::io::read_path(&path).unwrap().0.features.len(), 2); } /// A record from before #1958 of `ROADS.SHP` names `ROADS.shx` missing, as its lower-case diff --git a/crates/data/src/sidecar.rs b/crates/data/src/sidecar.rs index 32488b799c..10357cc5aa 100644 --- a/crates/data/src/sidecar.rs +++ b/crates/data/src/sidecar.rs @@ -6,16 +6,34 @@ use std::path::{Path, PathBuf}; -/// A Shapefile's files by their extensions in lower case: its shapes, index, table, coordinate -/// system and code page, then the spatial indexes a rewrite leaves stale. -pub(crate) const SHAPEFILE: [&str; 8] = ["shp", "shx", "dbf", "prj", "cpg", "qix", "sbn", "sbx"]; - /// The parts of a Shapefile besides its `.shp` that are read and written. pub(crate) const SHAPEFILE_COMPANIONS: [&str; 4] = ["shx", "dbf", "prj", "cpg"]; /// The spatial indexes beside a Shapefile, which no longer match once it is written again. pub(crate) const SHAPEFILE_INDEXES: [&str; 3] = ["qix", "sbn", "sbx"]; +/// A Shapefile's files by their extensions in lower case: its shapes, its +/// [`SHAPEFILE_COMPANIONS`], then its [`SHAPEFILE_INDEXES`]. +pub(crate) const SHAPEFILE: [&str; 8] = { + let [shx, dbf, prj, cpg] = SHAPEFILE_COMPANIONS; + let [qix, sbn, sbx] = SHAPEFILE_INDEXES; + ["shp", shx, dbf, prj, cpg, qix, sbn, sbx] +}; + +/// Whether an extension is in upper case (`SHP`, not `shp` or `Shp`): a part written for the +/// first time beside such a `.shp` is named in upper case too. +pub(crate) fn upper_extension(ext: &[u8]) -> bool { + !ext.is_empty() && !ext.iter().any(u8::is_ascii_lowercase) +} + +/// Whether two paths reach one file ([`Identity`]); `false` when either reaches nothing. +pub(crate) fn same_file(a: &Path, b: &Path) -> bool { + match (a.metadata(), b.metadata()) { + (Ok(ma), Ok(mb)) => identity(a, &ma) == identity(b, &mb), + _ => false, + } +} + /// The most folder entries one listing reads; a larger folder has each spelling tried instead. const LISTING_LIMIT: usize = 100_000; @@ -98,7 +116,7 @@ impl Sidecars { /// each spelling of each part is tried instead, keeping every one there but for spellings /// that reach a file already kept. pub(crate) fn shapefile(path: &Path) -> Sidecars { - let upper_of = |p: &Path| p.extension().is_some_and(|e| !e.is_empty() && !e.as_encoded_bytes().iter().any(u8::is_ascii_lowercase)); + let upper_of = |p: &Path| p.extension().is_some_and(|e| upper_extension(e.as_encoded_bytes())); let mut found: Vec<(&'static str, Vec)> = SHAPEFILE.iter().map(|&e| (e, Vec::new())).collect(); let file = match (path.file_name(), list(path)) { (Some(name), Some(entries)) => { @@ -135,9 +153,23 @@ impl Sidecars { file } _ => { + let upper = upper_of(path); for (ext, part) in &mut found { let mut seen: Vec = Vec::new(); - for spelling in case_spellings(ext) { + // Spellings that reach the `.shp` itself are it, never another Shapefile. + if *ext == "shp" + && let Ok(meta) = path.symlink_metadata() + { + seen.push(identity(path, &meta)); + part.push(path.to_path_buf()); + } + // Where case is ignored every spelling reaches one file: it is named as the + // `.shp`'s case suggests, the guess nearest the name it has. + let mut spellings = case_spellings(ext); + if upper { + spellings.sort_by_key(|s| !upper_extension(s.as_bytes())); + } + for spelling in spellings { let p = path.with_extension(&spelling); let Ok(meta) = p.symlink_metadata() else { continue }; let id = identity(&p, &meta); @@ -151,12 +183,17 @@ impl Sidecars { path.to_path_buf() } }; + let upper = upper_of(&file); + // Beside another `.shp` of the name in another case, a part spelled in this one's case + // (`ROADS.DBF` for `ROADS.SHP`, `ROADS.dbf` for `ROADS.shp`) is taken for this one's. + let paired = found.iter().any(|(e, f)| *e == "shp" && f.iter().any(|p| *p != file)); let parts = found .into_iter() .map(|(ext, mut entries)| { entries.sort_by_key(|p| { let e = p.extension().map(|e| e.as_encoded_bytes().to_vec()).unwrap_or_default(); - (e != ext.as_bytes(), e, p.as_os_str().as_encoded_bytes().to_vec()) + let unlike = paired && (if upper { !upper_extension(&e) } else { e != ext.as_bytes() }); + (unlike, e != ext.as_bytes(), e.clone(), p.as_os_str().as_encoded_bytes().to_vec()) }); let found = entries .into_iter() @@ -168,7 +205,7 @@ impl Sidecars { Part { ext, found } }) .collect(); - Sidecars { upper: upper_of(&file), file, parts } + Sidecars { upper, file, parts } } fn part(&self, ext: &str) -> Option<&Part> { @@ -218,6 +255,20 @@ impl Sidecars { self.spellings("shp").into_iter().find(|p| *p != self.file.as_path()) } + /// A note for reading beside another `.shp` of the name in another case ([`Sidecars::other_shp`]): + /// the parts taken for this one's, those spelled in its case, can't be told apart for sure. + pub(crate) fn other_shp_note(&self) -> Option { + let other = self.other_shp()?; + let name = |p: &Path| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let taken: Vec = SHAPEFILE_COMPANIONS.iter().filter_map(|e| self.existing(e)).map(name).collect(); + Some(format!( + "Shapefile: {}: {} is there too, a Shapefile of the same name in another case; RustGIS reads the parts spelled in this one's case ({}), and can't tell for sure which belong to which", + self.file.display(), + name(other), + if taken.is_empty() { "none".to_string() } else { taken.join(", ") } + )) + } + /// A note naming each part there under more than one spelling (`roads.dbf` and /// `roads.DBF`): which one is read and written, and that the others are left as they are. pub(crate) fn duplicates_note(&self) -> Option { @@ -243,18 +294,25 @@ impl Sidecars { } } -/// The names in `path`'s folder, each with whether it is a folder; `None` when the folder can't -/// be listed or holds more than [`LISTING_LIMIT`] entries. +/// The names in `path`'s folder whose stem is `path`'s in any ASCII case, each with whether it +/// is a folder; `None` when the folder can't be listed or holds more than [`LISTING_LIMIT`] +/// entries, which it stops at. fn list(path: &Path) -> Option> { let dir = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")); + let stem = path.file_stem()?.as_encoded_bytes(); let mut entries = Vec::new(); - for entry in std::fs::read_dir(dir).ok()? { - if entries.len() >= LISTING_LIMIT { + for (i, entry) in std::fs::read_dir(dir).ok()?.enumerate() { + if i >= LISTING_LIMIT { return None; } let entry = entry.ok()?; - let is_dir = entry.file_type().is_ok_and(|t| t.is_dir()); - entries.push((entry.file_name(), is_dir)); + let name = entry.file_name(); + let bytes = name.as_encoded_bytes(); + let base = bytes.iter().rposition(|&b| b == b'.').and_then(|dot| bytes.get(..dot)).unwrap_or(bytes); + if base.eq_ignore_ascii_case(stem) { + let is_dir = entry.file_type().is_ok_and(|t| t.is_dir()); + entries.push((name, is_dir)); + } } Some(entries) } @@ -325,6 +383,32 @@ pub(crate) mod tests { assert_eq!(files.other_shp(), Some(dir.path().join("roads.SHP").as_path())); } + /// Trying each spelling (a folder that can't be listed), every spelling of `ROADS.SHP` that + /// reaches it (all of them, where case is ignored) is it, not another Shapefile. + #[cfg(unix)] + #[test] + fn trying_each_spelling_never_takes_the_shp_for_another() { + let dir = tempfile::tempdir().unwrap(); + let d = dir.path(); + for ext in ["SHP", "SHX", "DBF"] { + std::fs::write(d.join(format!("ROADS.{ext}")), ext).unwrap(); + } + let mut perms = std::fs::metadata(d).unwrap().permissions(); + std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o300); + std::fs::set_permissions(d, perms.clone()).unwrap(); + let listed = std::fs::read_dir(d).is_ok(); + let files = Sidecars::shapefile(&d.join("ROADS.SHP")); + std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o700); + std::fs::set_permissions(d, perms).unwrap(); + if listed { + return; // Running as a user who reads any folder (root). + } + assert_eq!(files.other_shp(), None); + assert_eq!(files.spellings("shp"), [d.join("ROADS.SHP")]); + assert_eq!(std::fs::read_to_string(files.existing("shx").unwrap()).unwrap(), "SHX"); + assert_eq!(files.path("dbf").file_name().unwrap().to_string_lossy().to_ascii_lowercase(), "roads.dbf"); + } + /// Trying each spelling (a folder that can't be listed): a dangling `roads.prj` doesn't hide /// the real `roads.PRJ`, and a folder named like a part isn't one. #[cfg(unix)] diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 6cff93034e..11712ebc25 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -97,6 +97,8 @@ impl ShpSource { let mut notes = Vec::new(); let table = read_table(&dbf)?; let cpg = crate::dbf::read_cpg(files.existing("cpg"), &mut notes); + notes.extend(files.other_shp_note()); + notes.extend(files.duplicates_note()); let encoding = crate::dbf::encoding(cpg.as_deref(), table.ldid, &mut notes); let shp_len = std::fs::metadata(path)?.len(); if shp_len > u64::from(u32::MAX) { diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs index 532fbbc771..1633992e10 100644 --- a/crates/data/src/sync.rs +++ b/crates/data/src/sync.rs @@ -112,12 +112,47 @@ mod native { paths.into_iter().map(|p| (p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), p)).collect() } - /// The part of `now` that a recorded `name` is: the one of that name, else the one whose name - /// differs from it only in ASCII case. A record made where the file system ignores case, or - /// before parts were found in any case, can name `ROADS.shx` for what is `ROADS.SHX` now; the - /// two are taken for one file, unchanged only when its size and hash are those recorded. - fn part_named<'a>(now: &'a [(String, PathBuf)], name: &str) -> Option<&'a (String, PathBuf)> { - now.iter().find(|(n, _)| n == name).or_else(|| now.iter().find(|(n, _)| n.eq_ignore_ascii_case(name))) + /// What a recorded entry is among the parts there now. + enum Pair { + /// The part at this index of `now`. + At(usize), + /// A `.shx` an older lookup missed ([`missed_by_an_older_lookup`]): no change. + Missed, + /// None of them: the file is gone, or was never there. + Gone, + } + + /// Each recorded entry's [`Pair`] among the parts there now (`now`), and which of `now` are + /// the record's. A recorded name is the part of that name, else one whose name differs from + /// it only in ASCII case when the two names reach one file: where the file system ignores + /// case, a record can name `ROADS.shx` for what is `ROADS.SHX` now (made there, or before + /// parts were found in any case), and it is that file, unchanged only when its size and hash + /// are those recorded. Where case is told apart, a part under a new spelling (`ROADS.dbf` + /// beside the recorded `ROADS.DBF`) is a new file. + fn pair(files: &[(String, Option)], now: &[(String, PathBuf)]) -> (Vec, Vec) { + let mut theirs = vec![false; now.len()]; + let mut pairs = Vec::with_capacity(files.len()); + for (name, was) in files { + let one_file = + |(n, p): &(String, PathBuf)| n.eq_ignore_ascii_case(name) && crate::sidecar::same_file(&p.with_file_name(name), p); + let exact = now.iter().position(|(n, _)| n == name); + let missed = || now.iter().position(|part| missed_by_an_older_lookup(files, name, was, part)); + let (pair, at) = match exact { + Some(i) => (Pair::At(i), Some(i)), + None => match missed() { + Some(i) => (Pair::Missed, Some(i)), + None => match now.iter().position(one_file) { + Some(i) => (Pair::At(i), Some(i)), + None => (Pair::Gone, None), + }, + }, + }; + if let Some(t) = at.and_then(|i| theirs.get_mut(i)) { + *t = true; + } + pairs.push(pair); + } + (pairs, theirs) } /// Whether the record's `name`, recorded missing, is an index an older RustGIS couldn't see: @@ -135,11 +170,9 @@ mod native { was: &Option, now: &(String, PathBuf), ) -> bool { - let upper_set = files - .first() - .and_then(|(n, _)| n.rsplit_once('.')) - .is_some_and(|(_, e)| !e.is_empty() && !e.bytes().any(|b| b.is_ascii_lowercase())); - was.is_none() && upper_set && name.ends_with(".shx") && now.0 != name && now.1.exists() + let upper_set = + files.first().and_then(|(n, _)| n.rsplit_once('.')).is_some_and(|(_, e)| crate::sidecar::upper_extension(e.as_bytes())); + was.is_none() && upper_set && name.ends_with(".shx") && now.0 != name && now.0.eq_ignore_ascii_case(name) && now.1.exists() } /// The name a differing file is reported under: the one it has now when it is there (a part @@ -262,29 +295,52 @@ mod native { self.changed_among(&parts(path)) } + /// Whether every file is as recorded by its size, told by looking at each recorded name + /// alone, without listing the folder (a source checked often, as the desktop's watch on + /// it does): for a Shapefile, also that no other spelling of a part's name is there but + /// one that reaches the same file. `false` whenever something differs or might. + fn sized_as_recorded(&self, path: &Path) -> bool { + let shapefile = self.files.first().is_some_and(|(n, _)| n.to_ascii_lowercase().ends_with(".shp")); + self.files.iter().all(|(name, was)| { + let p = path.with_file_name(name); + let sized = match was { + Some(was) => len(&p).is_ok_and(|l| l == Some(was.len)), + None => p.symlink_metadata().is_err(), + }; + let Some((_, ext)) = name.rsplit_once('.').filter(|_| shapefile && sized) else { return sized }; + crate::sidecar::case_spellings(&ext.to_ascii_lowercase()).iter().all(|e| { + let other = p.with_extension(e); + other.symlink_metadata().is_err() || (was.is_some() && crate::sidecar::same_file(&other, &p)) + }) + }) + } + /// As [`FileSync::changed`], with the source's parts as [`FileSync::parts_of`] gives them. pub(crate) fn changed_among(&self, now: &[(String, PathBuf)]) -> Result> { let mut changed = Vec::new(); - // Files there now under a name the record has in no case; not a name `parts` gives - // for a part that isn't there. - for (name, p) in now { - if !self.files.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) && p.exists() { + let (pairs, theirs) = pair(&self.files, now); + // Files there now that aren't the record's; not a name `parts` gives for a part that + // isn't there. + for ((name, p), theirs) in now.iter().zip(&theirs) { + if !theirs && p.exists() { changed.push(name.clone()); } } let total = self.files.iter().filter_map(|(_, s)| s.as_ref()).map(|s| s.len).sum(); crate::progress::begin(count(total)); - for (name, was) in &self.files { - let Some(part) = part_named(now, name) else { + for ((name, was), pair) in self.files.iter().zip(&pairs) { + let part = match pair { + Pair::Missed => continue, + Pair::At(i) => now.get(*i), + Pair::Gone => None, + }; + let Some(part) = part else { // Out of the set now: changed if it held anything. if was.is_some() { changed.push(name.clone()); } continue; }; - if missed_by_an_older_lookup(&self.files, name, was, part) { - continue; - } let p = &part.1; let same = match (was, len(p)) { (None, Ok(None)) => true, @@ -306,17 +362,19 @@ mod native { /// added, removed, or another length. Reads no file, so a change that keeps every length /// isn't seen; [`FileSync::changed`] hashes them. An unreadable file counts as differing. pub fn resized(&self, path: &Path) -> Vec { + if self.sized_as_recorded(path) { + return Vec::new(); + } let now = parts(path); - let mut differ: Vec = now - .iter() - .filter(|(name, p)| !self.files.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) && p.exists()) - .map(|(n, _)| n.clone()) - .collect(); - for (name, was) in &self.files { - let part = part_named(&now, name); - if part.is_some_and(|part| missed_by_an_older_lookup(&self.files, name, was, part)) { - continue; - } + let (pairs, theirs) = pair(&self.files, &now); + let mut differ: Vec = + now.iter().zip(&theirs).filter(|((_, p), theirs)| !**theirs && p.exists()).map(|((n, _), _)| n.clone()).collect(); + for ((name, was), pair) in self.files.iter().zip(&pairs) { + let part = match pair { + Pair::Missed => continue, + Pair::At(i) => now.get(*i), + Pair::Gone => None, + }; let same = match (was, part.map(|(_, p)| len(p))) { (None, None | Some(Ok(None))) => true, (Some(was), Some(Ok(Some(len)))) => len == was.len, @@ -414,8 +472,10 @@ mod tests { assert_eq!(sync.changed(&path).unwrap(), ["a.CPG"]); } - /// A record naming `a.shx` for what is `a.SHX` now is the same file when its size and hash - /// are those recorded, and changed when they aren't, said under the name it has now. + /// A record naming `a.shx` for what is `a.SHX` now: where the file system ignores case, the + /// same file, unchanged when its size and hash are those recorded and changed, said under + /// the name it has now, when they aren't; where case is told apart, a new file, and the + /// recorded one gone. #[test] fn a_part_recorded_in_another_case_is_compared_by_its_bytes() { let dir = tempfile::tempdir().unwrap(); @@ -428,6 +488,11 @@ mod tests { let shx = sync.files.iter_mut().find(|(n, _)| n.eq_ignore_ascii_case("a.shx")).unwrap(); assert_eq!(shx.0, "a.SHX"); shx.0 = "a.shx".into(); + if !crate::sidecar::tests::ignores_case(d) { + assert_eq!(sync.changed(&path).unwrap(), ["a.SHX", "a.shx"]); + assert_eq!(sync.resized(&path), ["a.SHX", "a.shx"]); + return; + } assert!(sync.changed(&path).unwrap().is_empty()); assert!(sync.resized(&path).is_empty()); std::fs::write(d.join("a.SHX"), "SHX").unwrap(); diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index b12b96f44d..8b21d66027 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -705,6 +705,8 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk return Err(format!("{path}: {e}")); } let parquet = matches!(ext.as_str(), "parquet" | "geoparquet"); + // The old file's `.prj` a Shapefile in a system without one removes, found before it goes. + let stale_prj = if ext == "shp" { rustgis_data::io::shapefile_stale_prj(Path::new(path), crs) } else { None }; let (written, left_out, skipped, table, unfit, null_numbers, moved, format_notes, dates) = match &chunks { Some((src, layer)) => { let (e, table) = @@ -786,7 +788,12 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk 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())); + let removed = stale_prj + .as_deref() + .and_then(Path::file_name) + .map(|n| format!("; {} was removed, as it said the old file's system", n.to_string_lossy())) + .unwrap_or_default(); + said.push(format!("{path}: no .prj written, as {} has no WKT form{removed}", crs.label())); } said.push(format!("Exported {path}")); let answer = json!({"path": path, "features": written, "leftOut": left_out, "crs": crs.label()}); From b67fb746cc94e5a7bb8e6c709460eebf3d42e925 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:43:47 -0600 Subject: [PATCH 3/9] fix(data): say again when a Shapefile's .cpg can't be read, and build for the browser (#1958) Follow-up from the full CI run. - A folder (or anything else that isn't a file) at places.cpg was skipped by the new part lookup, so the reader no longer said it couldn't read the .cpg. Both readers, and a .dbf read on its own, try it again and say so. - The browser build failed on a helper only the desktop uses; it is now desktop-only. --- crates/data/src/io.rs | 4 +-- crates/data/src/sidecar.rs | 56 ++++++++++++++++++++++++----------- crates/data/src/source/shp.rs | 2 +- 3 files changed, 41 insertions(+), 21 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 251f5e0a6b..36eca70068 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -386,7 +386,7 @@ pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> { "dbf" => { check_size(path)?; let mut notes = Vec::new(); - let cpg = crate::dbf::read_cpg(crate::sidecar::find_one(path, "cpg").as_deref(), &mut notes); + let cpg = crate::dbf::read_cpg(crate::sidecar::find_present(path, "cpg").as_deref(), &mut notes); let (ds, mut report) = read_dbf(std::fs::read(path)?, cpg.as_deref(), &name, &mut csv_memory_budget())?; report.messages.extend(notes); (ds, report) @@ -2578,7 +2578,7 @@ pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(D }, dbf: crate::provenance::read(dbf)?, prj: files.existing("prj").and_then(crate::raster::read_prj_file), - cpg: crate::dbf::read_cpg(files.existing("cpg"), &mut notes), + cpg: crate::dbf::read_cpg(files.existing("cpg").or(files.unreadable("cpg")), &mut notes), }; let (ds, mut report) = read_shapefile_parts(parts, name, crs)?; report.messages.extend(notes); diff --git a/crates/data/src/sidecar.rs b/crates/data/src/sidecar.rs index 10357cc5aa..94086db02f 100644 --- a/crates/data/src/sidecar.rs +++ b/crates/data/src/sidecar.rs @@ -27,6 +27,7 @@ pub(crate) fn upper_extension(ext: &[u8]) -> bool { } /// Whether two paths reach one file ([`Identity`]); `false` when either reaches nothing. +#[cfg(not(target_arch = "wasm32"))] pub(crate) fn same_file(a: &Path, b: &Path) -> bool { match (a.metadata(), b.metadata()) { (Ok(ma), Ok(mb)) => identity(a, &ma) == identity(b, &mb), @@ -56,12 +57,18 @@ pub(crate) fn find_one(path: &Path, ext: &str) -> Option { case_spellings(ext).into_iter().map(|e| path.with_extension(e)).find(|p| p.is_file()) } +/// As [`find_one`], the first spelling there in any form (following a link): a folder or +/// another entry that isn't a file too, for a reader to try and say why it couldn't read it. +pub(crate) fn find_present(path: &Path, ext: &str) -> Option { + case_spellings(ext).into_iter().map(|e| path.with_extension(e)).find(|p| p.metadata().is_ok()) +} + /// One extension's entries beside the file. #[derive(Debug, Clone)] struct Part { ext: &'static str, - /// Its entries (any but folders, so a dangling link too), the lower-case spelling first and - /// then the others in byte order, each with whether it is a file (following a link). + /// Its entries (a folder or a dangling link too), the lower-case spelling first and then the + /// others in byte order, each with whether it is a file (following a link). found: Vec<(PathBuf, bool)>, } @@ -121,29 +128,29 @@ impl Sidecars { let file = match (path.file_name(), list(path)) { (Some(name), Some(entries)) => { let name = name.as_encoded_bytes(); - let exact = entries.iter().any(|(n, _)| n.as_encoded_bytes() == name); - let other = entries.iter().find(|(n, _)| n.as_encoded_bytes() != name && n.as_encoded_bytes().eq_ignore_ascii_case(name)); + let exact = entries.iter().any(|n| n.as_encoded_bytes() == name); + let other = entries.iter().find(|n| n.as_encoded_bytes() != name && n.as_encoded_bytes().eq_ignore_ascii_case(name)); // Whether the folder ignores case: the file is there under another spelling, or // its name in the opposite case, not listed, still reaches a file. let ignores_case = if exact { let flipped: Vec = name.iter().map(|b| if b.is_ascii_lowercase() { b.to_ascii_uppercase() } else { b.to_ascii_lowercase() }).collect(); flipped != name - && !entries.iter().any(|(n, _)| n.as_encoded_bytes() == flipped.as_slice()) + && !entries.iter().any(|n| n.as_encoded_bytes() == flipped.as_slice()) && std::str::from_utf8(&flipped).is_ok_and(|f| path.with_file_name(f).symlink_metadata().is_ok()) } else { other.is_some() && path.symlink_metadata().is_ok() }; let file = match other { - Some((n, _)) if !exact && ignores_case => path.with_file_name(n), + Some(n) if !exact && ignores_case => path.with_file_name(n), _ => path.to_path_buf(), }; let stem = file.file_stem().map(|s| s.as_encoded_bytes().to_vec()).unwrap_or_default(); - for (n, is_dir) in &entries { + for n in &entries { let bytes = n.as_encoded_bytes(); let Some(dot) = bytes.iter().rposition(|&b| b == b'.') else { continue }; let (base, ext) = (bytes.get(..dot).unwrap_or_default(), bytes.get(dot + 1..).unwrap_or_default()); - if *is_dir || !(base == stem.as_slice() || (ignores_case && base.eq_ignore_ascii_case(&stem))) { + if !(base == stem.as_slice() || (ignores_case && base.eq_ignore_ascii_case(&stem))) { continue; } if let Some((_, part)) = found.iter_mut().find(|(e, _)| e.as_bytes().eq_ignore_ascii_case(ext)) { @@ -173,7 +180,7 @@ impl Sidecars { let p = path.with_extension(&spelling); let Ok(meta) = p.symlink_metadata() else { continue }; let id = identity(&p, &meta); - if meta.is_dir() || seen.contains(&id) { + if seen.contains(&id) { continue; } seen.push(id); @@ -186,7 +193,7 @@ impl Sidecars { let upper = upper_of(&file); // Beside another `.shp` of the name in another case, a part spelled in this one's case // (`ROADS.DBF` for `ROADS.SHP`, `ROADS.dbf` for `ROADS.shp`) is taken for this one's. - let paired = found.iter().any(|(e, f)| *e == "shp" && f.iter().any(|p| *p != file)); + let paired = found.iter().any(|(e, f)| *e == "shp" && f.iter().any(|p| *p != file && p.is_file())); let parts = found .into_iter() .map(|(ext, mut entries)| { @@ -252,7 +259,17 @@ impl Sidecars { /// Another `.shp` of this name in another case (`roads.SHP` beside `roads.shp`, where case is /// told apart): a second Shapefile whose parts can't be told from this one's. pub(crate) fn other_shp(&self) -> Option<&Path> { - self.spellings("shp").into_iter().find(|p| *p != self.file.as_path()) + let part = self.part("shp")?; + part.found.iter().find(|(p, file)| *file && *p != self.file).map(|(p, _)| p.as_path()) + } + + /// The part `ext` when it is there but not as a file (a folder at `places.cpg`): what a + /// reader tries, to say it couldn't read it, when [`Sidecars::existing`] finds none. + pub(crate) fn unreadable(&self, ext: &str) -> Option<&Path> { + if self.existing(ext).is_some() { + return None; + } + self.part(ext)?.found.iter().map(|(p, _)| p.as_path()).find(|p| p.metadata().is_ok()) } /// A note for reading beside another `.shp` of the name in another case ([`Sidecars::other_shp`]): @@ -294,10 +311,9 @@ impl Sidecars { } } -/// The names in `path`'s folder whose stem is `path`'s in any ASCII case, each with whether it -/// is a folder; `None` when the folder can't be listed or holds more than [`LISTING_LIMIT`] -/// entries, which it stops at. -fn list(path: &Path) -> Option> { +/// The names in `path`'s folder whose stem is `path`'s in any ASCII case; `None` when the +/// folder can't be listed or holds more than [`LISTING_LIMIT`] entries, which it stops at. +fn list(path: &Path) -> Option> { let dir = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")); let stem = path.file_stem()?.as_encoded_bytes(); let mut entries = Vec::new(); @@ -310,8 +326,7 @@ fn list(path: &Path) -> Option> { let bytes = name.as_encoded_bytes(); let base = bytes.iter().rposition(|&b| b == b'.').and_then(|dot| bytes.get(..dot)).unwrap_or(bytes); if base.eq_ignore_ascii_case(stem) { - let is_dir = entry.file_type().is_ok_and(|t| t.is_dir()); - entries.push((name, is_dir)); + entries.push(name); } } Some(entries) @@ -343,6 +358,10 @@ pub(crate) mod tests { let found = find_one(&dir.path().join("a.tfw"), "prj").unwrap(); assert_eq!(std::fs::read_to_string(found).unwrap(), "GEOGCS"); assert_eq!(find_one(&dir.path().join("a.tfw"), "cpg"), None); + // A folder at the name is no file, but is there for a reader to say it can't read it. + std::fs::create_dir(dir.path().join("a.cpg")).unwrap(); + assert_eq!(find_one(&dir.path().join("a.tfw"), "cpg"), None); + assert_eq!(find_present(&dir.path().join("a.tfw"), "cpg"), Some(dir.path().join("a.cpg"))); } /// On a file system that ignores case, a project naming `roads.shp` finds `ROADS.*` and @@ -443,7 +462,8 @@ pub(crate) mod tests { assert_eq!(files.spellings("prj").len(), 1); assert_eq!(std::fs::read_to_string(files.existing("prj").unwrap()).unwrap(), "GEOGCS"); } + // A folder at a part's name is no part, but is there for a reader to say so. assert_eq!(files.existing("dbf"), None); - assert!(files.spellings("dbf").is_empty()); + assert_eq!(files.unreadable("dbf"), Some(d.join("roads.dbf").as_path())); } } diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 11712ebc25..c43eddb391 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -96,7 +96,7 @@ impl ShpSource { } let mut notes = Vec::new(); let table = read_table(&dbf)?; - let cpg = crate::dbf::read_cpg(files.existing("cpg"), &mut notes); + let cpg = crate::dbf::read_cpg(files.existing("cpg").or(files.unreadable("cpg")), &mut notes); notes.extend(files.other_shp_note()); notes.extend(files.duplicates_note()); let encoding = crate::dbf::encoding(cpg.as_deref(), table.ldid, &mut notes); From b7c09380fd21d80d193976cbd04498ad01889874 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:56:37 -0600 Subject: [PATCH 4/9] fix(data): never open a .cpg that isn't a regular file (#1958) From a security review of the last commit: a named pipe at places.cpg was opened to read, and with no writer the read never returned, so the desktop's read, the CLI and Python hung. The .cpg is now opened only when it is a regular file, without blocking on Unix, and checked again through the open handle; anything else gets the usual note that the .cpg couldn't be read. --- crates/data/src/dbf.rs | 6 +++-- crates/data/src/provenance.rs | 29 +++++++++++++++++++++++++ crates/data/tests/shapefile_encoding.rs | 27 +++++++++++++++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index a1531c37f5..b9dce73dbb 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -317,10 +317,12 @@ pub(crate) fn read_cpg(cpg: Option<&std::path::Path>, notes: &mut Vec) - } } -/// The `.cpg` at `cpg`, as [`crate::sidecar::Sidecars`] finds it beside a table. +/// The `.cpg` at `cpg`, as [`crate::sidecar::Sidecars`] finds it beside a table: anything there +/// but a regular file (a folder, a named pipe) is an error, never opened for reading +/// ([`crate::provenance::open_regular`]). fn try_read_cpg(cpg: &std::path::Path) -> std::io::Result>> { use std::io::Read; - match crate::provenance::open(cpg) { + match crate::provenance::open_regular(cpg) { Ok(file) => { let mut bytes = Vec::new(); (&file).take(MAX_CPG_BYTES as u64 + 1).read_to_end(&mut bytes)?; diff --git a/crates/data/src/provenance.rs b/crates/data/src/provenance.rs index 62f39072c3..2f9fa24610 100644 --- a/crates/data/src/provenance.rs +++ b/crates/data/src/provenance.rs @@ -211,6 +211,35 @@ pub fn open(path: impl AsRef) -> std::io::Result { Ok(file) } +/// As [`open`], for a file that may be anything at its path (a sidecar found by name, which can +/// be a folder or a named pipe): only a regular file is opened, and anything else is an error +/// ("not a regular file") given without waiting on it. On Unix it is opened without blocking (a +/// named pipe with no writer would hold the open forever) and checked again through the open +/// handle, so something put there between the check and the open is caught too. +pub(crate) fn open_regular(path: impl AsRef) -> std::io::Result { + let path = path.as_ref(); + let not_regular = || std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a regular file"); + if !std::fs::metadata(path)?.is_file() { + return Err(not_regular()); + } + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(all(unix, not(target_arch = "wasm32")))] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(rustix::fs::OFlags::NONBLOCK.bits() as i32); + } + let file = options.open(path)?; + let metadata = file.metadata()?; + if !metadata.is_file() { + return Err(not_regular()); + } + if active() { + observe(path, Some(&metadata), None); + } + Ok(file) +} + /// Reads once; a cheap digest uses those bytes, never a second file read. pub fn read(path: impl AsRef) -> std::io::Result> { use std::io::Read; diff --git a/crates/data/tests/shapefile_encoding.rs b/crates/data/tests/shapefile_encoding.rs index 9970d62e6d..6ad28b922a 100644 --- a/crates/data/tests/shapefile_encoding.rs +++ b/crates/data/tests/shapefile_encoding.rs @@ -271,6 +271,33 @@ fn unreadable_cpg_reports_fallback_without_preventing_native_imports() { } } +/// A named pipe at `places.cpg` (no writer, so opening it to read would wait forever) is never +/// opened: both readers return at once, saying the `.cpg` couldn't be read. +#[cfg(unix)] +#[test] +fn a_named_pipe_at_the_cpg_is_reported_without_waiting_on_it() { + use rustgis_data::source::FeatureSource; + let dir = tempfile::tempdir().unwrap(); + for (name, bytes) in parts("München".as_bytes(), 0, None) { + std::fs::write(dir.path().join(name), bytes).unwrap(); + } + let status = std::process::Command::new("mkfifo").arg(dir.path().join("places.cpg")).status().unwrap(); + assert!(status.success()); + let path = dir.path().join("places.shp"); + let (done, finished) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let (ds, report) = io::read_path(&path).unwrap(); + let src = open_shp(&path, "places").unwrap(); + let _ = done.send((ds.value(0, 0).clone(), report.messages, src.info().notes.clone())); + }); + // A read that opened the pipe would never finish: the deadline makes that a failure, not a hang. + let (value, messages, notes) = + finished.recv_timeout(std::time::Duration::from_secs(60)).expect("reading beside a named pipe must not wait on it"); + assert_eq!(value, Value::Text("München".into())); + assert!(messages.iter().any(|m| m.contains(".cpg") && m.contains("not a regular file")), "{messages:?}"); + assert!(notes.iter().any(|m| m.contains(".cpg") && m.contains("not a regular file")), "{notes:?}"); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn shapefile_decodes_legacy_field_names_in_all_readers() { From 2be287733fb3a8a41fb4c925b06523e59791bc2e Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:30:38 -0600 Subject: [PATCH 5/9] fix(data): say what saving a Shapefile removed, and excuse what older records missed (#1958) From review of the last commit. - Saving a Shapefile now returns what it did besides writing it: the old .prj files removed (every spelling, by the name each had) when the new system has no .prj form, and parts kept under another spelling. Both exports say it; a save that has no way to say it refuses instead of removing the .prj. - A save checks the folder again before placing the parts, and refuses if a part appeared under another spelling meanwhile. - A record from before #1958 named a missing .shx or .prj in lower case while the file was there in another case (ROADS.SHX beside ROADS.SHP or ROADS.shp). That is no longer a change, so the desktop's watch stays quiet; publish takes such a .prj only when the file read in that system is the layer as it was read, so one changed since is still refused. - The watch's quick check accepts those, and other spellings that wouldn't be read, without listing the folder. - Publish reads its parts only from regular files, so a named pipe can't make it wait. --- crates/data/src/io.rs | 120 +++++++++++++----- crates/data/src/publish.rs | 181 +++++++++++++++++++++------ crates/data/src/source/tests.rs | 2 +- crates/data/src/sync.rs | 53 +++++--- crates/engine/src/cmd/share.rs | 23 ++-- crates/engine/src/cmd/share/table.rs | 3 +- 6 files changed, 283 insertions(+), 99 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 36eca70068..1a2668c310 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -653,15 +653,59 @@ pub struct GpkgWritten { pub dependents: Vec, } +/// What saving a Shapefile over files there did besides writing its parts, for the caller to +/// say ([`ShapefileSaved::notes`]). Empty for other formats and for a Shapefile saved anew. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ShapefileSaved { + /// The old file's `.prj` files removed, every spelling that was there by the name it had: the + /// system written has no `.prj` form, and they would go on saying another. + pub removed_prj: Vec, + /// The note for parts kept under another spelling beside the ones written (`ROADS.DBF` + /// beside the `ROADS.dbf` written, where case is told apart). + pub kept: Option, +} + +impl ShapefileSaved { + /// What to say of it, each note naming `path`. + pub fn notes(&self, path: &str) -> Vec { + let mut notes: Vec = self.kept.iter().cloned().collect(); + if !self.removed_prj.is_empty() { + let names: Vec = + self.removed_prj.iter().map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()).collect(); + notes.push(format!( + "{path}: {} removed: {} the old file's system, and the one written has no .prj form", + names.join(", "), + if names.len() == 1 { "it said" } else { "they said" } + )); + } + notes + } +} + /// As [`write_path`], in the coordinate system `crs` (a GeoPackage, Shapefile or FlatGeobuf; see -/// [`write_bytes_in`]). +/// [`write_bytes_in`]). With nothing to say what it did besides, a Shapefile saved over one +/// with a `.prj` in a system that has no `.prj` form is refused rather than its `.prj` removed +/// unsaid ([`write_path_to`] removes it and says so). pub fn write_path_in(ds: &Dataset, path: &Path, crs: Crs) -> Result { - write_path_to(ds, path, crs, &GpkgTable::default()).map(|(left_out, _)| left_out) + write_path_saving(ds, path, crs, &GpkgTable::default(), false).map(|(left_out, _, _)| left_out) } /// As [`write_path_in`], a GeoPackage's table placed as `gpkg` says (other formats ignore it): -/// also returns the table written. -pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> Result<(usize, Option)> { +/// also returns the table written, and what saving a Shapefile over one did besides +/// ([`ShapefileSaved`]), for the caller to say. +pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> Result<(usize, Option, ShapefileSaved)> { + write_path_saving(ds, path, crs, gpkg, true) +} + +/// [`write_path_to`]; `remove_prj` says whether the caller says a `.prj` removed, else such a +/// save is refused. +fn write_path_saving( + ds: &Dataset, + path: &Path, + crs: Crs, + gpkg: &GpkgTable, + remove_prj: bool, +) -> Result<(usize, Option, ShapefileSaved)> { let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); let projected; let ds = if crs == Crs::LonLat || !PROJECTED_FORMATS.contains(&ext.as_str()) { @@ -679,7 +723,7 @@ pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> R // Every feature is written: a layer of several kinds of geometry gets a GEOMETRY // column, and one that declares no type takes its geometry's. let table = crate::source::gpkg::write_table_in(ds, path, crs, gpkg)?; - Ok((0, Some(table))) + Ok((0, Some(table), ShapefileSaved::default())) } #[cfg(target_arch = "wasm32")] { @@ -697,20 +741,51 @@ pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> R other.display() ))); } - // Its spatial indexes would no longer match; another spelling of a part stays, as - // [`shapefile_spellings_note`] says. In a system no `.prj` can describe, none is - // written, and the old file's (in any spelling) goes too, as - // [`shapefile_stale_prj`] says: it would go on saying another system. + // Its spatial indexes would no longer match; another spelling of a part stays, and is + // said. In a system no `.prj` can describe, none is written, and the old file's (in + // any spelling) goes too, and is said: it would go on saying another system. let mut stale: Vec = crate::sidecar::SHAPEFILE_INDEXES.iter().flat_map(|e| files.spellings(e)).map(Path::to_path_buf).collect(); - if shapefile_prj(crs).is_none() { - stale.extend(files.spellings("prj").into_iter().map(Path::to_path_buf)); + let old_prj: Vec = if shapefile_prj(crs).is_none() { + files.spellings("prj").into_iter().filter(|p| p.symlink_metadata().is_ok()).map(Path::to_path_buf).collect() + } else { + Vec::new() + }; + if let Some(prj) = old_prj.first().filter(|_| !remove_prj) { + return Err(DataError::Format(format!( + "{}: {} has no .prj form, and {} would go on saying the old file's system; remove it or save to another name; nothing was written", + path.display(), + crs.label(), + prj.display() + ))); } + stale.extend(old_prj.iter().cloned()); crate::progress::begin(ds.features.len()); let (parts, left_out) = shapefile_parts_in(ds, crs)?; + let exts: Vec<&str> = parts.iter().map(|(e, _)| *e).collect(); let parts: Vec<(std::path::PathBuf, Vec)> = parts.into_iter().map(|(e, bytes)| (files.path(e), bytes)).collect(); - place_shapefile(files.file(), &stage_shapefile(&parts)?, &stale)?; - Ok((left_out, None)) + let staged = stage_shapefile(&parts)?; + // Found again before the parts are placed: a part put there under another spelling + // meanwhile, which a reader would take instead of the one written, refuses the save. + let again = crate::sidecar::Sidecars::shapefile(path); + let moved = again + .other_shp() + .map(Path::to_path_buf) + .or_else(|| exts.iter().map(|e| again.path(e)).find(|p| !parts.iter().any(|(t, _)| t == p))); + if let Some(moved) = moved { + unstage(&staged); + return Err(DataError::Format(format!( + "{}: {} appeared while it was written, and would be read instead of the part written; nothing was written", + path.display(), + moved.display() + ))); + } + place_shapefile(files.file(), &staged, &stale)?; + let saved = ShapefileSaved { + removed_prj: old_prj.into_iter().filter(|p| p.symlink_metadata().is_err()).collect(), + kept: files.duplicates_note(), + }; + Ok((left_out, None, saved)) } _ if crs != Crs::LonLat && !PROJECTED_FORMATS.contains(&ext.as_str()) => { Err(DataError::Unsupported(format!(".{ext} in {} (it holds longitude/latitude only)", crs.label()))) @@ -718,7 +793,7 @@ pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> R _ => { let (bytes, left_out) = projected_bytes(ds, &ext, crs)?; write_atomic(path, &bytes)?; - Ok((left_out, None)) + Ok((left_out, None, ShapefileSaved::default())) } } } @@ -2538,23 +2613,6 @@ fn shapefile_prj(crs: Crs) -> Option { if crs == Crs::LonLat { Some(WGS84_PRJ.to_string()) } else { crate::raster::wkt::to_wkt(crs) } } -/// The `.prj` beside the Shapefile at `path` that saving it in `crs` removes: one is there (in -/// any spelling) and `crs` has no `.prj` form, so none is written and the old one would go on -/// saying another system. For the export to say; checked before the save. -pub fn shapefile_stale_prj(path: &Path, crs: Crs) -> Option { - if shapefile_prj(crs).is_some() { - return None; - } - crate::sidecar::find_one(path, "prj") -} - -/// The note for a Shapefile at `path` with a part there under more than one spelling -/// (`ROADS.dbf` and `ROADS.DBF`, where case is told apart): the one read and written, and that -/// the others are left as they are. For an export over such a file to say. -pub fn shapefile_spellings_note(path: &Path) -> Option { - crate::sidecar::Sidecars::shapefile(path).duplicates_note() -} - /// Reads a Shapefile with an optional source CRS replacing its `.prj`, before any geometry is /// converted. This changes only interpretation; the files on disk are never modified. pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(Dataset, ReadReport)> { diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 7c7d84b571..7ece4c3eda 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -146,13 +146,24 @@ struct Original { } /// Reads an original file at `p`, `None` when absent. The caller supplies format-specific size advice. +/// Anything there but a regular file (a folder, a named pipe) is an error, never opened for +/// reading ([`crate::provenance::open_regular`]). fn read_part(p: &Path, size_error: fn(&str, u64) -> String) -> Result>> { - match std::fs::metadata(p) { - Ok(m) if m.len() > crate::io::MAX_BYTES => Err(DataError::Format(size_error(&p.to_string_lossy(), crate::io::MAX_BYTES))), - Ok(_) => Ok(Some(std::fs::read(p)?)), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), - Err(e) => Err(e.into()), + use std::io::Read; + let file = match crate::provenance::open_regular(p) { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(DataError::Format(format!("{}: {e}", p.display()))), + }; + if file.metadata()?.len() > crate::io::MAX_BYTES { + return Err(DataError::Format(size_error(&p.to_string_lossy(), crate::io::MAX_BYTES))); } + let mut bytes = Vec::new(); + (&file).take(crate::io::MAX_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > crate::io::MAX_BYTES { + return Err(DataError::Format(size_error(&p.to_string_lossy(), crate::io::MAX_BYTES))); + } + Ok(Some(bytes)) } impl Original { @@ -228,6 +239,9 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result = + synced.files.unverified_among(&now).into_iter().filter(|n| n.to_ascii_lowercase().ends_with(".prj")).collect(); let original = Original::read(&files)?; let crs = ds.crs.filter(|c| *c != Crs::LonLat); let written_crs = crs.unwrap_or(Crs::LonLat); @@ -272,6 +286,20 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result Some(crate::io::read_shapefile_parts(original.parts(), &name, Some(Crs::LonLat))?.0), None => None, @@ -1080,16 +1108,16 @@ mod tests { let mut ds = parcels(); let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); ds.features = rows.into(); - crate::io::write_path(&ds, &path).unwrap(); + let (_, _, saved) = crate::io::write_path_to(&ds, &path, Crs::LonLat, &Default::default()).unwrap(); + assert_eq!(saved, Default::default()); assert_eq!(file_names(dir.path()), before); assert_eq!(std::fs::read(dir.path().join("ROADS.SHX")).unwrap().len(), 100 + 8); assert_eq!(crate::io::read_path(&path).unwrap().0.features.len(), 1); - assert_eq!(crate::io::shapefile_spellings_note(&path), None); } /// Where case is told apart, a part there under two spellings (`ROADS.dbf` beside /// `ROADS.DBF`) is saved over as the reader reads it, lower case first, and the other is - /// kept, as the note the export gives says. + /// kept, as the save says, in the words the reader uses. #[test] fn saving_over_a_part_spelled_twice_keeps_the_other_and_says_so() { let dir = tempfile::tempdir().unwrap(); @@ -1103,14 +1131,15 @@ mod tests { let mut ds = parcels(); let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); ds.features = rows.into(); - crate::io::write_path(&ds, &path).unwrap(); + let (_, _, saved) = crate::io::write_path_to(&ds, &path, Crs::LonLat, &Default::default()).unwrap(); assert_eq!(file_names(dir.path()), before); assert_eq!(std::fs::read(dir.path().join("ROADS.DBF")).unwrap(), upper); let (back, report) = crate::io::read_path(&path).unwrap(); assert_eq!(back.features.len(), 1); - let note = crate::io::shapefile_spellings_note(&path).unwrap(); + let note = saved.kept.clone().unwrap(); assert!(note.contains("ROADS.dbf (not ROADS.DBF)") && note.contains("leaves the others as they are"), "{note}"); assert!(report.messages.contains(¬e), "{:?}", report.messages); + assert_eq!(saved.notes("roads"), [note]); } /// Where case is told apart, saving to `roads.shp` beside another Shapefile `roads.SHP` (whose @@ -1140,52 +1169,126 @@ mod tests { } /// Saving over a Shapefile in a system no `.prj` can describe writes none and removes the - /// old file's `.prj` (in any case), which would say another system; the export is told - /// which one beforehand ([`crate::io::shapefile_stale_prj`]) to say so. + /// old file's `.prj`, which would say another system, and says which, by the name it had. + /// A save that can't say so ([`crate::io::write_path_in`]) refuses instead. #[test] - fn saving_in_a_system_without_a_prj_removes_the_old_prj() { + fn saving_in_a_system_without_a_prj_removes_the_old_prj_and_says_so() { let dir = tempfile::tempdir().unwrap(); let path = roads(dir.path(), None, |e| e.to_ascii_uppercase()); let gnomonic = Crs::parse("+proj=gnom +lat_0=35 +lon_0=-90 +datum=WGS84 +units=m +no_defs").unwrap(); assert!(crate::raster::wkt::to_wkt(gnomonic).is_none()); - let stale = crate::io::shapefile_stale_prj(&path, gnomonic).unwrap(); - assert_eq!(std::fs::read(&stale).unwrap(), std::fs::read(dir.path().join("ROADS.PRJ")).unwrap()); - assert_eq!(crate::io::shapefile_stale_prj(&path, Crs::LonLat), None); - crate::io::write_path_in(&parcels(), &path, gnomonic).unwrap(); + let before = file_names(dir.path()); + let shp = std::fs::read(&path).unwrap(); + let e = crate::io::write_path_in(&parcels(), &path, gnomonic).unwrap_err().to_string(); + assert!(e.contains("has no .prj form") && e.contains("ROADS.PRJ") && e.contains("nothing was written"), "{e}"); + assert_eq!((file_names(dir.path()), std::fs::read(&path).unwrap()), (before, shp)); + let (_, _, saved) = crate::io::write_path_to(&parcels(), &path, gnomonic, &Default::default()).unwrap(); + assert_eq!(saved.removed_prj, [dir.path().join("ROADS.PRJ")]); + let notes = saved.notes("roads"); + assert!(notes.len() == 1 && notes[0].contains("ROADS.PRJ removed"), "{notes:?}"); assert!(!file_names(dir.path()).iter().any(|n| n.to_ascii_lowercase().ends_with(".prj")), "{:?}", file_names(dir.path())); - assert_eq!(crate::io::shapefile_stale_prj(&path, gnomonic), None); assert_eq!(crate::io::read_path(&path).unwrap().0.features.len(), 2); } - /// A record from before #1958 of `ROADS.SHP` names `ROADS.shx` missing, as its lower-case - /// lookup missed `ROADS.SHX`: the layer still publishes, its index written again from the - /// `.shp`. Its `ROADS.prj`, recorded missing the same way, is a change (a publish reads in - /// the layer's system, so a `.PRJ` changed since would be written over unseen), and so is a - /// missing `.dbf`. + /// A part put there under another spelling while a Shapefile is saved (`ROADS.prj`, where + /// the save would write `ROADS.PRJ`), which a reader would take instead, refuses the save + /// before any part is placed. + #[test] + fn a_part_spelled_otherwise_that_appears_while_saving_is_refused() { + struct Plant(PathBuf, std::sync::atomic::AtomicBool); + impl crate::progress::Probe for Plant { + fn cancelled(&self) -> bool { + use std::sync::atomic::Ordering; + let staged = std::fs::read_dir(&self.0).unwrap().any(|e| e.unwrap().file_name().to_string_lossy().ends_with(".tmp")); + if staged && !self.1.swap(true, Ordering::SeqCst) { + std::fs::write(self.0.join("ROADS.prj"), "GEOGCS").unwrap(); + } + false + } + fn begin(&self, _: u64) {} + fn advance(&self, _: u64) {} + } + let dir = tempfile::tempdir().unwrap(); + let path = roads(dir.path(), None, |e| e.to_ascii_uppercase()); + std::fs::remove_file(dir.path().join("ROADS.PRJ")).unwrap(); + let shp = std::fs::read(&path).unwrap(); + let planted = std::sync::Arc::new(Plant(dir.path().to_path_buf(), std::sync::atomic::AtomicBool::new(false))); + let e = { + let _probe = crate::progress::install(Some(planted.clone())); + crate::io::write_path(&parcels(), &path).unwrap_err().to_string() + }; + assert!(planted.1.load(std::sync::atomic::Ordering::SeqCst)); + assert!(e.contains("ROADS.prj appeared while it was written") && e.contains("nothing was written"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), shp); + assert!(!file_names(dir.path()).iter().any(|n| n.ends_with(".tmp"))); + } + + /// A record from before #1958 names a Shapefile's `.shx` and `.prj` missing in lower case + /// (`ROADS.shx`, `ROADS.prj`), as its lookup missed `ROADS.SHX` and `ROADS.PRJ`; also beside + /// a lower-case `ROADS.shp`. Neither is a change, so the desktop's watch is quiet and the + /// layer publishes. A `.PRJ` changed since, so the file read in its own system isn't the + /// layer as read, is still refused; a `.dbf` recorded missing that is there is a change. #[test] fn a_record_from_an_older_lookup_still_publishes_and_still_guards() { let older = |sync: &mut Synced, part: &str| { - let entry = sync.files.files.iter_mut().find(|(n, _)| *n == format!("ROADS.{part}")).unwrap(); + let entry = sync.files.files.iter_mut().find(|(n, _)| n.eq_ignore_ascii_case(&format!("ROADS.{part}"))).unwrap(); *entry = (format!("ROADS.{}", part.to_ascii_lowercase()), None); }; - let dir = tempfile::tempdir().unwrap(); - let path = roads(dir.path(), Some(Crs::parse("EPSG:32616").unwrap()), |e| e.to_ascii_uppercase()); - let (mut ds, mut sync) = read(&path); - older(&mut sync, "SHX"); - assert!(sync.files.changed(&path).unwrap().is_empty()); - assert!(sync.files.resized(&path).is_empty()); - let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); - ds.features = rows.into(); - shapefile(&ds, &path, &sync).unwrap(); - assert_eq!(std::fs::read(dir.path().join("ROADS.SHX")).unwrap().len(), 100 + 8); - for part in ["PRJ", "DBF"] { + for shp in ["SHP", "shp"] { + let dir = tempfile::tempdir().unwrap(); + let upper = roads(dir.path(), Some(Crs::parse("EPSG:32616").unwrap()), |e| e.to_ascii_uppercase()); + let path = dir.path().join(format!("ROADS.{shp}")); + std::fs::rename(&upper, &path).unwrap(); + let (mut ds, mut sync) = read(&path); + older(&mut sync, "SHX"); + older(&mut sync, "PRJ"); + assert!(sync.files.changed(&path).unwrap().is_empty(), "{shp}"); + assert!(sync.files.resized(&path).is_empty(), "{shp}"); + let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); + ds.features = rows.into(); + shapefile(&ds, &path, &sync).unwrap(); + assert_eq!(std::fs::read(dir.path().join("ROADS.SHX")).unwrap().len(), 100 + 8, "{shp}"); + let (ds, mut sync) = read(&path); older(&mut sync, "SHX"); - older(&mut sync, part); - assert_eq!(sync.files.changed(&path).unwrap(), [format!("ROADS.{part}")]); - let e = shapefile(&ds, &path, &sync).err().expect("a part recorded missing that is there is a change").to_string(); - assert!(e.contains(&format!("ROADS.{part} changed since the layer was read")), "{e}"); + older(&mut sync, "PRJ"); + let prj = dir.path().join("ROADS.PRJ"); + let was = std::fs::read(&prj).unwrap(); + std::fs::write(&prj, crate::raster::wkt::to_wkt(Crs::parse("EPSG:32617").unwrap()).unwrap()).unwrap(); + assert!(sync.files.changed(&path).unwrap().is_empty(), "{shp}"); + let e = shapefile(&ds, &path, &sync).err().expect("a .PRJ changed since is refused").to_string(); + assert!(e.contains("ROADS.PRJ is there, but the layer's record, from an older RustGIS"), "{shp}: {e}"); + std::fs::write(&prj, was).unwrap(); + + let (_, mut sync) = read(&path); + older(&mut sync, "SHX"); + let dbf = sync.files.files.iter_mut().find(|(n, _)| n == "ROADS.DBF").unwrap(); + *dbf = ("ROADS.dbf".into(), None); + assert_eq!(sync.files.changed(&path).unwrap(), ["ROADS.DBF"], "{shp}"); + } + } + + /// Reading a part to publish never opens what isn't a regular file: a named pipe (whose + /// open would wait for a writer) or a folder is an error at once, and a missing part none. + #[cfg(unix)] + #[test] + fn a_part_that_isnt_a_file_is_an_error_without_waiting_on_it() { + let dir = tempfile::tempdir().unwrap(); + let fifo = dir.path().join("roads.cpg"); + assert!(std::process::Command::new("mkfifo").arg(&fifo).status().unwrap().success()); + std::fs::create_dir(dir.path().join("roads.prj")).unwrap(); + let (paths, missing) = ([fifo, dir.path().join("roads.prj")], dir.path().join("roads.shx")); + let (done, finished) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let read = |p: &Path| read_part(p, crate::io::shapefile_size_error).map_err(|e| e.to_string()); + let _ = done.send((paths.iter().map(|p| read(p)).collect::>(), read(&missing))); + }); + // A read that opened the pipe would never finish: the deadline makes that a failure, not a hang. + let (read, missing) = finished.recv_timeout(std::time::Duration::from_secs(60)).expect("reading a named pipe must not wait on it"); + for r in read { + assert!(r.as_ref().is_err_and(|e| e.contains("not a regular file")), "{r:?}"); } + assert_eq!(missing, Ok(None)); } /// A part put there under another spelling while the layer is written (`ROADS.cpg`, between diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 7ee3fca894..f2c107b2d3 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -3726,7 +3726,7 @@ fn geopackage_export_adds_and_replaces_tables_and_keeps_the_others() { } let to = |mode, name: Option<&str>| GpkgTable { mode, name: name.map(String::from) }; let written = write_path_to(&permits, &path, Crs::LonLat, &to(GpkgMode::AddTable, None)).unwrap(); - assert_eq!(written, (0, Some(GpkgWritten { table: "permits".into(), replaced: false, dependents: vec![] }))); + assert_eq!(written, (0, Some(GpkgWritten { table: "permits".into(), replaced: false, dependents: vec![] }), Default::default())); rusqlite::Connection::open(&path).unwrap().execute_batch("INSERT INTO gpkg_ogr_contents VALUES ('permits', 3)").unwrap(); assert_eq!(gpkg_tables(&path), ["owners", "parcels", "permits"]); // The file's own trigger on its contents didn't run. diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs index 1633992e10..fe4b09b549 100644 --- a/crates/data/src/sync.rs +++ b/crates/data/src/sync.rs @@ -155,24 +155,28 @@ mod native { (pairs, theirs) } - /// Whether the record's `name`, recorded missing, is an index an older RustGIS couldn't see: - /// before #1958 a record of `ROADS.SHP` looked for its `.shx` in lower case only, so - /// `ROADS.shx` was recorded missing while `ROADS.SHX` was there. This RustGIS names a missing - /// part of an upper-case `.SHP` in upper case, so such an entry only comes from an older one, - /// and says nothing of the file there now (`now`). It isn't counted as a change: a `.shx` - /// holds only where each record of the `.shp` is, which a publish writes again from the - /// `.shp`, so writing over it loses nothing. Its `.prj` was recorded the same way, but isn't - /// taken so: a publish reads the file in the layer's system, so a `.prj` changed since would - /// be written over unseen; such a layer is refused once, and publishes once added again. + /// Whether the record's `name`, recorded missing, is a name an older RustGIS looked a part up + /// by alone: before #1958 a Shapefile's `.shx` and `.prj` were looked for in lower case only + /// (`ROADS.shx`, `ROADS.prj`), so one there in another case (`ROADS.SHX`) was recorded + /// missing. Such an entry says nothing of the file there now under another spelling. + fn older_lookup_name(files: &[(String, Option)], name: &str, was: &Option) -> bool { + let Some((stem, _)) = files.first().and_then(|(n, _)| n.rsplit_once('.')) else { return false }; + was.is_none() && [".shx", ".prj"].iter().any(|ext| name.strip_suffix(ext) == Some(stem)) + } + + /// Whether the record's `name`, recorded missing, was [missed by an older + /// lookup](older_lookup_name) and is there now (`now`) under another spelling: it isn't + /// counted as a change by itself, as the record can't say what it held. A `.shx` holds only + /// where each record of the `.shp` is, which a publish writes again from the `.shp`; a + /// `.prj` is said ([`FileSync::unverified_among`]), and a publish takes it only when the file + /// read in that system is the layer as it was read. fn missed_by_an_older_lookup( files: &[(String, Option)], name: &str, was: &Option, now: &(String, PathBuf), ) -> bool { - let upper_set = - files.first().and_then(|(n, _)| n.rsplit_once('.')).is_some_and(|(_, e)| crate::sidecar::upper_extension(e.as_bytes())); - was.is_none() && upper_set && name.ends_with(".shx") && now.0 != name && now.0.eq_ignore_ascii_case(name) && now.1.exists() + older_lookup_name(files, name, was) && now.0 != name && now.0.eq_ignore_ascii_case(name) && now.1.exists() } /// The name a differing file is reported under: the one it has now when it is there (a part @@ -308,13 +312,34 @@ mod native { None => p.symlink_metadata().is_err(), }; let Some((_, ext)) = name.rsplit_once('.').filter(|_| shapefile && sized) else { return sized }; - crate::sidecar::case_spellings(&ext.to_ascii_lowercase()).iter().all(|e| { + // Another spelling there is a change only when it would be taken instead: before + // the one recorded, in the order spellings are taken in, or where the record says + // the part was missing (but for a name an older lookup missed it by). + let spellings = crate::sidecar::case_spellings(&ext.to_ascii_lowercase()); + let rank = spellings.iter().position(|e| e == ext).unwrap_or(0); + let excused = older_lookup_name(&self.files, name, was); + spellings.iter().enumerate().filter(|(_, e)| *e != ext).all(|(i, e)| { let other = p.with_extension(e); - other.symlink_metadata().is_err() || (was.is_some() && crate::sidecar::same_file(&other, &p)) + let there = other.symlink_metadata().is_ok(); + match was { + Some(_) => !there || i > rank || crate::sidecar::same_file(&other, &p), + None => !there || excused, + } }) }) } + /// The names of the parts there now that a record from an older RustGIS couldn't speak + /// for ([`missed_by_an_older_lookup`]), so [`FileSync::changed`] doesn't count them: the + /// caller about to write over the file checks them otherwise. + pub(crate) fn unverified_among(&self, now: &[(String, PathBuf)]) -> Vec { + self.files + .iter() + .filter_map(|(name, was)| now.iter().find(|part| missed_by_an_older_lookup(&self.files, name, was, part))) + .map(|(n, _)| n.clone()) + .collect() + } + /// As [`FileSync::changed`], with the source's parts as [`FileSync::parts_of`] gives them. pub(crate) fn changed_among(&self, now: &[(String, PathBuf)]) -> Result> { let mut changed = Vec::new(); diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 8b21d66027..b22b8391f8 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -7,7 +7,7 @@ pub(super) use table::table_work; use std::path::Path; -use rustgis_data::io::{GpkgMode, GpkgTable, GpkgWritten}; +use rustgis_data::io::{GpkgMode, GpkgTable, GpkgWritten, ShapefileSaved}; use rustgis_data::raster::Crs; use rustgis_render::View; use serde_json::{Value, json}; @@ -705,8 +705,9 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk return Err(format!("{path}: {e}")); } let parquet = matches!(ext.as_str(), "parquet" | "geoparquet"); - // The old file's `.prj` a Shapefile in a system without one removes, found before it goes. - let stale_prj = if ext == "shp" { rustgis_data::io::shapefile_stale_prj(Path::new(path), crs) } else { None }; + // What saving a Shapefile over one did besides writing it (a `.prj` removed, a part kept + // under another spelling), as the save found it. + let mut shapefile_saved = ShapefileSaved::default(); let (written, left_out, skipped, table, unfit, null_numbers, moved, format_notes, dates) = match &chunks { Some((src, layer)) => { let (e, table) = @@ -740,7 +741,8 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk None => { let format_notes = rustgis_data::io::export_losses_notes(ds, &ext, rustgis_data::io::name_field(ds), path).map_err(|e| e.to_string())?; - let (left_out, table) = rustgis_data::io::write_path_to(ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())?; + let (left_out, table, saved) = rustgis_data::io::write_path_to(ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())?; + shapefile_saved = saved; let unfit = if parquet { rustgis_data::source::parquet::values_note(ds, path) } else { None }; let null_numbers = rustgis_data::export::numbers_written_as_null(&ds.features, &ds.fields, &ext); let mut dates = read_notes(path, &ds.name, &unreadable); @@ -765,9 +767,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk if shapefile { dbf_notes.extend(rustgis_data::io::shapefile_names_note(&ds.fields, path)); // A part there under another spelling too (`ROADS.dbf` beside `ROADS.DBF`) is kept. - if ext == "shp" { - dbf_notes.extend(rustgis_data::io::shapefile_spellings_note(Path::new(path))); - } + dbf_notes.extend(shapefile_saved.kept.clone()); dbf_notes.extend(rustgis_data::io::shapefile_values_notes(ds, path)); dbf_notes.extend(rustgis_data::io::shapefile_geometry_notes(ds, path, crs)); } @@ -788,12 +788,9 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk said.extend(unfit); said.extend(dates); if shapefile && rustgis_data::raster::wkt::to_wkt(crs).is_none() { - let removed = stale_prj - .as_deref() - .and_then(Path::file_name) - .map(|n| format!("; {} was removed, as it said the old file's system", n.to_string_lossy())) - .unwrap_or_default(); - said.push(format!("{path}: no .prj written, as {} has no WKT form{removed}", crs.label())); + said.push(format!("{path}: no .prj written, as {} has no WKT form", crs.label())); + // The old file's `.prj`, every spelling removed, by the names they had. + said.extend(ShapefileSaved { removed_prj: shapefile_saved.removed_prj.clone(), kept: None }.notes(path)); } said.push(format!("Exported {path}")); let answer = json!({"path": path, "features": written, "leftOut": left_out, "crs": crs.label()}); diff --git a/crates/engine/src/cmd/share/table.rs b/crates/engine/src/cmd/share/table.rs index 4e1578709f..7e92451939 100644 --- a/crates/engine/src/cmd/share/table.rs +++ b/crates/engine/src/cmd/share/table.rs @@ -173,8 +173,9 @@ pub(in crate::cmd) fn table_work(s: &Session, p: &Value) -> Result notes.extend(super::gpkg_dates_note(&ds, &ext, &path)); let name_field = rustgis_data::io::name_field(&ds); notes.extend(rustgis_data::io::export_losses_notes(&ds, &ext, name_field, &path).map_err(|e| e.to_string())?); - let (left_out, table) = + let (left_out, table, saved) = rustgis_data::io::write_path_to(&ds, Path::new(&path), rustgis_data::raster::Crs::LonLat, &gpkg).map_err(|e| e.to_string())?; + notes.extend(saved.notes(&path)); if let Some(note) = rustgis_data::io::left_out_note(&path, &ext, left_out) { notes.insert(0, note); } From 3ddceb44335ccc1ec6acc426b979a03b198cebcb Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:07:37 -0600 Subject: [PATCH 6/9] fix(data): an export over a Shapefile whose .dbf isn't a file says its columns can't be compared (#1958) A named pipe or folder at roads.dbf isn't the table the listing takes, so the comparison saw no old table and said nothing. It is compared now, which fails, and the export says the declarations couldn't be compared, as before the merge. --- crates/data/src/io.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 7cc5619567..f2e639c037 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1604,7 +1604,7 @@ fn write_path_as( ))); } let declaration_changes = if compare { - shapefile_declaration_changes(path, files.existing("dbf"), &parts, &ds.fields) + shapefile_declaration_changes(path, files.existing("dbf").or(files.unreadable("dbf")), &parts, &ds.fields) } else { DeclarationChanges::Unchanged }; @@ -1636,8 +1636,9 @@ fn write_path_as( } } -/// Compares the old attributes (`old_dbf`, the `.dbf` the Shapefile at `path` had, `None` when it -/// had none) independently of the state of the geometry file. +/// Compares the old attributes (`old_dbf`, the `.dbf` the Shapefile at `path` had, or what is there +/// at its name when it isn't a file, which can't be compared; `None` when there is nothing) +/// independently of the state of the geometry file. fn shapefile_declaration_changes( path: &Path, old_dbf: Option<&Path>, From a89ac8f975b2bb5660fa03dd87823107054fd5a0 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:57:33 -0600 Subject: [PATCH 7/9] fix(data): Shapefile parts from review: names the listing can't see, newer records, a .prj kept (#1958) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Where the folder listing doesn't hold the file's own name though it is there (macOS stores Québec.shp decomposed and opens it composed), each spelling is tried instead, so the .prj and .cpg are read again. - A record now says it looked for every spelling. Only one without that mark, from an older RustGIS, is excused a .shx or .prj it recorded missing, so a .PRJ added since is a change again. - An old .prj that can't be removed when the system has no .prj form is said to still name the old system. Only a regular file counts as one. - Publish refuses a .shp of the name in another case that appears while it writes. - The .cpg and .dbf spellings are tried in the order the listing takes them. - A protocol buffer page's read report is boxed, as the record grew. --- crates/data/src/dbf.rs | 14 ++-- crates/data/src/io.rs | 35 ++++++++-- crates/data/src/ogc.rs | 14 ++-- crates/data/src/publish.rs | 112 +++++++++++++++++++++++++++++++ crates/data/src/sidecar.rs | 13 +++- crates/data/src/sync.rs | 60 +++++++++++------ crates/engine/src/cmd/service.rs | 2 +- crates/ui-egui/src/serviceui.rs | 2 +- crates/ui-egui/src/syncmark.rs | 2 +- 9 files changed, 209 insertions(+), 45 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 8acccef360..4b79678a30 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -576,13 +576,15 @@ fn cpg_result(result: std::io::Result>>, ldid: u8, notes: &mut cr } } -/// Every ASCII case of the `.cpg` extension, the conventional spellings first: tried in turn, -/// without scanning a potentially large directory. Non-file spellings are skipped; the first -/// regular file wins. -pub const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"]; +/// Every ASCII case of the `.cpg` extension, lower case first, then in byte order, the order a +/// Shapefile's parts are taken in ([`crate::sidecar::case_spellings`]): tried in turn, without +/// scanning a potentially large directory. Non-file spellings are skipped; the first regular file +/// wins. +pub const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "CPg", "CpG", "Cpg", "cPG", "cPg", "cpG"]; -/// Every ASCII case of a Shapefile attribute table's extension, in reader preference order. -pub const DBF_SPELLINGS: [&str; 8] = ["dbf", "DBF", "Dbf", "dBf", "dbF", "DBf", "DbF", "dBF"]; +/// Every ASCII case of a Shapefile attribute table's extension, in reader preference order (as +/// [`CPG_SPELLINGS`]). +pub const DBF_SPELLINGS: [&str; 8] = ["dbf", "DBF", "DBf", "DbF", "Dbf", "dBF", "dBf", "dbF"]; /// Skips special-file spellings, retaining an unusable-declaration notice if none is regular. fn try_read_cpg(path: &std::path::Path) -> std::io::Result>> { diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index f2e639c037..0fdf7beb85 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1443,6 +1443,8 @@ pub(crate) struct ShapefileSaved { /// The old file's `.prj` files removed, every spelling that was there by the name it had: the /// system written has no `.prj` form, and they would go on saying another. pub(crate) removed_prj: Vec, + /// Those of them that couldn't be removed, so still say the old file's system. + pub(crate) kept_prj: Vec, /// The note for parts kept under another spelling beside the ones written (`ROADS.DBF` /// beside the `ROADS.dbf` written, where case is told apart). pub(crate) kept: Option, @@ -1461,6 +1463,12 @@ impl ShapefileSaved { if names.len() == 1 { "it said" } else { "they said" } )); } + for p in &self.kept_prj { + let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + notes.push(format!( + "{path}: {name} could not be removed and still says the old file's system, though the one written has no .prj form; remove it by hand" + )); + } notes } } @@ -1569,7 +1577,8 @@ fn write_path_as( let mut stale: Vec = crate::sidecar::SHAPEFILE_INDEXES.iter().flat_map(|e| files.spellings(e)).map(Path::to_path_buf).collect(); let old_prj: Vec = if shapefile_prj(crs).is_none() { - files.spellings("prj").into_iter().filter(|p| p.symlink_metadata().is_ok()).map(Path::to_path_buf).collect() + // Only a file says a system: a folder or a link to nothing there isn't one. + files.spellings("prj").into_iter().filter(|p| p.is_file()).map(Path::to_path_buf).collect() } else { Vec::new() }; @@ -1609,10 +1618,8 @@ fn write_path_as( DeclarationChanges::Unchanged }; let kept = place_shapefile(files.file(), &staged, &stale)?; - let saved = ShapefileSaved { - removed_prj: old_prj.into_iter().filter(|p| p.symlink_metadata().is_err()).collect(), - kept: files.duplicates_note(), - }; + let (removed_prj, kept_prj) = old_prj.into_iter().partition(|p| p.symlink_metadata().is_err()); + let saved = ShapefileSaved { removed_prj, kept_prj, kept: files.duplicates_note() }; let notes = unplaced .into_iter() .chain(kept_backups_note(path, &kept).map(crate::loss::Note::plain)) @@ -1865,8 +1872,9 @@ pub(crate) fn place_shapefile( // A copy that can't be removed is returned, to be said: it holds an old part beside the file. let left: Vec = backups.into_iter().filter(|(bak, _)| remove_backup(bak).is_err()).map(|(bak, _)| bak).collect(); // A spatial index left from an older file of the same name would no longer match. + // One that can't be removed is left: a caller that replaces one it must say looks again. for p in stale { - let _ = std::fs::remove_file(p); + let _ = remove_stale(p); } // Every part is renamed within `path`'s folder. sync_folder(path); @@ -1880,6 +1888,21 @@ thread_local! { static KEEP_BACKUPS: std::cell::Cell = const { std::cell::Cell::new(false) }; } +#[cfg(test)] +thread_local! { + /// Makes [`remove_stale`] fail on this thread, for the tests of a file that can't be removed. + pub(crate) static KEEP_STALE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Removes a file the placed Shapefile makes stale ([`place_shapefile`]). +fn remove_stale(p: &Path) -> std::io::Result<()> { + #[cfg(test)] + if KEEP_STALE.get() { + return Err(std::io::Error::other("kept for the test")); + } + std::fs::remove_file(p) +} + /// Removes an old part's copy once the new parts have landed ([`place_shapefile`]). fn remove_backup(bak: &Path) -> std::io::Result<()> { #[cfg(test)] diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 98611b33f7..de30dd755f 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -4050,7 +4050,7 @@ pub enum Step { Done(Vec, Option), /// An ArcGIS layer read in protocol buffer pages (`f=pbf`, see [`begin_with_pbf`]): its /// features, what reading them said, and a note when some were left unread. - Decoded(Box, crate::ReadReport, Option), + Decoded(Box, Box, Option), /// The features couldn't be fetched at all: why. Failed(String), } @@ -5041,7 +5041,7 @@ impl Pages { } } report.messages.extend(losses.messages()); - return Step::Decoded(Box::new(ds), report, note); + return Step::Decoded(Box::new(ds), Box::new(report), note); } // Done before a page was read (a limit of none). if self.doc.is_null() { @@ -6761,7 +6761,7 @@ mod tests { let a = if pages.next_url().contains("/query") { page.clone() } else { layer.to_vec() }; step = (*pages).land(Ok(a)); } - Step::Decoded(ds, report, _) => break (*ds, report), + Step::Decoded(ds, report, _) => break (*ds, *report), other => panic!("{other:?}"), } }; @@ -6873,7 +6873,7 @@ mod tests { }; step = (*pages).land(Ok(a)); } - Step::Decoded(ds, report, note) => break (*ds, report, note), + Step::Decoded(ds, report, note) => break (*ds, *report, note), other => panic!("{other:?}"), } }; @@ -6970,7 +6970,7 @@ mod tests { }; step = (*pages).land(Ok(a)); } - Step::Decoded(ds, report, _) => break (*ds, report), + Step::Decoded(ds, report, _) => break (*ds, *report), other => panic!("{other:?}"), } }; @@ -6999,7 +6999,7 @@ mod tests { let a = if pages.next_url().contains("/query") { bad_wkt.clone() } else { layer.to_vec() }; step = (*pages).land(Ok(a)); } - Step::Decoded(ds, report, _) => break (*ds, report), + Step::Decoded(ds, report, _) => break (*ds, *report), other => panic!("{other:?}"), } }; @@ -7018,7 +7018,7 @@ mod tests { let a = if pages.next_url().contains("/query") { degrees.clone() } else { layer.to_vec() }; step = (*pages).land(Ok(a)); } - Step::Decoded(ds, report, _) => break (*ds, report), + Step::Decoded(ds, report, _) => break (*ds, *report), other => panic!("{other:?}"), } }; diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 5b22dc51aa..1c9a4dcc7e 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -466,6 +466,15 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result bool { + use std::sync::atomic::Ordering; + let staged = std::fs::read_dir(&self.0).unwrap().any(|e| e.unwrap().file_name().to_string_lossy().ends_with(".tmp")); + if staged && !self.1.swap(true, Ordering::SeqCst) { + std::fs::copy(self.0.join("ROADS.SHP"), self.0.join("ROADS.shp")).unwrap(); + } + false + } + fn begin(&self, _: u64) {} + fn advance(&self, _: u64) {} + } + let dir = tempfile::tempdir().unwrap(); + if crate::sidecar::tests::ignores_case(dir.path()) { + return; + } + let path = roads(dir.path(), None, |e| e.to_ascii_uppercase()); + let (mut ds, sync) = read(&path); + let rows: Vec<_> = ds.features.iter().skip(1).cloned().collect(); + ds.features = rows.into(); + let shp = std::fs::read(&path).unwrap(); + let planted = std::sync::Arc::new(Plant(dir.path().to_path_buf(), std::sync::atomic::AtomicBool::new(false))); + let e = { + let _probe = crate::progress::install(Some(planted.clone())); + shapefile(&ds, &path, &sync).err().expect("another .shp while writing is refused").to_string() + }; + assert!(planted.1.load(std::sync::atomic::Ordering::SeqCst)); + assert!(e.contains("ROADS.shp appeared while the layer was written"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), shp); + } + /// Where case is told apart, reading `ROADS.SHP` beside another Shapefile `ROADS.shp` takes /// the parts spelled in its own case (`ROADS.DBF`, not `ROADS.dbf`) and says the other is /// there. @@ -1441,6 +1486,20 @@ mod tests { assert!(notes.len() == 1 && notes[0].contains("ROADS.PRJ removed"), "{notes:?}"); assert!(!file_names(dir.path()).iter().any(|n| n.to_ascii_lowercase().ends_with(".prj")), "{:?}", file_names(dir.path())); assert_eq!(crate::io::read_path(&path).unwrap().0.features.len(), 2); + // A `.prj` that can't be removed still says the old system, and the save says so. + std::fs::write(dir.path().join("ROADS.PRJ"), crate::io::WGS84_PRJ).unwrap(); + crate::io::KEEP_STALE.set(true); + let saved = crate::io::write_path_to(&parcels(), &path, gnomonic, &Default::default()); + crate::io::KEEP_STALE.set(false); + let (_, _, notes) = saved.unwrap(); + assert!(dir.path().join("ROADS.PRJ").is_file()); + assert!(notes.len() == 1 && notes[0].contains("ROADS.PRJ could not be removed and still says the old file's system"), "{notes:?}"); + // A folder at the name says no system: nothing to refuse or remove, and nothing said. + std::fs::remove_file(dir.path().join("ROADS.PRJ")).unwrap(); + std::fs::create_dir(dir.path().join("ROADS.PRJ")).unwrap(); + crate::io::write_path_in(&parcels(), &path, gnomonic).unwrap(); + let (_, _, notes) = crate::io::write_path_to(&parcels(), &path, gnomonic, &Default::default()).unwrap(); + assert!(notes.is_empty(), "{notes:?}"); } /// A part put there under another spelling while a Shapefile is saved (`ROADS.prj`, where @@ -1483,7 +1542,9 @@ mod tests { /// layer as read, is still refused; a `.dbf` recorded missing that is there is a change. #[test] fn a_record_from_an_older_lookup_still_publishes_and_still_guards() { + // Made by an older RustGIS: without the mark of a lookup of every spelling. let older = |sync: &mut Synced, part: &str| { + sync.files.every_spelling = false; let entry = sync.files.files.iter_mut().find(|(n, _)| n.eq_ignore_ascii_case(&format!("ROADS.{part}"))).unwrap(); *entry = (format!("ROADS.{}", part.to_ascii_lowercase()), None); }; @@ -1521,6 +1582,57 @@ mod tests { } } + /// A Shapefile whose names the disk stores in other bytes than the path it is opened by + /// (macOS keeps `Que\u{301}bec.shp` decomposed and opens it as `Québec.shp`) is read with its + /// `.prj` and `.cpg`, as before the parts were found from a listing. Skipped where the disk + /// tells the two names apart. + #[test] + fn a_name_the_disk_stores_otherwise_is_read_with_its_parts() { + let dir = tempfile::tempdir().unwrap(); + let made = tempfile::tempdir().unwrap(); + let mut ds = parcels(); + ds.crs = Some(Crs::parse("EPSG:32616").unwrap()); + crate::io::write_path_in(&ds, &made.path().join("x.shp"), ds.crs.unwrap()).unwrap(); + std::fs::write(made.path().join("x.cpg"), "UTF-8").unwrap(); + for ext in ["shp", "shx", "dbf", "prj", "cpg"] { + std::fs::copy(made.path().join(format!("x.{ext}")), dir.path().join(format!("Que\u{301}bec.{ext}"))).unwrap(); + } + let composed = dir.path().join("Qu\u{e9}bec.shp"); + if !composed.exists() { + return; + } + let files = Sidecars::shapefile(&composed); + for ext in ["shx", "dbf", "prj", "cpg"] { + assert!(files.existing(ext).is_some(), "{ext}"); + } + assert!(files.duplicates_note().is_none() && files.other_shp().is_none()); + let (back, report) = crate::io::read_path(&composed).unwrap(); + assert_eq!(back.crs, ds.crs, "{report:?}"); + assert_eq!(back.features.len(), 2); + let source = crate::source::shp::ShpSource::open_path(&composed, "q").unwrap(); + assert_eq!(crate::source::FeatureSource::info(&source).crs, "EPSG:32616"); + } + + /// A record this version made looked for every spelling of each part: a `.PRJ` added after + /// it recorded none (`roads.prj` missing) is a change, which the desktop's watch and publish + /// see, though a record from before #1958 would have been excused it. + #[test] + fn a_prj_added_after_a_record_of_this_version_is_a_change() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("roads.shp"); + crate::io::write_path_in(&parcels(), &path, Crs::LonLat).unwrap(); + std::fs::remove_file(path.with_extension("prj")).unwrap(); + let (ds, sync) = read(&path); + assert!(sync.files.every_spelling); + assert!(sync.files.changed(&path).unwrap().is_empty()); + assert!(sync.files.resized(&path).is_empty()); + std::fs::write(path.with_extension("PRJ"), crate::raster::wkt::to_wkt(Crs::parse("EPSG:32616").unwrap()).unwrap()).unwrap(); + assert_eq!(sync.files.changed(&path).unwrap(), ["roads.PRJ"]); + assert_eq!(sync.files.resized(&path), ["roads.PRJ"]); + let e = shapefile(&ds, &path, &sync).err().expect("a .PRJ added since is a change").to_string(); + assert!(e.contains("roads.PRJ changed since the layer was read"), "{e}"); + } + /// Reading a part to publish never opens what isn't a regular file: a named pipe (whose /// open would wait for a writer) or a folder is an error at once, and a missing part none. #[cfg(unix)] diff --git a/crates/data/src/sidecar.rs b/crates/data/src/sidecar.rs index 01ad49bff0..0967d80836 100644 --- a/crates/data/src/sidecar.rs +++ b/crates/data/src/sidecar.rs @@ -119,7 +119,15 @@ impl Sidecars { pub(crate) fn shapefile(path: &Path) -> Sidecars { let upper_of = |p: &Path| p.extension().is_some_and(|e| upper_extension(e.as_encoded_bytes())); let mut found: Vec<(&'static str, Vec)> = SHAPEFILE.iter().map(|&e| (e, Vec::new())).collect(); - let file = match (path.file_name(), list(path)) { + // A listing that doesn't hold the file, though it is there, can't see its names: the disk + // reaches it by a name it stores in other bytes (macOS keeps `Québec.shp` decomposed, + // and opens it by its composed name; Windows matches non-ASCII letters in either case). + // Each spelling is tried instead, as for a folder that can't be listed. + let listed = list(path).filter(|entries| { + let name = path.file_name().map(|n| n.as_encoded_bytes()).unwrap_or_default(); + entries.iter().any(|n| n.as_encoded_bytes().eq_ignore_ascii_case(name)) || path.symlink_metadata().is_err() + }); + let file = match (path.file_name(), listed) { (Some(name), Some(entries)) => { let name = name.as_encoded_bytes(); let exact = entries.iter().any(|n| n.as_encoded_bytes() == name); @@ -342,6 +350,9 @@ pub(crate) mod tests { fn spellings_are_lower_case_first() { assert_eq!(case_spellings("cpg"), ["cpg", "CPG", "CPg", "CpG", "Cpg", "cPG", "cPg", "cpG"]); assert_eq!(case_spellings("7z"), ["7z", "7Z"]); + // A part looked up on its own takes the spelling the listing takes. + assert_eq!(case_spellings("cpg"), crate::dbf::CPG_SPELLINGS); + assert_eq!(case_spellings("dbf"), crate::dbf::DBF_SPELLINGS); } /// One extension's file is found by its spellings, in that order. diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs index e9bc44e1be..e1c14cf7dc 100644 --- a/crates/data/src/sync.rs +++ b/crates/data/src/sync.rs @@ -8,11 +8,18 @@ use serde::{Deserialize, Serialize}; /// the files that weren't there. A Shapefile is its `.shp`, `.shx`, `.dbf`, `.prj` and `.cpg` /// (the ones its reader opens); a GeoJSON file is itself. Only the contents count: a file /// copied, touched or moved to another disk with the same bytes is the same file. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct FileSync { /// Each file by its name beside the source (`parcels.dbf`), with its stamp, or `None` for /// one that wasn't there, so a `.prj` added since counts as a change too. pub files: Vec<(String, Option)>, + /// Whether the record was made looking for each part in every spelling (#1958). A record + /// without it, from an older RustGIS, looked for a `.shx` and `.prj` in lower case alone, so + /// one it recorded missing may have been there in another case: that alone isn't a change. + /// An older RustGIS reading a project leaves it out, and a record saved again without it is + /// compared as one of its own, which is what it is then. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub every_spelling: bool, } /// One file as it was. @@ -209,14 +216,15 @@ mod native { /// parts were found in any case), and it is that file, unchanged only when its size and hash /// are those recorded. Where case is told apart, a part under a new spelling (`ROADS.dbf` /// beside the recorded `ROADS.DBF`) is a new file. - fn pair(files: &[(String, Option)], now: &[(String, PathBuf)]) -> (Vec, Vec) { + fn pair(sync: &FileSync, now: &[(String, PathBuf)]) -> (Vec, Vec) { + let files = &sync.files; let mut theirs = vec![false; now.len()]; let mut pairs = Vec::with_capacity(files.len()); for (name, was) in files { let one_file = |(n, p): &(String, PathBuf)| n.eq_ignore_ascii_case(name) && crate::sidecar::same_file(&p.with_file_name(name), p); let exact = now.iter().position(|(n, _)| n == name); - let missed = || now.iter().position(|part| missed_by_an_older_lookup(files, name, was, part)); + let missed = || now.iter().position(|part| missed_by_an_older_lookup(sync, name, was, part)); let (pair, at) = match exact { Some(i) => (Pair::At(i), Some(i)), None => match missed() { @@ -238,9 +246,14 @@ mod native { /// Whether the record's `name`, recorded missing, is a name an older RustGIS looked a part up /// by alone: before #1958 a Shapefile's `.shx` and `.prj` were looked for in lower case only /// (`ROADS.shx`, `ROADS.prj`), so one there in another case (`ROADS.SHX`) was recorded - /// missing. Such an entry says nothing of the file there now under another spelling. - fn older_lookup_name(files: &[(String, Option)], name: &str, was: &Option) -> bool { - let Some((stem, _)) = files.first().and_then(|(n, _)| n.rsplit_once('.')) else { return false }; + /// missing. Such an entry says nothing of the file there now under another spelling. A + /// record this version made ([`FileSync::every_spelling`]) looked for every spelling, so one + /// there now that it recorded missing was added since. + fn older_lookup_name(sync: &FileSync, name: &str, was: &Option) -> bool { + if sync.every_spelling { + return false; + } + let Some((stem, _)) = sync.files.first().and_then(|(n, _)| n.rsplit_once('.')) else { return false }; was.is_none() && [".shx", ".prj"].iter().any(|ext| name.strip_suffix(ext) == Some(stem)) } @@ -250,13 +263,8 @@ mod native { /// where each record of the `.shp` is, which a publish writes again from the `.shp`; a /// `.prj` is said ([`FileSync::unverified_among`]), and a publish takes it only when the file /// read in that system is the layer as it was read. - fn missed_by_an_older_lookup( - files: &[(String, Option)], - name: &str, - was: &Option, - now: &(String, PathBuf), - ) -> bool { - older_lookup_name(files, name, was) && now.0 != name && now.0.eq_ignore_ascii_case(name) && now.1.exists() + fn missed_by_an_older_lookup(sync: &FileSync, name: &str, was: &Option, now: &(String, PathBuf)) -> bool { + older_lookup_name(sync, name, was) && now.0 != name && now.0.eq_ignore_ascii_case(name) && now.1.exists() } /// The name a differing file is reported under: the one it has now when it is there (a part @@ -316,7 +324,7 @@ mod native { }; files.push((name, stamp)); } - Ok(FileSync { files }) + Ok(FileSync { files, every_spelling: true }) } /// The files of the source at `path` as just written: each of `written` (a path and @@ -352,7 +360,7 @@ mod native { }; files.push((name, stamp)); } - Ok(FileSync { files }) + Ok(FileSync { files, every_spelling: true }) } /// Runs `read`, which reads the source at `path`, and returns with its result the files @@ -400,7 +408,7 @@ mod native { // the part was missing (but for a name an older lookup missed it by). let spellings = crate::sidecar::case_spellings(&ext.to_ascii_lowercase()); let rank = spellings.iter().position(|e| e == ext).unwrap_or(0); - let excused = older_lookup_name(&self.files, name, was); + let excused = older_lookup_name(self, name, was); spellings.iter().enumerate().filter(|(_, e)| *e != ext).all(|(i, e)| { let other = p.with_extension(e); let there = other.symlink_metadata().is_ok(); @@ -418,7 +426,7 @@ mod native { pub(crate) fn unverified_among(&self, now: &[(String, PathBuf)]) -> Vec { self.files .iter() - .filter_map(|(name, was)| now.iter().find(|part| missed_by_an_older_lookup(&self.files, name, was, part))) + .filter_map(|(name, was)| now.iter().find(|part| missed_by_an_older_lookup(self, name, was, part))) .map(|(n, _)| n.clone()) .collect() } @@ -426,7 +434,7 @@ mod native { /// As [`FileSync::changed`], with the source's parts as [`FileSync::parts_of`] gives them. pub(crate) fn changed_among(&self, now: &[(String, PathBuf)]) -> Result> { let mut changed = Vec::new(); - let (pairs, theirs) = pair(&self.files, now); + let (pairs, theirs) = pair(self, now); // Files there now that aren't the record's; not a name `parts` gives for a part that // isn't there. for ((name, p), theirs) in now.iter().zip(&theirs) { @@ -474,7 +482,7 @@ mod native { return Vec::new(); } let now = parts(path); - let (pairs, theirs) = pair(&self.files, &now); + let (pairs, theirs) = pair(self, &now); let mut differ: Vec = now.iter().zip(&theirs).filter(|((_, p), theirs)| !**theirs && p.exists()).map(|((n, _), _)| n.clone()).collect(); for ((name, was), pair) in self.files.iter().zip(&pairs) { @@ -687,7 +695,7 @@ mod tests { let mut lonlat = Dataset::new("a".to_string(), GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); lonlat.features = vec![Feature { id: 1, geometry: Some(Geometry::Point(Coord { x: 7.4, y: 46.9 })), attrs: vec![Value::Int(4)] }].into(); - let files = FileSync { files: Vec::new() }; + let files = FileSync::default(); let plain = Synced::record(files.clone(), &lonlat).unwrap(); assert_eq!(plain, Synced { files: files.clone(), rows: rows_digest(&lonlat).unwrap(), native: None }); assert_eq!(serde_json::to_string(&plain).unwrap(), r#"{"files":{"files":[]},"rows":"#.to_string() + &plain.rows.to_string() + "}"); @@ -726,9 +734,17 @@ mod tests { #[test] fn a_record_round_trips() { - let sync = FileSync { files: vec![("a.geojson".into(), Some(FileStamp { len: 2, sha256: "ab".into() })), ("a.prj".into(), None)] }; + let sync = FileSync { + files: vec![("a.geojson".into(), Some(FileStamp { len: 2, sha256: "ab".into() })), ("a.prj".into(), None)], + every_spelling: true, + }; let text = serde_json::to_string(&sync).unwrap(); - assert_eq!(text, r#"{"files":[["a.geojson",{"len":2,"sha256":"ab"}],["a.prj",null]]}"#); + assert_eq!(text, r#"{"files":[["a.geojson",{"len":2,"sha256":"ab"}],["a.prj",null]],"every_spelling":true}"#); assert_eq!(serde_json::from_str::(&text).unwrap(), sync); + // A record from an older RustGIS has no mark: it reads, and is saved again, without one. + let old = r#"{"files":[["a.geojson",{"len":2,"sha256":"ab"}],["a.prj",null]]}"#; + let read = serde_json::from_str::(old).unwrap(); + assert!(!read.every_spelling); + assert_eq!(serde_json::to_string(&read).unwrap(), old); } } diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 4aa98d4808..b221821f65 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -831,7 +831,7 @@ fn download_layer_with( let (downloaded, note) = loop { let pages = match step { Step::Done(bytes, note) => break (Downloaded::Bytes(bytes), note), - Step::Decoded(dataset, report, note) => break (Downloaded::Read(Box::new((*dataset, report))), note), + Step::Decoded(dataset, report, note) => break (Downloaded::Read(Box::new((*dataset, *report))), note), // A first answer that timed out says how to add a large layer instead. Step::Failed(e) => return Err(crate::sources::message_with_address(url, &cache::large_file_hint(e))), Step::Fetch(pages) => pages, diff --git a/crates/ui-egui/src/serviceui.rs b/crates/ui-egui/src/serviceui.rs index b9c10780f8..daea087b12 100644 --- a/crates/ui-egui/src/serviceui.rs +++ b/crates/ui-egui/src/serviceui.rs @@ -646,7 +646,7 @@ pub(crate) fn go_on(app: &mut RustGisApp, mut landed: Landed, left: usize, reach match step { Step::Decoded(dataset, report, note) => { noted(app, &landed, note); - app.add_landed_read(landed, *dataset, report); + app.add_landed_read(landed, *dataset, *report); } Step::Failed(e) => { app.session.request_failed(&landed.params, &e); diff --git a/crates/ui-egui/src/syncmark.rs b/crates/ui-egui/src/syncmark.rs index cfcd24cd12..110a75292f 100644 --- a/crates/ui-egui/src/syncmark.rs +++ b/crates/ui-egui/src/syncmark.rs @@ -234,7 +234,7 @@ mod tests { rows: Weak::new(), fields: Vec::new(), crs: None, - synced: Synced { files: FileSync { files: Vec::new() }, rows: 7, native: None }, + synced: Synced { files: FileSync::default(), rows: 7, native: None }, digest: None, job: Some(Job { slot, stop: Arc::new(AtomicBool::new(false)), current }), retry: None, From d2cb9d0faf5ad0fb2640665865cf79f9f7a9b332 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:57:06 -0600 Subject: [PATCH 8/9] fix(data): Shapefile parts the listing misses are looked for, and only Shapefile records are marked (#1958) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A part with no listed entry beside a listed .shp (Québec.shp beside a decomposed Québec.prj on macOS, école.dbf beside ÉCOLE.SHP on Windows) is looked for by its spellings before it counts as missing. - Only a Shapefile's record carries every_spelling, so other layers' records are saved as before. - Old .prj files that can't be removed are said in one note with a count. --- crates/data/src/io.rs | 13 ++++++--- crates/data/src/publish.rs | 54 +++++++++++++++++++++++++++++++++++++- crates/data/src/sidecar.rs | 46 +++++++++++++++++++++----------- crates/data/src/sync.rs | 31 ++++++++++++++++------ 4 files changed, 116 insertions(+), 28 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 0fdf7beb85..7de20985b0 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1463,10 +1463,17 @@ impl ShapefileSaved { if names.len() == 1 { "it said" } else { "they said" } )); } - for p in &self.kept_prj { - let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + if !self.kept_prj.is_empty() { + let names: Vec = + self.kept_prj.iter().map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()).collect(); + let (what, says) = match names.len() { + 1 => ("1 old .prj".to_string(), "still says"), + n => (format!("{n} old .prj files"), "still say"), + }; notes.push(format!( - "{path}: {name} could not be removed and still says the old file's system, though the one written has no .prj form; remove it by hand" + "{path}: {what} could not be removed and {says} the old file's system, though the one written has no .prj form ({}); remove {} by hand", + names.join(", "), + if names.len() == 1 { "it" } else { "them" } )); } notes diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 1c9a4dcc7e..5542536cfc 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -1493,7 +1493,23 @@ mod tests { crate::io::KEEP_STALE.set(false); let (_, _, notes) = saved.unwrap(); assert!(dir.path().join("ROADS.PRJ").is_file()); - assert!(notes.len() == 1 && notes[0].contains("ROADS.PRJ could not be removed and still says the old file's system"), "{notes:?}"); + assert!( + notes.len() == 1 + && notes[0].contains("1 old .prj could not be removed and still says the old file's system") + && notes[0].contains("(ROADS.PRJ)"), + "{notes:?}" + ); + // Two spellings kept, where case is told apart: one note counts them. + if !crate::sidecar::tests::ignores_case(dir.path()) { + std::fs::write(dir.path().join("ROADS.prj"), crate::io::WGS84_PRJ).unwrap(); + crate::io::KEEP_STALE.set(true); + let saved = crate::io::write_path_to(&parcels(), &path, gnomonic, &Default::default()); + crate::io::KEEP_STALE.set(false); + let (_, _, notes) = saved.unwrap(); + let kept: Vec<_> = notes.iter().filter(|n| n.contains("could not be removed")).collect(); + assert!(kept.len() == 1 && kept[0].contains("2 old .prj files could not be removed and still say"), "{notes:?}"); + std::fs::remove_file(dir.path().join("ROADS.prj")).unwrap(); + } // A folder at the name says no system: nothing to refuse or remove, and nothing said. std::fs::remove_file(dir.path().join("ROADS.PRJ")).unwrap(); std::fs::create_dir(dir.path().join("ROADS.PRJ")).unwrap(); @@ -1613,6 +1629,42 @@ mod tests { assert_eq!(crate::source::FeatureSource::info(&source).crs, "EPSG:32616"); } + /// A `.shp` the folder lists under the name it is opened by, beside parts the disk stores in + /// other bytes (`Qu\u{e9}bec.shp` beside `Que\u{301}bec.prj` and `.cpg` on macOS), is read with + /// them: a part with no listed entry is looked for by its spellings before it is taken as + /// missing. Without them nothing is found, and the reader says nothing of a `.prj`. Skipped + /// where the disk tells the two names apart. + #[test] + fn parts_the_disk_stores_otherwise_beside_a_listed_shp_are_read() { + let dir = tempfile::tempdir().unwrap(); + let made = tempfile::tempdir().unwrap(); + let mut ds = parcels(); + ds.crs = Some(Crs::parse("EPSG:32616").unwrap()); + crate::io::write_path_in(&ds, &made.path().join("x.shp"), ds.crs.unwrap()).unwrap(); + std::fs::write(made.path().join("x.cpg"), "UTF-8").unwrap(); + for (ext, stem) in + [("shp", "Qu\u{e9}bec"), ("shx", "Qu\u{e9}bec"), ("dbf", "Qu\u{e9}bec"), ("prj", "Que\u{301}bec"), ("cpg", "Que\u{301}bec")] + { + std::fs::copy(made.path().join(format!("x.{ext}")), dir.path().join(format!("{stem}.{ext}"))).unwrap(); + } + let composed = dir.path().join("Qu\u{e9}bec.shp"); + if !dir.path().join("Qu\u{e9}bec.prj").exists() { + return; + } + let files = Sidecars::shapefile(&composed); + assert!(files.existing("prj").is_some() && files.existing("cpg").is_some()); + assert!(files.duplicates_note().is_none()); + let (back, report) = crate::io::read_path(&composed).unwrap(); + assert_eq!(back.crs, ds.crs, "{report:?}"); + let source = crate::source::shp::ShpSource::open_path(&composed, "q").unwrap(); + assert_eq!(crate::source::FeatureSource::info(&source).crs, "EPSG:32616"); + // With them gone, there are none. + std::fs::remove_file(dir.path().join("Que\u{301}bec.prj")).unwrap(); + std::fs::remove_file(dir.path().join("Que\u{301}bec.cpg")).unwrap(); + let files = Sidecars::shapefile(&composed); + assert!(files.existing("prj").is_none() && files.existing("cpg").is_none()); + } + /// A record this version made looked for every spelling of each part: a `.PRJ` added after /// it recorded none (`roads.prj` missing) is a change, which the desktop's watch and publish /// see, though a record from before #1958 would have been excused it. diff --git a/crates/data/src/sidecar.rs b/crates/data/src/sidecar.rs index 0967d80836..b235bb6ee5 100644 --- a/crates/data/src/sidecar.rs +++ b/crates/data/src/sidecar.rs @@ -159,6 +159,14 @@ impl Sidecars { part.push(path.with_file_name(n)); } } + // A part the listing has no entry for may still be there under bytes the disk + // matches otherwise (`Que\u{301}bec.prj` beside `Québec.shp` on macOS, `école.dbf` + // beside `ÉCOLE.SHP` on Windows): its spellings are tried before it is taken as + // missing. + let upper = upper_of(&file); + for (ext, part) in found.iter_mut().filter(|(e, part)| *e != "shp" && part.is_empty()) { + probe(&file, ext, upper, &mut Vec::new(), part); + } file } _ => { @@ -172,22 +180,7 @@ impl Sidecars { seen.push(identity(path, &meta)); part.push(path.to_path_buf()); } - // Where case is ignored every spelling reaches one file: it is named as the - // `.shp`'s case suggests, the guess nearest the name it has. - let mut spellings = case_spellings(ext); - if upper { - spellings.sort_by_key(|s| !upper_extension(s.as_bytes())); - } - for spelling in spellings { - let p = path.with_extension(&spelling); - let Ok(meta) = p.symlink_metadata() else { continue }; - let id = identity(&p, &meta); - if seen.contains(&id) { - continue; - } - seen.push(id); - part.push(p); - } + probe(path, ext, upper, &mut seen, part); } path.to_path_buf() } @@ -313,6 +306,27 @@ impl Sidecars { } } +/// Adds to `part` each spelling of `ext` beside `path` that is there in any form, one per file +/// (by [`Identity`], with those in `seen` already taken). Where case is ignored every spelling +/// reaches one file: it is named as the `.shp`'s case suggests (`upper`), the guess nearest the +/// name it has. +fn probe(path: &Path, ext: &str, upper: bool, seen: &mut Vec, part: &mut Vec) { + let mut spellings = case_spellings(ext); + if upper { + spellings.sort_by_key(|s| !upper_extension(s.as_bytes())); + } + for spelling in spellings { + let p = path.with_extension(&spelling); + let Ok(meta) = p.symlink_metadata() else { continue }; + let id = identity(&p, &meta); + if seen.contains(&id) { + continue; + } + seen.push(id); + part.push(p); + } +} + /// The names in `path`'s folder whose stem is `path`'s in any ASCII case; `None` when the /// folder can't be listed or holds more than [`LISTING_LIMIT`] entries, which it stops at. fn list(path: &Path) -> Option> { diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs index e1c14cf7dc..2f0d509f27 100644 --- a/crates/data/src/sync.rs +++ b/crates/data/src/sync.rs @@ -13,11 +13,13 @@ pub struct FileSync { /// Each file by its name beside the source (`parcels.dbf`), with its stamp, or `None` for /// one that wasn't there, so a `.prj` added since counts as a change too. pub files: Vec<(String, Option)>, - /// Whether the record was made looking for each part in every spelling (#1958). A record + /// Whether the record of a Shapefile was made looking for each part in every spelling + /// (#1958); set on a Shapefile's record only, so another's is saved as before. A record /// without it, from an older RustGIS, looked for a `.shx` and `.prj` in lower case alone, so /// one it recorded missing may have been there in another case: that alone isn't a change. - /// An older RustGIS reading a project leaves it out, and a record saved again without it is - /// compared as one of its own, which is what it is then. + /// An older RustGIS reading a project says the key is unknown and leaves it out, and a record + /// it saves again without it is compared as one of its own, excusing those parts, which is + /// what it is then. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub every_spelling: bool, } @@ -305,6 +307,11 @@ mod native { Ok(hash) } + /// Whether a record is of a Shapefile: its first file, the source, is a `.shp`. + fn shapefile_record(files: &[(String, Option)]) -> bool { + files.first().is_some_and(|(n, _)| n.rsplit_once('.').is_some_and(|(_, e)| e.eq_ignore_ascii_case("shp"))) + } + /// Bytes as a progress count. fn count(bytes: u64) -> usize { usize::try_from(bytes).unwrap_or(usize::MAX) @@ -324,7 +331,7 @@ mod native { }; files.push((name, stamp)); } - Ok(FileSync { files, every_spelling: true }) + Ok(FileSync { every_spelling: shapefile_record(&files), files }) } /// The files of the source at `path` as just written: each of `written` (a path and @@ -360,7 +367,7 @@ mod native { }; files.push((name, stamp)); } - Ok(FileSync { files, every_spelling: true }) + Ok(FileSync { every_spelling: shapefile_record(&files), files }) } /// Runs `read`, which reads the source at `path`, and returns with its result the files @@ -735,16 +742,24 @@ mod tests { #[test] fn a_record_round_trips() { let sync = FileSync { - files: vec![("a.geojson".into(), Some(FileStamp { len: 2, sha256: "ab".into() })), ("a.prj".into(), None)], + files: vec![("a.shp".into(), Some(FileStamp { len: 2, sha256: "ab".into() })), ("a.prj".into(), None)], every_spelling: true, }; let text = serde_json::to_string(&sync).unwrap(); - assert_eq!(text, r#"{"files":[["a.geojson",{"len":2,"sha256":"ab"}],["a.prj",null]],"every_spelling":true}"#); + assert_eq!(text, r#"{"files":[["a.shp",{"len":2,"sha256":"ab"}],["a.prj",null]],"every_spelling":true}"#); assert_eq!(serde_json::from_str::(&text).unwrap(), sync); // A record from an older RustGIS has no mark: it reads, and is saved again, without one. - let old = r#"{"files":[["a.geojson",{"len":2,"sha256":"ab"}],["a.prj",null]]}"#; + let old = r#"{"files":[["a.shp",{"len":2,"sha256":"ab"}],["a.prj",null]]}"#; let read = serde_json::from_str::(old).unwrap(); assert!(!read.every_spelling); assert_eq!(serde_json::to_string(&read).unwrap(), old); + // Only a Shapefile's record is marked: a GeoJSON file's is saved as before. + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("a.geojson"), "{}").unwrap(); + std::fs::write(dir.path().join("b.shp"), "x").unwrap(); + let geojson = FileSync::read(&dir.path().join("a.geojson")).unwrap(); + assert!(!geojson.every_spelling); + assert!(!serde_json::to_string(&geojson).unwrap().contains("every_spelling")); + assert!(FileSync::read(&dir.path().join("b.shp")).unwrap().every_spelling); } } From 0c57055c5dfed64959d10e30d34980141a191ec6 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:07:25 -0600 Subject: [PATCH 9/9] refactor(data): look for unlisted Shapefile parts only beside a non-ASCII name, and say so in the docs (#1958) --- crates/data/src/publish.rs | 6 ++++-- crates/data/src/sidecar.rs | 20 +++++++++++++------- crates/data/src/sync.rs | 2 +- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 5542536cfc..9ebe3a6e95 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -1632,8 +1632,10 @@ mod tests { /// A `.shp` the folder lists under the name it is opened by, beside parts the disk stores in /// other bytes (`Qu\u{e9}bec.shp` beside `Que\u{301}bec.prj` and `.cpg` on macOS), is read with /// them: a part with no listed entry is looked for by its spellings before it is taken as - /// missing. Without them nothing is found, and the reader says nothing of a `.prj`. Skipped - /// where the disk tells the two names apart. + /// missing. Without them nothing is found, and the reader says nothing of a `.prj`. It runs + /// only on a disk that doesn't tell the two forms apart (macOS) and skips elsewhere; the + /// Windows path, a part in another non-ASCII case (`école.dbf` beside `ÉCOLE.SHP`), has no + /// test. #[test] fn parts_the_disk_stores_otherwise_beside_a_listed_shp_are_read() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/data/src/sidecar.rs b/crates/data/src/sidecar.rs index b235bb6ee5..7ec1100ede 100644 --- a/crates/data/src/sidecar.rs +++ b/crates/data/src/sidecar.rs @@ -1,8 +1,9 @@ //! The files that go with a file, in whichever ASCII case the folder spells them. A whole //! Shapefile is found once per read, publish or save from one listing of its folder -//! ([`Sidecars`]), so every reader and writer picks the same file and writes each part back -//! under the name it has; one file of one extension is found by trying its spellings -//! ([`find_one`]), without listing the folder. +//! ([`Sidecars`]), with a part the listing has no entry for looked for by its spellings when the +//! name isn't ASCII (the disk may store it in other bytes), so every reader and writer picks the +//! same file and writes each part back under the name it has; one file of one extension is found +//! by trying its spellings ([`find_one`]), without listing the folder. use std::path::{Path, PathBuf}; @@ -110,7 +111,10 @@ fn identity(path: &Path, meta: &std::fs::Metadata) -> Identity { impl Sidecars { /// The parts of the Shapefile whose `.shp` is at `path` ([`SHAPEFILE`]), named its stem and - /// an extension in any ASCII case, from one listing of its folder. Where the folder ignores + /// an extension in any ASCII case, from one listing of its folder; a part it has no entry for, + /// beside a `.shp` whose stem isn't ASCII, is looked for by its spellings, as the disk may + /// store its name in other bytes than the `.shp`'s (decomposed, or in another non-ASCII + /// case), and goes by the `.shp`'s spelling then. Where the folder ignores /// case, a stem in another case (`roads.shp` for `ROADS.SHP`) names the same files and they /// keep the names they have; where it tells cases apart, only the stem as the file has it /// counts. When the folder can't be listed or holds more than [`LISTING_LIMIT`] entries, @@ -162,10 +166,12 @@ impl Sidecars { // A part the listing has no entry for may still be there under bytes the disk // matches otherwise (`Que\u{301}bec.prj` beside `Québec.shp` on macOS, `école.dbf` // beside `ÉCOLE.SHP` on Windows): its spellings are tried before it is taken as - // missing. + // missing. An ASCII stem needs none: the listing already matched its case. let upper = upper_of(&file); - for (ext, part) in found.iter_mut().filter(|(e, part)| *e != "shp" && part.is_empty()) { - probe(&file, ext, upper, &mut Vec::new(), part); + if !stem.is_ascii() { + for (ext, part) in found.iter_mut().filter(|(e, part)| *e != "shp" && part.is_empty()) { + probe(&file, ext, upper, &mut Vec::new(), part); + } } file } diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs index 2f0d509f27..6a4a5f6e1d 100644 --- a/crates/data/src/sync.rs +++ b/crates/data/src/sync.rs @@ -402,7 +402,7 @@ mod native { /// it does): for a Shapefile, also that no other spelling of a part's name is there but /// one that reaches the same file. `false` whenever something differs or might. fn sized_as_recorded(&self, path: &Path) -> bool { - let shapefile = self.files.first().is_some_and(|(n, _)| n.to_ascii_lowercase().ends_with(".shp")); + let shapefile = shapefile_record(&self.files); self.files.iter().all(|(name, was)| { let p = path.with_file_name(name); let sized = match was {