Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion apps/rustgis-python/python/rustgis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,7 +697,14 @@ def __iter__(self) -> Iterator[Layer]:
"""The active map's layers, top first."""
return iter([Layer._of(self, int(entry["id"])) for entry in self.layers()])

def add_data(self, path: PathLike, name: Optional[str] = None, **params: Any) -> Any:
def add_data(
self,
path: PathLike,
name: Optional[str] = None,
*,
encoding: Optional[Union[str, int]] = None,
**params: Any,
) -> Any:
"""Adds a file as a layer, or as a standalone table when it has no geometry.

Args:
Expand All @@ -707,6 +714,8 @@ def add_data(self, path: PathLike, name: Optional[str] = None, **params: Any) ->
name: The layer's name (the file's name when left out). Native multi-layer imports
apply it only to the first layer. GDAL or DuckDB files split into several layers keep
their generated names and report the ignored name in a notice.
encoding: A dBASE code page name or number (e.g. ``"Shift_JIS"`` or ``932``) for
Shapefiles and dBASE tables, including ZIP members. Overrides file metadata.
**params: More ``layer.addData`` parameters, e.g. ``layer=`` for one table of a
GeoPackage, ``x=`` and ``y=`` for a CSV's coordinate columns.

Expand All @@ -717,6 +726,8 @@ def add_data(self, path: PathLike, name: Optional[str] = None, **params: Any) ->
command, args = self._data_command(path)
if name is not None:
params["name"] = name
if encoding is not None:
params["encoding"] = encoding
return self._outputs(self.run(command, {**args, **params}))

def add_geojson(self, data: Union[Dict[str, Any], str, PathLike], name: str = "GeoJSON") -> Any:
Expand Down
50 changes: 32 additions & 18 deletions crates/data/src/dbf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,17 @@ impl DbfEncoding {
}
}

pub(crate) fn parse(name: &str) -> crate::Result<Self> {
if name.len() <= MAX_CPG_BYTES
&& let Some(encoding) = Self::from_name(name.trim())
{
return Ok(encoding);
}
Err(crate::DataError::Format(
"unsupported dBASE encoding; use an ASCII-compatible WHATWG encoding name (such as UTF-8, Shift_JIS, GBK, EUC-KR, Big5 or windows-1252) or code page 437, 850, 852, 861, 865, 866, 874, 932, 936, 949, 950, 10000, 10007, 1250–1258 or 65001".into(),
))
}

fn from_number(number: u16) -> Option<Self> {
// DOS 437, 850, 852, 861 and 865 go to dbase's OEM adapter; DOS 866 and the other pages
// decoded here keep encoding_rs, because dbase's yore adapter is strict for those and can
Expand Down Expand Up @@ -192,17 +203,8 @@ fn page_name(page: u16) -> Option<&'static str> {
})
}

/// The end of each note of text that isn't UTF-8: why a `.dbf`'s text was read as UTF-8, and what
/// names another encoding. A `.cpg` comes before the code page, so text is read as UTF-8 only when
/// no `.cpg` names another encoding RustGIS reads: the file names none, names UTF-8, or names a
/// code page RustGIS can't decode.
pub(crate) const NO_OTHER_ENCODING: &str = "no .cpg file names another encoding RustGIS reads (a .cpg file containing 950 names Big5)";

/// The end of each note of text that isn't valid in `encoding`: for UTF-8, why the text was read as
/// it ([`NO_OTHER_ENCODING`]); for another, that the file declares it.
pub(crate) fn cause(encoding: &str) -> String {
if encoding == "UTF-8" { NO_OTHER_ENCODING.to_string() } else { format!("the .cpg or the .dbf's language driver declares {encoding}") }
}
/// Advice in a loss notice for DBF text that could not be decoded.
pub(crate) const ENCODING_HINT: &str = "if the file uses another code page, supply it with encoding or a .cpg file";

/// What opening a `.dbf` says of its field names that aren't valid in its `encoding` ([`not_utf8`]),
/// naming the first five by their column (from 1). `None` when there are none.
Expand All @@ -214,11 +216,8 @@ pub(crate) fn not_utf8_names_note(columns: &[usize], encoding: &str) -> Option<c
};
let named: Vec<String> = columns.iter().take(5).map(usize::to_string).collect();
let more = if columns.len() > 5 { format!(" and {} more", columns.len() - 5) } else { String::new() };
let text = format!(
"{what} read with U+FFFD in place of the bytes that can't be read, in {label} {}{more}; {}",
named.join(", "),
cause(encoding)
);
let text =
format!("{what} read with U+FFFD in place of the bytes that can't be read, in {label} {}{more}; {ENCODING_HINT}", named.join(", "));
Some(crate::loss::Note::loss(crate::loss::LossCode::ChangedEncoding, text))
}

Expand Down Expand Up @@ -522,6 +521,21 @@ pub(crate) fn unused_cst(cpg: Option<&[u8]>, ldid: u8, present: impl FnOnce() ->
}
}

/// Reads sidecars only when the caller relies on their declarations.
pub(crate) fn cpg_for_read(
path: &std::path::Path,
ldid: u8,
override_name: Option<&str>,
notes: &mut crate::loss::Notes,
) -> crate::Result<Option<Vec<u8>>> {
if override_name.is_some() {
return Ok(None);
}
let cpg = read_cpg(path, ldid, notes)?;
unused_cst(cpg.as_deref(), ldid, || has_cst(path), notes);
Ok(cpg)
}

/// The decoder named by a bounded UTF-8 CPG label, with its optional BOM and padding removed.
fn cpg_encoding(cpg: Option<&[u8]>) -> Option<DbfEncoding> {
cpg.filter(|b| b.len() <= MAX_CPG_BYTES)
Expand Down Expand Up @@ -1002,15 +1016,15 @@ mod tests {
let two = two.as_str();
assert!(two.starts_with("2 field names aren't valid UTF-8 and were read with U+FFFD"), "{two}");
assert!(two.contains("in fields 3, 7;"), "{two}");
assert!(two.ends_with(NO_OTHER_ENCODING), "{two}");
assert!(two.ends_with(ENCODING_HINT), "{two}");
let many = not_utf8_names_note(&[1, 2, 3, 4, 5, 6, 7], "UTF-8").unwrap();
let many = many.as_str();
assert!(many.contains("in fields 1, 2, 3, 4, 5 and 2 more;"), "{many}");
// A declared code page is named, as what the file declares.
assert_eq!(
not_utf8_names_note(&[1], "Big5").as_ref().map(crate::loss::Note::as_str),
Some(
"1 field name isn't valid Big5 and was read with U+FFFD in place of the bytes that can't be read, in field 1; the .cpg or the .dbf's language driver declares Big5"
"1 field name isn't valid Big5 and was read with U+FFFD in place of the bytes that can't be read, in field 1; if the file uses another code page, supply it with encoding or a .cpg file"
)
);
}
Expand Down
Loading
Loading