use std::collections::BTreeMap;
use std::path::Path;
use crate::error::{DatasetError, IoOp, IoResultExt as _, Result};
use geo::{Area as _, Coord, LineString, MultiPolygon, Polygon};
use serde_json::{Value, json};
use shapefile::dbase::{FieldValue, Record as DbaseRecord};
use shapefile::record::traits::HasXY;
use super::areas::{Area, AreasFile, write_areas_geojson, write_collection, write_json};
use super::areas_tiles::write_areas_pmtiles;
use super::country::{BoundaryFile, CountryConfig, split_antimeridian};
struct BoundaryRecord {
index: usize,
code: String,
name: String,
parent: Option<String>,
shape: MultiPolygon<f64>,
}
fn field(record: &DbaseRecord, field: &str) -> Option<String> {
record.get(field).and_then(|value| match value {
FieldValue::Character(text) => text.clone(),
_ => None,
})
}
pub fn run(config: &CountryConfig, boundaries_dir: &Path, out: &Path, max_zoom: u8) -> Result<()> {
let boundaries = &config.boundaries;
let units = boundaries
.units
.as_ref()
.ok_or_else(|| DatasetError::data("the country config has no boundaries.units"))?;
let parents_file = boundaries
.parents
.as_ref()
.ok_or_else(|| DatasetError::data("the country config has no boundaries.parents"))?;
let mut parent_names: BTreeMap<String, String> = BTreeMap::new();
for record in read_records(parents_file, boundaries_dir)? {
if parents_file.skip.iter().any(|code| code == &record.code) {
continue;
}
if parent_names
.insert(record.code.clone(), record.name)
.is_some()
{
return Err(DatasetError::data(format!(
"the parent file repeats the code {} (record {})",
record.code, record.index
)));
}
}
let unit_records = read_records(units, boundaries_dir)?;
let mut seen: BTreeMap<String, usize> = BTreeMap::new();
let mut skipped = 0_usize;
let mut areas: Vec<Area> = Vec::with_capacity(unit_records.len());
for record in unit_records {
if let Some(first) = seen.insert(record.code.clone(), record.index) {
return Err(DatasetError::data(format!(
"the units file repeats the code {}: records {first} and {}",
record.code, record.index
)));
}
let parent_code = record.parent.as_deref().ok_or_else(|| {
DatasetError::data({
format!(
"record {} ({}) has no {} value",
record.index, record.code, "parent"
)
})
})?;
if parents_file.skip.iter().any(|code| code == parent_code) {
skipped += 1;
tracing::debug!(
record = record.index,
code = record.code.as_str(),
parent = parent_code,
"area skipped with its parent"
);
continue;
}
let parent_name = parent_names.get(parent_code).ok_or_else(|| {
DatasetError::data({
format!(
"record {} ({}) names the parent {parent_code}, which the parent file lacks",
record.index, record.code
)
})
})?;
if record.shape.unsigned_area() == 0.0 {
return Err(DatasetError::data(format!(
"record {} ({}) encloses no area: its rings are empty or degenerate",
record.index, record.code
)));
}
areas.push(Area {
id: config.area_id(&record.code),
code: Some(record.code.clone()),
name: record.name,
country: config.code.to_uppercase(),
level: boundaries.level.clone(),
parent_id: Some(parent_code.to_string()),
parent_name: Some(parent_name.clone()),
region_code: Some(parent_code.to_string()),
shape: split_antimeridian(&record.shape),
});
}
areas.sort_by(|a, b| a.id.cmp(&b.id));
config.check_counts(&areas)?;
std::fs::create_dir_all(out).io_at(IoOp::Create, out)?;
let file = AreasFile {
areas,
boundary_release: boundaries.release.clone(),
attribution: boundaries.attribution.clone(),
};
write_areas_geojson(&out.join("areas.geojson"), &file)?;
write_collection(
&out.join("gaps.geojson"),
std::iter::empty::<geojson::Feature>(),
&file.boundary_release,
&file.attribution,
)?;
let report = json!({
"areas": file.areas.len(),
"parents": parent_names.len(),
"gaps": Vec::<Value>::new(),
"skipped": skipped,
"orphans": 0,
"invariants": boundaries.invariants,
"source": "shapefile",
"release": file.boundary_release,
"datum": datum(units, boundaries_dir),
"subtype": boundaries.level,
"attribution": file.attribution,
});
write_json(&out.join("areas-report.json"), &report)?;
let gaps = Vec::new();
write_areas_pmtiles(
&out.join("areas.pmtiles"),
&file.areas,
&gaps,
max_zoom,
&file.attribution,
Some(config.bounds),
)?;
tracing::info!(
areas = file.areas.len(),
parents = parent_names.len(),
out = %out.display(),
"official areas written"
);
Ok(())
}
fn datum(units: &BoundaryFile, boundaries_dir: &Path) -> &'static str {
let prj = boundaries_dir.join(units.member.replace(".shp", ".prj"));
let Ok(text) = std::fs::read_to_string(prj) else {
return "unknown";
};
if text.contains("NAD83") || text.contains("NAD_1983") || text.contains("North_American_1983") {
"NAD83"
} else if text.contains("GDA2020") {
"GDA2020"
} else if text.contains("GDA94") {
"GDA94"
} else if text.contains("WGS_1984") || text.contains("WGS 84") {
"WGS84"
} else {
"unknown"
}
}
fn read_records(file: &BoundaryFile, boundaries_dir: &Path) -> Result<Vec<BoundaryRecord>> {
let path = boundaries_dir.join(&file.member);
let dbf = path.with_extension("dbf");
let shapes: Vec<shapefile::Shape> = shapefile::ShapeReader::from_path(&path)
.io_at(IoOp::Open, &path)?
.read()
.io_at(IoOp::Read, &path)?;
let mut table = shapefile::dbase::ReaderBuilder::new()
.with_encoding(shapefile::dbase::encoding::UnicodeLossy)
.open(&dbf)
.io_at(IoOp::Open, &dbf)?;
let records = table.read().io_at(IoOp::Read, &dbf)?;
if shapes.len() != records.len() {
return Err(DatasetError::data(format!(
"{} holds {} shapes and {} records",
path.display(),
shapes.len(),
records.len()
)));
}
let mut found = Vec::with_capacity(records.len());
let mut empty = 0_usize;
for (index, (shape, record)) in shapes.iter().zip(records.iter()).enumerate() {
if matches!(shape, shapefile::Shape::NullShape) {
empty += 1;
continue;
}
let code = field(record, &file.fields.code).unwrap_or_default();
let code = code.trim().to_string();
if code.is_empty() {
return Err(DatasetError::data(format!(
"record {index} of {} has a blank {} code",
path.display(),
file.fields.code
)));
}
let name = field(record, &file.fields.name)
.ok_or_else(|| {
DatasetError::data(format!(
"record {index} ({code}) has no {}",
file.fields.name
))
})?
.trim()
.to_string();
if name.is_empty() {
return Err(DatasetError::data(format!(
"record {index} ({code}) has a blank {} name",
file.fields.name
)));
}
let parent = match &file.fields.parent {
Some(key) => Some(
field(record, key)
.ok_or_else(|| {
DatasetError::data(format!("record {index} ({code}) has no {key}"))
})?
.trim()
.to_string(),
),
None => None,
};
let shape = shape_to_multi(shape, index, &code)?;
found.push(BoundaryRecord {
index,
code,
name,
parent,
shape,
});
}
if empty > 0 {
tracing::info!(
file = %path.display(),
records = empty,
"records without a shape are not areas"
);
}
Ok(found)
}
fn shape_to_multi(shape: &shapefile::Shape, index: usize, code: &str) -> Result<MultiPolygon<f64>> {
let polygons = match shape {
shapefile::Shape::Polygon(polygon) => rings_to_polygons(polygon.rings()),
shapefile::Shape::PolygonM(polygon) => rings_to_polygons(polygon.rings()),
shapefile::Shape::PolygonZ(polygon) => rings_to_polygons(polygon.rings()),
_ => {
return Err(DatasetError::data(format!(
"record {index} ({code}) is not a polygon"
)));
}
};
if polygons.is_empty() {
return Err(DatasetError::data(format!(
"record {index} ({code}) holds no ring"
)));
}
Ok(MultiPolygon(polygons))
}
fn rings_to_polygons<T: HasXY>(rings: &[shapefile::PolygonRing<T>]) -> Vec<Polygon<f64>> {
let mut polygons: Vec<Polygon<f64>> = Vec::new();
let mut open: Option<(LineString<f64>, Vec<LineString<f64>>)> = None;
for ring in rings {
let points: Vec<Coord<f64>> = ring
.points()
.iter()
.map(|p| Coord { x: p.x(), y: p.y() })
.collect();
if points.len() < 4 {
continue;
}
match ring {
shapefile::PolygonRing::Outer(_) => {
if let Some((exterior, holes)) = open.take() {
polygons.push(Polygon::new(exterior, holes));
}
open = Some((LineString::new(points), Vec::new()));
}
shapefile::PolygonRing::Inner(_) => {
if let Some((_, holes)) = open.as_mut() {
holes.push(LineString::new(points));
}
}
}
}
if let Some((exterior, holes)) = open.take() {
polygons.push(Polygon::new(exterior, holes));
}
polygons
}
#[cfg(test)]
mod tests {
use super::*;
use crate::areas::read_areas_geojson;
use crate::country::official_id;
use std::path::PathBuf;
fn config_dir() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("data/datasets/countries")
}
fn us_config() -> CountryConfig {
CountryConfig::load(&config_dir().join("us.json")).expect("us.json loads")
}
struct Fixture {
code: &'static str,
name: &'static str,
parent: Option<&'static str>,
rings: Vec<(Vec<(f64, f64)>, bool)>,
}
fn outer(x0: f64, y0: f64, x1: f64, y1: f64) -> (Vec<(f64, f64)>, bool) {
(vec![(x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)], true)
}
fn hole(x0: f64, y0: f64, x1: f64, y1: f64) -> (Vec<(f64, f64)>, bool) {
(
vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)],
false,
)
}
fn write_file(dir: &Path, name: &str, parent_field: bool, records: &[Fixture]) {
let mut table = shapefile::dbase::TableWriterBuilder::new()
.add_character_field("GEOID".try_into().expect("field"), 16)
.add_character_field("NAME".try_into().expect("field"), 60);
if parent_field {
table = table.add_character_field("STATEFP".try_into().expect("field"), 4);
}
let mut writer =
shapefile::Writer::from_path(dir.join(name), table).expect("shapefile writer");
for fixture in records {
let rings: Vec<shapefile::PolygonRing<shapefile::Point>> = fixture
.rings
.iter()
.map(|(points, clockwise)| {
let points: Vec<shapefile::Point> = points
.iter()
.map(|(x, y)| shapefile::Point::new(*x, *y))
.collect();
if *clockwise {
shapefile::PolygonRing::Outer(points)
} else {
shapefile::PolygonRing::Inner(points)
}
})
.collect();
let shape = shapefile::Polygon::with_rings(rings);
let mut record = DbaseRecord::default();
record.insert(
"GEOID".into(),
FieldValue::Character(Some(fixture.code.into())),
);
record.insert(
"NAME".into(),
FieldValue::Character(Some(fixture.name.into())),
);
if let Some(parent) = fixture.parent {
record.insert("STATEFP".into(), FieldValue::Character(Some(parent.into())));
}
writer
.write_shape_and_record(&shape, &record)
.expect("record written");
}
}
fn fixture_config(units: &str, parents: &str, invariants: &str) -> CountryConfig {
let json = format!(
r#"{{
"code": "us", "name": "Fixture",
"unit": {{"one": "county", "many": "counties"}},
"parent": {{"one": "state", "many": "states"}},
"bounds": [-170.0, 18.0, -66.0, 72.0],
"boundaries": {{
"source": "shapefile", "release": "2026-10-06.0", "level": "county",
"attribution": "Boundaries: fixture",
"licence_id": "CC0-1.0",
"units": {{"url": "https://x/{units}", "member": "{units}", "sha256": "pending",
"fields": {{"code": "GEOID", "name": "NAME", "parent": "STATEFP"}}}},
"parents": {{"url": "https://y/{parents}", "member": "{parents}", "sha256": "pending",
"fields": {{"code": "GEOID", "name": "NAME"}}, "skip": ["72"]}},
"invariants": {invariants}
}}
}}"#
);
CountryConfig::from_json_str(&json).expect("fixture config parses")
}
fn two_parents() -> Vec<Fixture> {
vec![
Fixture {
code: "06",
name: "California",
parent: None,
rings: vec![outer(0.0, 0.0, 10.0, 10.0)],
},
Fixture {
code: "36",
name: "New York",
parent: None,
rings: vec![outer(10.0, 0.0, 20.0, 10.0)],
},
Fixture {
code: "72",
name: "Puerto Rico",
parent: None,
rings: vec![outer(20.0, 0.0, 30.0, 10.0)],
},
]
}
fn run_with(units: &[Fixture], invariants: &str) -> (tempfile::TempDir, PathBuf, Result<()>) {
let tmp = tempfile::tempdir().expect("tempdir");
let dir = tmp.path().join("boundaries");
std::fs::create_dir_all(&dir).expect("mkdir");
write_file(&dir, "units.shp", true, units);
write_file(&dir, "parents.shp", false, &two_parents());
let config = fixture_config("units.shp", "parents.shp", invariants);
let out = tmp.path().join("out");
let result = run(&config, &dir, &out, 8);
(tmp, out, result)
}
fn three_counties() -> Vec<Fixture> {
vec![
Fixture {
code: "06001",
name: "Alameda County",
parent: Some("06"),
rings: vec![outer(0.0, 0.0, 10.0, 10.0)],
},
Fixture {
code: "36001",
name: "Albany County",
parent: Some("36"),
rings: vec![outer(10.0, 0.0, 20.0, 10.0)],
},
Fixture {
code: "06002",
name: "Amador County",
parent: Some("06"),
rings: vec![outer(0.0, 10.0, 10.0, 20.0)],
},
]
}
#[test]
fn the_ids_are_the_official_ones() {
let (tmp, out, result) = run_with(&three_counties(), r#"{"areas": 3}"#);
result.expect("fixture runs");
let file = read_areas_geojson(&out.join("areas.geojson")).expect("areas.geojson reads");
assert_eq!(file.areas.len(), 3);
for area in &file.areas {
let code = area.code.as_ref().expect("a code");
assert_eq!(area.id, official_id("us", code), "{code}");
assert_eq!(area.level, "county");
assert_eq!(area.country, "US");
assert_eq!(
area.parent_name.as_deref(),
Some(match code.as_str() {
"36001" => "New York",
_ => "California",
})
);
}
let ids: Vec<&str> = file.areas.iter().map(|a| a.id.as_str()).collect();
assert!(ids.is_sorted(), "sorted by id: {ids:?}");
drop(tmp);
}
#[test]
fn a_multipart_record_with_a_hole_keeps_its_hole() {
let units = vec![
Fixture {
code: "06001",
name: "Two parts",
parent: Some("06"),
rings: vec![
outer(0.0, 0.0, 4.0, 10.0),
hole(1.0, 1.0, 2.0, 2.0),
outer(6.0, 0.0, 10.0, 10.0),
],
},
Fixture {
code: "06002",
name: "Plain",
parent: Some("06"),
rings: vec![outer(0.0, 20.0, 10.0, 30.0)],
},
];
let (tmp, out, result) = run_with(&units, r#"{"areas": 2}"#);
result.expect("fixture runs");
let file = read_areas_geojson(&out.join("areas.geojson")).expect("reads");
let area = file
.areas
.iter()
.find(|a| a.code.as_deref() == Some("06001"))
.expect("06001");
assert_eq!(area.shape.0.len(), 2, "two polygons, one per outer ring");
assert_eq!(area.shape.0[0].interiors().len(), 1, "the hole stays");
assert!((area.shape.unsigned_area() - 79.0).abs() < 1e-9);
drop(tmp);
}
#[test]
fn holes_stay_out_of_the_land() {
let units = vec![Fixture {
code: "06001",
name: "Square with hole",
parent: Some("06"),
rings: vec![outer(0.0, 0.0, 10.0, 10.0), hole(4.0, 4.0, 6.0, 6.0)],
}];
let (tmp, out, result) = run_with(&units, r#"{"areas": 1}"#);
result.expect("fixture runs");
let file = read_areas_geojson(&out.join("areas.geojson")).expect("reads");
assert!((file.areas[0].shape.unsigned_area() - 96.0).abs() < 1e-9);
drop(tmp);
}
#[test]
fn a_repeated_or_blank_code_is_an_error_naming_it() {
let repeated = vec![
Fixture {
code: "01001",
name: "A",
parent: Some("06"),
rings: vec![outer(0.0, 0.0, 1.0, 1.0)],
},
Fixture {
code: "01001",
name: "B",
parent: Some("06"),
rings: vec![outer(2.0, 0.0, 3.0, 1.0)],
},
];
let (_tmp, _out, result) = run_with(&repeated, "{}");
let err = result.expect_err("a repeated code");
let text = geolith::error::report(&err);
assert!(text.contains("01001"), "{text}");
assert!(text.contains("records 0 and 1"), "{text}");
let blank = vec![Fixture {
code: " ",
name: "Blank",
parent: Some("06"),
rings: vec![outer(0.0, 0.0, 1.0, 1.0)],
}];
let (_tmp, _out, result) = run_with(&blank, "{}");
let err = result.expect_err("a blank code");
assert!(geolith::error::report(&err).contains("blank"), "{err:#}");
}
#[test]
fn an_orphan_parent_is_an_error() {
let units = vec![Fixture {
code: "01001",
name: "Orphan",
parent: Some("99"),
rings: vec![outer(0.0, 0.0, 1.0, 1.0)],
}];
let (_tmp, _out, result) = run_with(&units, "{}");
let err = result.expect_err("no parent 99");
let text = geolith::error::report(&err);
assert!(text.contains("99") && text.contains("01001"), "{text}");
}
#[test]
fn a_parent_in_skip_drops_its_children() {
let units = vec![
Fixture {
code: "72001",
name: "Skipped",
parent: Some("72"),
rings: vec![outer(0.0, 0.0, 1.0, 1.0)],
},
Fixture {
code: "06001",
name: "Kept",
parent: Some("06"),
rings: vec![outer(2.0, 0.0, 3.0, 1.0)],
},
];
let (tmp, out, result) = run_with(&units, r#"{"areas": 1, "parents": 1}"#);
result.expect("the skipped parent drops its child");
let file = read_areas_geojson(&out.join("areas.geojson")).expect("reads");
assert_eq!(file.areas.len(), 1);
assert_eq!(file.areas[0].code.as_deref(), Some("06001"));
let text = std::fs::read_to_string(out.join("areas-report.json")).expect("report");
let report: Value = serde_json::from_str(&text).expect("report json");
assert_eq!(report["skipped"], 1);
drop(tmp);
}
#[test]
fn the_invariants_run_on_the_real_areas() {
let (_tmp, _out, result) = run_with(&three_counties(), r#"{"areas": 4}"#);
let err = result.expect_err("3 areas, 4 expected");
assert!(
geolith::error::report(&err).contains("expected 4 areas, found 3"),
"{err:#}"
);
}
#[test]
fn a_degenerate_area_is_an_error() {
let units = vec![
Fixture {
code: "06001",
name: "Line",
parent: Some("06"),
rings: vec![(vec![(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (0.0, 0.0)], true)],
},
Fixture {
code: "06002",
name: "Fine",
parent: Some("06"),
rings: vec![outer(0.0, 20.0, 1.0, 21.0)],
},
];
let (_tmp, _out, result) = run_with(&units, "{}");
let err = result.expect_err("a zero-area record");
assert!(geolith::error::report(&err).contains("06001"), "{err:#}");
}
#[test]
fn nothing_in_the_output_spans_more_than_180_degrees() {
let units = vec![Fixture {
code: "02016",
name: "Aleutians West",
parent: Some("06"),
rings: vec![(
vec![
(179.0, -10.0),
(-179.5, -10.0),
(-179.5, 10.0),
(179.0, 10.0),
(179.0, -10.0),
],
true,
)],
}];
let (tmp, out, result) = run_with(&units, "{}");
result.expect("fixture runs");
let file = read_areas_geojson(&out.join("areas.geojson")).expect("reads");
for area in &file.areas {
for polygon in &area.shape.0 {
for ring in std::iter::once(polygon.exterior()).chain(polygon.interiors()) {
let xs: Vec<f64> = ring.0.iter().map(|c| c.x).collect();
let lo = xs.iter().fold(f64::INFINITY, |a, b| a.min(*b));
let hi = xs.iter().fold(f64::NEG_INFINITY, |a, b| a.max(*b));
assert!(
hi - lo <= 180.0 + 1e-9,
"{} spans {lo}..{hi}",
area.code.as_deref().unwrap_or("?")
);
}
}
}
drop(tmp);
}
#[test]
fn the_report_names_the_source_and_the_release() {
let (tmp, out, result) = run_with(&three_counties(), r#"{"areas": 3}"#);
result.expect("fixture runs");
let text = std::fs::read_to_string(out.join("areas-report.json")).expect("report");
let report: Value = serde_json::from_str(&text).expect("report json");
assert_eq!(report["areas"], 3);
assert_eq!(report["parents"], 2);
assert_eq!(report["orphans"], 0);
assert_eq!(report["source"], "shapefile");
assert_eq!(report["release"], "2026-10-06.0");
assert_eq!(report["subtype"], "county");
assert_eq!(report["gaps"].as_array().map(Vec::len), Some(0));
drop(tmp);
}
#[test]
fn the_us_config_boundary_files_are_readable() {
let config = us_config();
let units = config.boundaries.units.as_ref().expect("units");
assert_eq!(units.member, "tl_2026_us_county.shp");
assert_eq!(
config.boundaries.parents.as_ref().expect("parents").skip,
vec!["60", "66", "69", "72", "78"]
);
}
}