diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs
index b1fcfd932a..4b79678a30 100644
--- a/crates/data/src/dbf.rs
+++ b/crates/data/src/dbf.rs
@@ -544,6 +544,21 @@ pub(crate) fn read_cpg(path: &std::path::Path, ldid: u8, notes: &mut crate::loss
cpg_result(try_read_cpg(path), ldid, notes)
}
+/// As [`read_cpg`], for the `.cpg` a Shapefile's [`crate::sidecar::Sidecars`] found (`None` when
+/// it has none): that one file, so the reader takes the spelling publish and save write back.
+/// Anything there but a regular file (a folder, a named pipe) is said as unreadable.
+pub(crate) fn read_cpg_at(cpg: Option<&std::path::Path>, ldid: u8, notes: &mut crate::loss::Notes) -> crate::Result>> {
+ let Some(cpg) = cpg else { return Ok(None) };
+ let read = match read_one_cpg(cpg) {
+ Ok(Some(bytes)) => Ok(Some(bytes)),
+ Ok(None) => Err(std::io::Error::other("not a regular file")),
+ // Gone since its folder was listed: there is none.
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(e) => Err(e),
+ };
+ cpg_result(read, ldid, notes)
+}
+
/// An optional declaration can fall back after an I/O failure, but Cancel must end the read.
fn cpg_result(result: std::io::Result >>, ldid: u8, notes: &mut crate::loss::Notes) -> crate::Result >> {
match result.map_err(crate::DataError::from) {
@@ -561,34 +576,23 @@ 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 >> {
- use std::io::Read;
let mut non_file = false;
for ext in CPG_SPELLINGS {
- let candidate = path.with_extension(ext);
- match open_regular_file(&candidate) {
- Ok(None) => {
- non_file = true;
- continue;
- }
- Ok(Some(file)) => {
- crate::provenance::opened(&candidate, &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 read_one_cpg(&path.with_extension(ext)) {
+ Ok(None) => non_file = true,
+ Ok(Some(bytes)) => return Ok(Some(bytes)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
@@ -599,6 +603,20 @@ fn try_read_cpg(path: &std::path::Path) -> std::io::Result >> {
Ok(None)
}
+/// The `.cpg` at `cpg` when it is a regular file (`None` when it is something else, never opened
+/// for reading), its bytes recorded as a source input.
+fn read_one_cpg(cpg: &std::path::Path) -> std::io::Result >> {
+ use std::io::Read;
+ let Some(file) = open_regular_file(cpg)? else { return Ok(None) };
+ crate::provenance::opened(cpg, &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);
+ }
+ Ok(Some(bytes))
+}
+
/// Reads the first present code-page spelling without recording a provenance input.
fn read_declaration_cpg(path: &std::path::Path) -> std::io::Result >> {
use std::io::{Error, ErrorKind, Read};
diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs
index 68d8e50c76..7de20985b0 100644
--- a/crates/data/src/io.rs
+++ b/crates/data/src/io.rs
@@ -1436,9 +1436,55 @@ pub struct PathWritten {
pub declaration_changes: DeclarationChanges,
}
+/// 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(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,
+}
+
+impl ShapefileSaved {
+ /// What to say of it, each note naming `path`.
+ pub(crate) 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" }
+ ));
+ }
+ 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}: {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
+ }
+}
+
/// As [`write_path`], in the coordinate system `crs` (a GeoPackage, Shapefile or FlatGeobuf; see
/// [`write_bytes_in`]). Refused on a place `crs` can't hold, naming its feature, as it gives no
/// notes to say it; [`write_path_to`] writes the feature without its geometry instead, and says so.
+/// For the same reason 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_as(ds, path, crs, &GpkgTable::default(), false, false).map(|(written, _)| written.left_out)
}
@@ -1523,14 +1569,69 @@ fn write_path_as(
}
}
"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()
+ )));
+ }
+ // 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();
+ let old_prj: Vec = if shapefile_prj(crs).is_none() {
+ // 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()
+ };
+ // Only a caller that takes the notes (`leaving_out`, [`write_path_to`]) can be told.
+ if let Some(prj) = old_prj.first().filter(|_| !leaving_out) {
+ 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 parts: Vec<(std::path::PathBuf, Vec)> = parts.into_iter().map(|(e, bytes)| (shapefile_part(path, e), bytes)).collect();
+ 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();
let staged = stage_shapefile(&parts)?;
- let declaration_changes =
- if compare { shapefile_declaration_changes(path, &parts, &ds.fields) } else { DeclarationChanges::Unchanged };
- let kept = place_shapefile(path, &staged)?;
- let notes = unplaced.into_iter().chain(kept_backups_note(path, &kept).map(crate::loss::Note::plain)).collect();
+ // 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()
+ )));
+ }
+ let declaration_changes = if compare {
+ shapefile_declaration_changes(path, files.existing("dbf").or(files.unreadable("dbf")), &parts, &ds.fields)
+ } else {
+ DeclarationChanges::Unchanged
+ };
+ let kept = place_shapefile(files.file(), &staged, &stale)?;
+ 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))
+ .chain(saved.notes(&path.display().to_string()).into_iter().map(crate::loss::Note::plain))
+ .collect();
Ok((PathWritten { left_out, table: None, notes, declaration_changes }, placed))
}
_ if crs != Crs::LonLat && !holds_a_system(&ext) => {
@@ -1549,16 +1650,24 @@ fn write_path_as(
}
}
-/// Compares the old attributes independently of the state of the geometry file.
-fn shapefile_declaration_changes(path: &Path, parts: &[(std::path::PathBuf, Vec)], fields: &[Field]) -> DeclarationChanges {
+/// 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>,
+ parts: &[(std::path::PathBuf, Vec)],
+ fields: &[Field],
+) -> DeclarationChanges {
let Some(after) = parts
.iter()
- .find(|(part, _)| part.extension().is_some_and(|e| e == "dbf"))
+ .find(|(part, _)| part.extension().is_some_and(|e| e.eq_ignore_ascii_case("dbf")))
.and_then(|(_, bytes)| crate::dbf::written_declarations(bytes, fields.len()))
else {
return DeclarationChanges::Unavailable;
};
- match crate::dbf::read_declarations(&dbf_sidecar(path)) {
+ let Some(old_dbf) = old_dbf else { return DeclarationChanges::Unchanged };
+ match crate::dbf::read_declarations(old_dbf) {
Ok((before, ldid)) => compare_dbf_declarations(&before, &after, fields, crate::dbf::declaration_names(path, &before, ldid)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => DeclarationChanges::Unchanged,
Err(_) => DeclarationChanges::Unavailable,
@@ -1655,12 +1764,6 @@ fn compare_dbf_declarations(
DeclarationChanges::compared(changed, unresolved)
}
-/// 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`]).
@@ -1692,13 +1795,19 @@ 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.
+/// rolls back the same way. Once all have landed, the old parts and the `stale` files are
+/// removed: the spatial indexes that would no longer match (`.qix`, `.sbn`, `.sbx`, as the
+/// folder spells them, [`crate::sidecar::Sidecars`]) and any other the caller replaces (an old
+/// `.prj` in a system that has none).
///
/// Returns the old parts that landed but couldn't be removed afterwards, each as the hidden copy
/// that holds it ([`kept_backups_note`] says them). When a part fails to land and every old part is
/// put back, the error names `path` and says nothing changed.
-pub(crate) fn place_shapefile(path: &Path, staged: &[(std::path::PathBuf, std::path::PathBuf)]) -> Result> {
+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();
@@ -1770,16 +1879,9 @@ pub(crate) fn place_shapefile(path: &Path, staged: &[(std::path::PathBuf, std::p
// 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.
- 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));
- }
+ // One that can't be removed is left: a caller that replaces one it must say looks again.
+ for p in stale {
+ let _ = remove_stale(p);
}
// Every part is renamed within `path`'s folder.
sync_folder(path);
@@ -1793,6 +1895,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)]
@@ -4283,13 +4400,18 @@ fn csv_stopped() -> DataError {
// ---------------------------------------------------------------------------------------------
// 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")
+}
+
+/// 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) }
}
/// Finds the attributes beside a Shapefile, accepting every ASCII case of `.dbf` in whole
@@ -4302,26 +4424,32 @@ pub fn dbf_sidecar(path: &Path) -> std::path::PathBuf {
/// 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 = crate::loss::Notes::new();
let shp = crate::provenance::read(path)?;
- let shx = if shx.is_file() { Some(crate::provenance::read(shx)?) } else { None };
+ let shx = match shx {
+ Some(shx) => Some(crate::provenance::read(shx)?),
+ None => None,
+ };
let dbf = crate::provenance::read(dbf)?;
// The `.dbf`'s language driver, for what an unreadable `.cpg` falls back to.
let ldid = dbf.get(29).copied().unwrap_or(0);
- let cpg = crate::dbf::read_cpg(path, ldid, &mut notes)?;
+ let cpg = crate::dbf::read_cpg_at(files.existing("cpg").or(files.unreadable("cpg")), ldid, &mut notes)?;
crate::dbf::unused_cst(cpg.as_deref(), ldid, || crate::dbf::has_cst(path), &mut notes);
- let parts = ShapefileParts { shp, shx, dbf, prj: crate::raster::read_prj(path), cpg };
+ let parts = ShapefileParts { shp, shx, dbf, prj: files.existing("prj").and_then(crate::raster::read_prj_file), cpg };
let (ds, mut report) = read_shapefile_parts(parts, name, crs)?;
report.messages.extend(notes.prefixed(name));
+ report.messages.extend(files.other_shp_note());
+ report.messages.extend(files.duplicates_note());
Ok((ds, report))
}
@@ -7218,7 +7346,7 @@ fn shapefile_parts_within(
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
@@ -7696,7 +7824,7 @@ mod tests {
let parts = |tag: &str| vec![(shp.clone(), format!("{tag} shp").into_bytes()), (dbf.clone(), format!("{tag} dbf").into_bytes())];
KEEP_BACKUPS.set(true);
- let kept = place_shapefile(&shp, &stage_shapefile(&parts("new"))?);
+ let kept = place_shapefile(&shp, &stage_shapefile(&parts("new"))?, &[]);
KEEP_BACKUPS.set(false);
let kept = kept?;
assert_eq!(std::fs::read(&shp)?, b"new shp");
@@ -7710,7 +7838,7 @@ mod tests {
}
// Clean: nothing kept, nothing said, nothing left beside the file.
- let kept = place_shapefile(&shp, &stage_shapefile(&parts("newer"))?)?;
+ let kept = place_shapefile(&shp, &stage_shapefile(&parts("newer"))?, &[])?;
assert!(kept.is_empty() && kept_backups_note(&shp, &kept).is_none());
assert_eq!(entries()?, 2);
@@ -7718,7 +7846,7 @@ mod tests {
let staged = stage_shapefile(&parts("newest"))?;
let (gone, _) = staged.iter().find(|(_, target)| *target == dbf).ok_or("no staged .dbf")?;
std::fs::remove_file(gone)?;
- let error = place_shapefile(&shp, &staged).err().ok_or("placed")?.to_string();
+ let error = place_shapefile(&shp, &staged, &[]).err().ok_or("placed")?.to_string();
assert!(
error.contains(&format!("{}: ", shp.display())) && error.ends_with("the old file was put back, nothing changed"),
"{error}"
@@ -7733,7 +7861,7 @@ mod tests {
let staged = stage_shapefile(&parts)?;
let (gone, _) = staged.iter().find(|(_, target)| *target == fresh).ok_or("no staged .shp")?;
std::fs::remove_file(gone)?;
- let error = place_shapefile(&fresh, &staged).err().ok_or("placed")?.to_string();
+ let error = place_shapefile(&fresh, &staged, &[]).err().ok_or("placed")?.to_string();
assert!(error.ends_with("nothing was written") && !error.contains("put back"), "{error}");
assert_eq!(entries()?, 2);
diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs
index 1c5044a867..0b70934fd9 100644
--- a/crates/data/src/lib.rs
+++ b/crates/data/src/lib.rs
@@ -56,6 +56,7 @@ pub mod rows;
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/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 4c0081e879..9ebe3a6e95 100644
--- a/crates/data/src/publish.rs
+++ b/crates/data/src/publish.rs
@@ -28,6 +28,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};
@@ -140,18 +141,19 @@ 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)>,
}
/// 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::dbf::open_regular_file`]).
fn read_part(p: &Path, size_error: fn(&str, u64) -> String) -> Result>> {
use std::io::Read;
let file = match crate::dbf::open_regular_file(p) {
@@ -177,25 +179,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.
@@ -229,23 +225,45 @@ impl Original {
/// checking Cancel between features; serializing one geometry runs to its end.
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, none a link, and none there but a regular
+ // file (a named pipe at `roads.cpg` beside the `roads.CPG` read): another program may read it.
+ 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)?;
+ if std::fs::metadata(&part).is_ok_and(|m| !m.is_file()) {
+ return Err(refused(path, format!("{} is there but isn't a regular file", part.display())));
+ }
+ }
}
- 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")?;
+ // A `.prj` a record from an older RustGIS couldn't speak for.
+ let unverified_prj: Vec =
+ 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);
- 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 {
@@ -286,6 +304,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,
@@ -414,35 +446,59 @@ 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, native) = crate::sync::digests(&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, and so
+ // is one the reader would now take instead of the one written.
+ let again = Sidecars::shapefile(path);
+ if let Some(other) = again.other_shp() {
+ return Err(refused(
+ path,
+ format!(
+ "{} appeared while the layer was written, a Shapefile of the same name in another case whose parts can't be told from this one's",
+ other.display()
+ ),
+ ));
+ }
+ unchanged(&again, "while the layer was written")?;
+ for ext in std::iter::once("shp").chain(crate::sidecar::SHAPEFILE_COMPANIONS) {
+ let (was, now) = (files.path(ext), again.path(ext));
+ if was != now {
+ return Err(refused(
+ path,
+ format!("{} is there now and would be read instead of {}, which this would write", now.display(), was.display()),
+ ));
+ }
+ }
+ Ok(again)
})();
- if let Err(e) = checked {
- crate::io::unstage(&staged);
- return Err(e);
- }
- let kept = crate::io::place_shapefile(path, &staged)?;
+ 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();
+ let kept = crate::io::place_shapefile(files.file(), &staged, &stale)?;
notes.extend(crate::io::kept_backups_note(path, &kept));
- Ok(Published { files, read: read_back, rows, native, features: ds.features.len(), notes })
+ Ok(Published { files: record, read: read_back, rows, native, features: ds.features.len(), notes })
}
/// `ds` in the file's coordinate system `crs` (`None`: longitude/latitude), from the system it
@@ -1125,6 +1181,641 @@ 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 where the file system ignores case can name `ROADS.shx` for `ROADS.SHX`:
+ /// there the same file by its size and hash, so the layer still publishes, under the names
+ /// the files have. Where case is told apart, those names are other files, so it is refused.
+ #[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());
+ }
+ }
+ let rows: Vec<_> = 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, another `.shp` of the name in another case (`ROADS.shp`) put
+ /// there while the layer is written refuses the publish, with the file as it was.
+ #[test]
+ fn a_shp_in_another_case_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::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.
+ #[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]
+ 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();
+ let (_, _, notes) = crate::io::write_path_to(&ds, &path, Crs::LonLat, &Default::default()).unwrap();
+ assert!(notes.is_empty(), "{notes:?}");
+ 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);
+ }
+
+ /// 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 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();
+ 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();
+ let (_, _, notes) = 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);
+ assert_eq!(notes.len(), 1, "{notes:?}");
+ let note = notes[0].as_str();
+ assert!(note.contains("ROADS.dbf (not ROADS.DBF)") && note.contains("leaves the others as they are"), "{note}");
+ assert!(report.messages.iter().any(|m| m.as_str() == note), "{:?}", 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 writes none and removes the
+ /// 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_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 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 (_, _, notes) = crate::io::write_path_to(&parcels(), &path, gnomonic, &Default::default()).unwrap();
+ 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("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();
+ 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
+ /// 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() {
+ // 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);
+ };
+ 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, "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}");
+ }
+ }
+
+ /// 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 `.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`. 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();
+ 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.
+ #[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)]
+ #[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::Builder::new()
+ .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)));
+ })
+ .unwrap();
+ // 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
+ /// 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]
@@ -1184,7 +1875,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);
@@ -1329,7 +2020,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 7e07700611..00adb0896d 100644
--- a/crates/data/src/raster/mod.rs
+++ b/crates/data/src/raster/mod.rs
@@ -2154,10 +2154,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)) => {
@@ -2216,16 +2216,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..7ec1100ede
--- /dev/null
+++ b/crates/data/src/sidecar.rs
@@ -0,0 +1,493 @@
+//! 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`]), 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};
+
+/// 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.
+#[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),
+ _ => false,
+ }
+}
+
+/// 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 (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)>,
+}
+
+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; 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,
+ /// 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| upper_extension(e.as_encoded_bytes()));
+ let mut found: Vec<(&'static str, Vec)> = SHAPEFILE.iter().map(|&e| (e, Vec::new())).collect();
+ // 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);
+ 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 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 !(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));
+ }
+ }
+ // 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. An ASCII stem needs none: the listing already matched its case.
+ let upper = upper_of(&file);
+ 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
+ }
+ _ => {
+ let upper = upper_of(path);
+ for (ext, part) in &mut found {
+ let mut seen: Vec = Vec::new();
+ // 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());
+ }
+ probe(path, ext, upper, &mut seen, part);
+ }
+ 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 && p.is_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();
+ 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()
+ .map(|p| {
+ let file = p.is_file();
+ (p, file)
+ })
+ .collect();
+ Part { ext, found }
+ })
+ .collect();
+ Sidecars { upper, 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> {
+ 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`]):
+ /// 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 {
+ 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(", ")
+ ))
+ }
+}
+
+/// 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> {
+ 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 (i, entry) in std::fs::read_dir(dir).ok()?.enumerate() {
+ if i >= LISTING_LIMIT {
+ return None;
+ }
+ let entry = entry.ok()?;
+ 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) {
+ entries.push(name);
+ }
+ }
+ 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"]);
+ // 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.
+ #[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);
+ // A folder at the name is no file.
+ std::fs::create_dir(dir.path().join("a.cpg")).unwrap();
+ 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), 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)]
+ #[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");
+ }
+ // 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_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 0bd07e6f98..b7f4e453bb 100644
--- a/crates/data/src/source/shp.rs
+++ b/crates/data/src/source/shp.rs
@@ -32,7 +32,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)
}
@@ -138,7 +138,8 @@ 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())));
}
@@ -146,8 +147,10 @@ impl ShpSource {
let stamps = [Stamp::of(path), Stamp::of(&dbf)];
let mut notes = crate::loss::Notes::new();
let table = read_table(&dbf)?;
- let cpg = crate::dbf::read_cpg(path, table.ldid, &mut notes)?;
+ let cpg = crate::dbf::read_cpg_at(files.existing("cpg").or(files.unreadable("cpg")), table.ldid, &mut notes)?;
crate::dbf::unused_cst(cpg.as_deref(), table.ldid, || crate::dbf::has_cst(path), &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) {
@@ -177,7 +180,7 @@ impl ShpSource {
if table.rows != index.count {
notes.push(format!("the .shp holds {} shapes and the .dbf {} rows; rows are matched by position", index.count, table.rows));
}
- let prj = if crs.is_none() { crate::raster::read_prj(path) } else { None };
+ let prj = if crs.is_none() { files.existing("prj").and_then(crate::raster::read_prj_file) } else { None };
// A system given or in a `.prj` (even one that can't be used, said on its own) isn't one
// RustGIS assumed, as for a Shapefile read whole.
let declared = crs.is_some() || prj.is_some();
diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs
index d3ce1d08a0..6a4a5f6e1d 100644
--- a/crates/data/src/sync.rs
+++ b/crates/data/src/sync.rs
@@ -8,11 +8,20 @@ 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 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 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,
}
/// One file as it was.
@@ -174,27 +183,98 @@ 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()
}
+ /// 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(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(sync, 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 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. 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))
+ }
+
+ /// 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(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
+ /// 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) {
@@ -227,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)
@@ -246,16 +331,30 @@ mod native {
};
files.push((name, stamp));
}
- Ok(FileSync { files })
+ Ok(FileSync { every_spelling: shapefile_record(&files), files })
}
/// The files of the source at `path` as just written: each of `written` (a path and
/// 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,
@@ -268,7 +367,7 @@ mod native {
};
files.push((name, stamp));
}
- Ok(FileSync { files })
+ Ok(FileSync { every_spelling: shapefile_record(&files), files })
}
/// Runs `read`, which reads the source at `path`, and returns with its result the files
@@ -295,25 +394,77 @@ 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))
+ }
+
+ /// 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 = shapefile_record(&self.files);
+ 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 };
+ // 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, 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();
+ 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, 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();
- // 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() {
+ 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) {
+ 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((_, p)) = now.iter().find(|(n, _)| n == 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;
};
+ 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) {
@@ -324,7 +475,7 @@ mod native {
_ => false,
};
if !same {
- changed.push(name.clone());
+ changed.push(shown(name, part));
}
}
Ok(changed)
@@ -334,18 +485,26 @@ 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 (pairs, theirs) = pair(self, &now);
let mut differ: Vec =
- now.iter().filter(|(name, p)| !self.files.iter().any(|(n, _)| n == 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) {
+ 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,
_ => false,
};
if !same {
- differ.push(name.clone());
+ differ.push(part.map_or_else(|| name.clone(), |part| shown(name, part)));
}
}
differ
@@ -436,6 +595,51 @@ mod tests {
assert_eq!(sync.changed(&path).unwrap(), ["a.CPG"]);
}
+ /// 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();
+ 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();
+ 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();
+ 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();
@@ -498,7 +702,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() + "}");
@@ -537,9 +741,25 @@ 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.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]]}"#);
+ 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.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);
}
}
diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs
index 2a9a9d1ffc..80bdbcbd65 100644
--- a/crates/data/tests/integration/shapefile_encoding.rs
+++ b/crates/data/tests/integration/shapefile_encoding.rs
@@ -428,6 +428,35 @@ 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::Builder::new()
+ .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()));
+ })
+ .unwrap();
+ // 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() {
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,