Validate places.toml and the record's place fields

This commit is contained in:
swaits committed 2026-11-20 09:24:18 -07:00
1 parent aad93a246c
commit 18dff9650d
4 files changed
+420

No files matched your search

+1
View File
@@ -13,6 +13,7 @@ jobs:
with:
python-version: "3.12"
- run: python3 tools/validate.py
- run: python3 -m unittest discover tools/tests -p "test_places*.py"
# A change to a fact needs a new [[history]] entry (docs/schema.md), and trail-numbers.txt may
# only be appended to. The check compares the work with its base, so it needs the history of
+228
View File
@@ -0,0 +1,228 @@
"""Checks for places.toml and the place fields on each record.
places.toml [[place]] slug, kind, name, where, within, source, source_id,
source_version, box (docs/schema.md, "places.toml")
trail.toml [[place]] kind, slug, basis, km or source; places_checked, places_track
Each function appends one message per problem to `errors`. Used by tools/validate.py.
Python 3 standard library only.
"""
import datetime
import hashlib
import os
import re
import tomllib
KINDS = ("park", "range", "wilderness")
SOURCES = ("nps", "wilderness-connect", "cpcad", "gmba-v2")
REGISTRY_KEYS = {"slug", "kind", "name", "where", "within", "source", "source_id",
"source_version", "box"}
REGISTRY_REQUIRED = ("slug", "kind", "name", "where", "source", "source_id",
"source_version", "box")
PLACE_KEYS = {"kind", "slug", "basis", "km", "source"}
ID_RE = re.compile(r"[a-z0-9]+(-[a-z0-9]+)*")
DATE_RE = re.compile(r"\d{4}-\d{2}-\d{2}")
HASH_RE = re.compile(r"[0-9a-f]{16}")
# Ship 1 validates shape only. Ship 2 turns this on once every record is placed,
# so a new trail or a new track cannot ship unplaced.
REQUIRE_PLACES_CHECKED = False
def track_hash(path):
"""The first 16 hex digits of the SHA-256 of the file's bytes."""
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()[:16]
def _is_date(value):
if isinstance(value, datetime.date):
return True
if not isinstance(value, str) or not DATE_RE.fullmatch(value):
return False
try:
datetime.date.fromisoformat(value)
return True
except ValueError:
return False
def _text(table, field, where, errors):
value = table.get(field)
if not isinstance(value, str) or not value.strip():
errors.append(f"{where} {field} must be a non-empty string")
return ""
return value
def check_registry(entries, errors):
"""Check the shape of places.toml's entries: fields, kinds, slugs, boxes, within."""
seen = {}
by_key = {}
for i, e in enumerate(entries, 1):
where = f"places.toml: entry {i}"
if not isinstance(e, dict):
errors.append(f"{where} must be a table ([[place]])")
continue
where = f"places.toml: {e.get('kind', '?')}/{e.get('slug', f'entry {i}')}"
for name in sorted(set(e) - REGISTRY_KEYS):
errors.append(f"{where} has unknown field {name}")
for name in REGISTRY_REQUIRED:
if name not in e:
errors.append(f"{where} is missing required field {name}")
slug = _text(e, "slug", where, errors) if "slug" in e else ""
if slug and not ID_RE.fullmatch(slug):
errors.append(f"{where} slug must be lower-case words joined by hyphens")
kind = e.get("kind")
if "kind" in e and kind not in KINDS:
errors.append(f"{where} kind must be park, range or wilderness, not {kind!r}")
if "name" in e:
_text(e, "name", where, errors)
where_codes = e.get("where")
if "where" in e and (not isinstance(where_codes, list) or not where_codes
or not all(isinstance(c, str) and c for c in where_codes)):
errors.append(f"{where} where must be a non-empty list of state or province codes")
source = e.get("source")
if "source" in e and source not in SOURCES:
errors.append(f"{where} source must be one of {', '.join(SOURCES)}, not {source!r}")
sid = e.get("source_id")
if "source_id" in e:
ok = (isinstance(sid, str) and sid.strip()) or (
isinstance(sid, list) and sid and all(isinstance(s, str) and s.strip() for s in sid))
if not ok:
errors.append(f"{where} source_id must be a string or a non-empty list of strings")
if "source_version" in e:
_text(e, "source_version", where, errors)
box = e.get("box")
if "box" in e:
ok = (isinstance(box, list) and len(box) == 4
and all(isinstance(v, (int, float)) for v in box)
and -180.0 <= box[0] < box[2] <= 180.0 and -90.0 <= box[1] < box[3] <= 90.0)
if not ok:
errors.append(f"{where} box must be [west, south, east, north] inside the world, west before east and south before north")
within = e.get("within", [])
if not isinstance(within, list) or not all(isinstance(s, str) and s for s in within):
errors.append(f"{where} within must be a list of parent place slugs")
key = (kind, slug)
if slug and kind in KINDS:
if key in seen:
errors.append(f"{where} slug {slug!r} is used twice in kind {kind}")
seen[key] = e
by_key[key] = e
# within: parents exist, are ranges, and never circle
for (kind, slug), e in by_key.items():
where = f"places.toml: {kind}/{slug}"
for parent in e.get("within", []) or []:
if ("range", parent) not in by_key:
errors.append(f"{where} within names {parent!r}, which is not an existing range in places.toml")
def walk(slug, trail):
for parent in (by_key.get(("range", slug), {}).get("within") or []):
if parent in trail:
errors.append(f"places.toml: within circles back to {parent} ({' -> '.join(trail + [parent])})")
return
walk(parent, trail + [parent])
for (kind, slug) in by_key:
if kind == "range":
walk(slug, [slug])
def check_record(tid, rec, tdir, registry, errors):
"""Check one record's [[place]] tables, places_checked and places_track."""
places = rec.get("place", [])
if places is None:
places = []
if not isinstance(places, list) or not all(isinstance(p, dict) for p in places):
errors.append(f"{tid}: place must be an array of tables ([[place]])")
places = []
line_file = str((rec.get("source") or {}).get("line_file") or "")
has_track = bool(line_file)
seen = set()
for i, p in enumerate(places, 1):
where = f"{tid}: place {i}"
for name in sorted(set(p) - PLACE_KEYS):
errors.append(f"{where} has unknown field {name}")
kind, slug, basis = p.get("kind"), p.get("slug"), p.get("basis")
if kind not in KINDS:
errors.append(f"{where} kind must be park, range or wilderness, not {kind!r}")
if not isinstance(slug, str) or not slug:
errors.append(f"{where} slug must be a non-empty string")
elif kind in KINDS and (kind, slug) not in registry:
errors.append(f"{where} {kind}/{slug} is not in places.toml")
if (kind, slug) in seen:
errors.append(f"{where} lists {kind}/{slug} more than once; a place is listed once per record")
seen.add((kind, slug))
if basis not in ("track", "stated"):
errors.append(f"{where} basis must be track or stated, not {basis!r}")
continue
if basis == "track":
if not has_track:
errors.append(f"{where} basis is track but the record has no track")
km = p.get("km")
if not isinstance(km, (int, float)) or isinstance(km, bool) or km <= 0:
errors.append(f"{where} basis track needs km, the measured length inside")
if "source" in p:
errors.append(f"{where} basis track must not have a source; source is for stated")
else:
if has_track:
errors.append(f"{where} basis stated is only for a trail with no track; this record has one, so it must be re-measured")
if "km" in p:
errors.append(f"{where} basis stated must not have km; km is a measurement")
source = p.get("source")
if not isinstance(source, str) or not source.startswith(("https://", "http://")):
errors.append(f"{where} basis stated needs a source that is an http(s) address")
checked = rec.get("places_checked")
if checked is None:
if REQUIRE_PLACES_CHECKED:
errors.append(f"{tid}: places_checked is missing; run tools/place_trails.py (a trail in no park, range or wilderness still carries the date)")
elif not _is_date(checked):
errors.append(f"{tid}: places_checked must be a date (YYYY-MM-DD)")
stamp = rec.get("places_track")
if has_track:
if checked is not None or REQUIRE_PLACES_CHECKED:
if stamp is None:
errors.append(f"{tid}: places_track is missing; a record with a track records the track its places were measured from")
if stamp is not None:
if not isinstance(stamp, str) or not HASH_RE.fullmatch(stamp):
errors.append(f"{tid}: places_track must be 16 hex digits")
else:
path = os.path.join(tdir, line_file)
if os.path.isfile(path) and track_hash(path) != stamp:
errors.append(f"{tid}: the track has changed since its places were measured (places_track does not match {line_file}); run tools/place_trails.py")
elif stamp is not None:
errors.append(f"{tid}: places_track is present but the record has no track")
def check(root, trails, errors):
"""Load places.toml, check it and every record, then the cross-checks."""
path = os.path.join(root, "places.toml")
if not os.path.isfile(path):
errors.append("places.toml: missing")
return
try:
with open(path, "rb") as f:
entries = tomllib.load(f).get("place") or []
except Exception as e: # noqa: BLE001 - report and continue
errors.append(f"places.toml: does not parse: {e}")
return
if not isinstance(entries, list):
errors.append("places.toml: place must be an array of tables ([[place]])")
return
check_registry(entries, errors)
registry = {(e.get("kind"), e.get("slug")): e for e in entries if isinstance(e, dict)}
named = set()
for rec in trails:
tid = rec.get("id", "?")
check_record(tid, rec, os.path.join(root, tid), registry, errors)
for p in rec.get("place") or []:
if isinstance(p, dict):
named.add((p.get("kind"), p.get("slug")))
for e in entries:
if isinstance(e, dict):
for parent in e.get("within") or []:
named.add(("range", parent))
for (kind, slug) in sorted(registry, key=str):
if (kind, slug) not in named:
errors.append(f"places.toml: {kind}/{slug} is named by no record")
+185
View File
@@ -0,0 +1,185 @@
"""Tests for tools/check_places.py: the places.toml registry and the record's place fields.
Standard library only. Run from the repository root:
python3 -m unittest discover tools/tests -p "test_places.py"
"""
import os
import sys
import tempfile
import unittest
from unittest import mock
sys.dont_write_bytecode = True
TOOLS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT = os.path.dirname(TOOLS)
sys.path.insert(0, TOOLS)
import build_index # noqa: E402
import check_places as C # noqa: E402
def entry(**kw):
base = {"slug": "wind-river-range", "kind": "range", "name": "Wind River Range",
"where": ["WY"], "source": "gmba-v2", "source_id": "1",
"source_version": "2026-11-20", "box": [-110.0, 42.5, -108.5, 43.5]}
base.update(kw)
return base
def record(**kw):
base = {"id": "x", "source": {"line_file": ""}}
base.update(kw)
return base
REGISTRY = {("range", "wind-river-range"): entry()}
def registry_errors(entries):
errors = []
C.check_registry(entries, errors)
return errors
def record_errors(rec, tdir=None, registry=REGISTRY):
errors = []
C.check_record(rec.get("id", "x"), rec, tdir or "/no-such-dir", registry, errors)
return errors
class RegistryTest(unittest.TestCase):
def test_registry_entry_needs_every_field(self):
e = entry()
del e["box"]
self.assertTrue(any("box" in m for m in registry_errors([e])))
def test_kind_must_be_park_range_or_wilderness(self):
self.assertTrue(any("kind" in m for m in registry_errors([entry(kind="forest")])))
for kind in ("park", "range", "wilderness"):
self.assertEqual(registry_errors([entry(kind=kind)]), [], kind)
def test_same_slug_in_two_kinds_is_allowed_and_twice_in_one_kind_is_not(self):
a = entry(slug="glacier", kind="park")
b = entry(slug="glacier", kind="wilderness")
self.assertEqual(registry_errors([a, b]), [])
self.assertTrue(any("glacier" in m for m in registry_errors([a, dict(a)])))
def test_within_names_existing_ranges_and_has_no_cycle(self):
parent = entry(slug="rocky-mountains", name="Rocky Mountains")
child = entry(within=["rocky-mountains"])
self.assertEqual(registry_errors([parent, child]), [])
self.assertTrue(any("within" in m for m in registry_errors([entry(within=["no-such"])])))
park_parent = entry(slug="some-park", kind="park")
self.assertTrue(any("within" in m for m in registry_errors([park_parent, entry(within=["some-park"])])))
a = entry(slug="a", within=["b"])
b = entry(slug="b", within=["a"])
self.assertTrue(any("within" in m for m in registry_errors([a, b])))
def test_source_id_is_a_string_or_a_list_of_strings(self):
self.assertEqual(registry_errors([entry(source_id=["1", "2"])]), [])
self.assertTrue(any("source_id" in m for m in registry_errors([entry(source_id=7)])))
self.assertTrue(any("source_id" in m for m in registry_errors([entry(source_id=[])])))
def test_box_is_west_south_east_north_inside_the_world(self):
for bad in ([-108.5, 42.5, -110.0, 43.5], [-190.0, 42.5, -108.5, 43.5],
[-110.0, 42.5, -108.5, 95.0], [-110.0, 42.5, -108.5], "x"):
self.assertTrue(any("box" in m for m in registry_errors([entry(box=bad)])), bad)
class RecordTest(unittest.TestCase):
def test_record_place_must_be_in_the_registry(self):
rec = record(place=[{"kind": "range", "slug": "no-such", "basis": "stated",
"source": "https://example.org/x"}])
self.assertTrue(any("not in places.toml" in m for m in record_errors(rec)))
def test_track_basis_needs_km_and_forbids_source_and_stated_the_reverse(self):
with tempfile.TemporaryDirectory() as d:
with open(os.path.join(d, "line.geojson"), "w") as f:
f.write("{}")
h = C.track_hash(os.path.join(d, "line.geojson"))
base = record(source={"line_file": "line.geojson"}, places_checked="2026-11-20",
places_track=h)
ok = dict(base, place=[{"kind": "range", "slug": "wind-river-range",
"basis": "track", "km": 12.3}])
self.assertEqual(record_errors(ok, d), [])
no_km = dict(base, place=[{"kind": "range", "slug": "wind-river-range", "basis": "track"}])
self.assertTrue(any("km" in m for m in record_errors(no_km, d)))
with_src = dict(base, place=[{"kind": "range", "slug": "wind-river-range",
"basis": "track", "km": 1.0, "source": "https://x/"}])
self.assertTrue(any("source" in m for m in record_errors(with_src, d)))
stated_km = record(place=[{"kind": "range", "slug": "wind-river-range", "basis": "stated",
"km": 3.0, "source": "https://example.org/x"}])
self.assertTrue(any("km" in m for m in record_errors(stated_km)))
def test_stated_needs_a_source_url_and_a_trackless_record(self):
no_url = record(place=[{"kind": "range", "slug": "wind-river-range",
"basis": "stated", "source": "a book"}])
self.assertTrue(any("source" in m for m in record_errors(no_url)))
tracked = record(source={"line_file": "line.geojson"},
place=[{"kind": "range", "slug": "wind-river-range",
"basis": "stated", "source": "https://example.org/x"}])
self.assertTrue(any("stated" in m for m in record_errors(tracked)))
def test_a_place_is_listed_once_per_record(self):
one = {"kind": "range", "slug": "wind-river-range", "basis": "stated",
"source": "https://example.org/x"}
self.assertTrue(any("once" in m or "twice" in m for m in record_errors(record(place=[one, dict(one)]))))
def test_places_track_must_match_the_track_file(self):
with tempfile.TemporaryDirectory() as d:
with open(os.path.join(d, "line.geojson"), "w") as f:
f.write("{}")
rec = record(source={"line_file": "line.geojson"}, places_checked="2026-11-20",
places_track="0" * 16)
self.assertTrue(any("track has changed since" in m for m in record_errors(rec, d)))
def test_a_record_with_a_track_needs_places_track_and_one_without_must_not_have_it(self):
with tempfile.TemporaryDirectory() as d:
with open(os.path.join(d, "line.geojson"), "w") as f:
f.write("{}")
rec = record(source={"line_file": "line.geojson"}, places_checked="2026-11-20")
self.assertTrue(any("places_track" in m for m in record_errors(rec, d)))
no_track = record(places_checked="2026-11-20", places_track="a" * 16)
self.assertTrue(any("places_track" in m for m in record_errors(no_track)))
def test_places_checked_required_only_when_switched_on(self):
rec = record()
with mock.patch.object(C, "REQUIRE_PLACES_CHECKED", True):
self.assertTrue(any("places_checked" in m for m in record_errors(rec)))
with mock.patch.object(C, "REQUIRE_PLACES_CHECKED", False):
self.assertEqual(record_errors(rec), [])
bad = record(places_checked="yesterday")
self.assertTrue(any("places_checked" in m for m in record_errors(bad)))
def test_a_trackless_trail_given_a_track_later_is_refused(self):
rec = record(source={"line_file": "line.geojson"}, places_checked="2026-11-20",
place=[{"kind": "range", "slug": "wind-river-range",
"basis": "stated", "source": "https://example.org/x"}])
errors = record_errors(rec)
self.assertTrue(any("stated" in m for m in errors))
self.assertTrue(any("places_track" in m for m in errors))
class WholeRepoTest(unittest.TestCase):
def test_every_registry_entry_is_named_by_a_record(self):
with tempfile.TemporaryDirectory() as d:
with open(os.path.join(d, "places.toml"), "w") as f:
f.write('[[place]]\nslug = "wind-river-range"\nkind = "range"\n'
'name = "Wind River Range"\nwhere = ["WY"]\nsource = "gmba-v2"\n'
'source_id = "1"\nsource_version = "2026-11-20"\n'
'box = [-110.0, 42.5, -108.5, 43.5]\n')
errors = []
C.check(d, [record()], errors)
self.assertTrue(any("named by no record" in m for m in errors))
def test_the_real_repository_passes(self):
trails = []
for tid in build_index.trail_dirs(ROOT):
trails.append(build_index.load_toml(os.path.join(ROOT, tid, "trail.toml")))
errors = []
C.check(ROOT, trails, errors)
self.assertEqual(errors, [])
if __name__ == "__main__":
unittest.main()
+6
View File
@@ -63,6 +63,11 @@ spec = importlib.util.spec_from_file_location(
check_datafiles = importlib.util.module_from_spec(spec)
spec.loader.exec_module(check_datafiles)
spec = importlib.util.spec_from_file_location(
"check_places", os.path.join(ROOT, "tools", "check_places.py"))
check_places = importlib.util.module_from_spec(spec)
spec.loader.exec_module(check_places)
def haversine_km(coords):
total, R = 0.0, 6371.0088
@@ -933,6 +938,7 @@ def main():
check_left_out(ROOT, trails, errors)
check_datafiles.check_datafiles(ROOT, trails, errors)
check_places.check(ROOT, trails, errors)
trail_numbers.check(ROOT, trail_ids, errors)
for dirpath, dirnames, filenames in os.walk(ROOT):