Show each trail's own emblem, keep a history on every record, and list what was left out
Mirror to forge / mirror (push) Canceled after 0s
Validate / validate (push) Canceled after 0s
Validate / history (push) Canceled after 0s
Validate / site (push) Canceled after 0s
Validate / deploy (push) Canceled after 0s

- Emblems for 81 trails, up from 41. Each is the trail's own crest, badge
  or roundel alone, cropped out of a larger logo where need be and made
  transparent where that could be done cleanly. Records without one say
  where an emblem was looked for. The validator checks the logo state.
- Every record has a `[[history]]` list: what changed or was asked for,
  on what basis, who asked and whether it was applied or declined.
  `tools/check_history.py` fails a changed fact with no history entry and
  prints earlier entries about a changed field. It runs in CI before the
  site deploys. Each trail page shows the history.
- A new page, "Considered and left out", built from `left-out.toml`:
  35 trails and routes with the reason, the deciding fact and its source.
- The Hoosier Heritage Trail has its ends, its free map set and its
  emblem from its association (issue 2). Any trail may list its holder's
  own guide or map set.
- A stated permission is quoted in the download credit box.
- `tools/gpx_track.py` turns a GPX file from a holder or a hiker into a
  record's track files.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-16 13:40:03 -07:00
1 parent d34a9617cd
commit 24bfbb2fa8
374 files changed
+7796 -703

No files matched your search

+251
View File
@@ -0,0 +1,251 @@
#!/usr/bin/env python3
"""Check that a change to a trail's facts comes with a new [[history]] entry.
Python 3 standard library only, and git. Run it from anywhere inside the clone, before you
send a change:
python3 tools/check_history.py # against origin/main (or main)
python3 tools/check_history.py --base REV # against another revision
python3 tools/check_history.py --facts # print which fields count as facts
For every trail.toml (or track file) that differs from the base, it
* FAILS when a fact about the trail or its track changed and no new history entry names
that field with the outcome "applied" (it says which record and which fields);
* FAILS when an entry that was already in the base history was changed or removed
(history is only added to; use --allow-history-edits for a typing mistake);
* PRINTS, for every changed fact, the earlier history entries about the same field, and
prints "!!" lines when one of them was declined or was asked for by someone other than
the dataset's own check: that is where two requests may conflict.
The history is compared with the merge base of the revision and HEAD, so the work you are
sending is checked, and not what others have merged meanwhile. Your uncommitted edits count.
Exit status: 0 passes, 1 a check failed, 2 the base revision could not be read.
The fields that count as facts are listed in tools/trail_history.py (NOT_FACTS is the short
list of fields that do not) and in docs/schema.md, section "[[history]]".
"""
import sys
sys.dont_write_bytecode = True
import argparse
import os
import re
import subprocess
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import build_index # noqa: E402
import trail_history as H # noqa: E402
DEFAULT_BASES = ("origin/main", "github/main", "main")
TRACK_FILE_RE = re.compile(r"^([^/]+)/([^/]+\.geojson)$")
TOML_RE = re.compile(r"^([^/]+)/trail\.toml$")
class BaseError(Exception):
"""The base revision could not be used."""
def git(root, *args, check=True):
done = subprocess.run(["git", "-C", root, *args], capture_output=True, text=True)
if check and done.returncode != 0:
raise BaseError(f"git {' '.join(args)}: {done.stderr.strip() or 'failed'}")
return done
def repo_root():
here = os.path.dirname(HERE)
try:
return git(here, "rev-parse", "--show-toplevel").stdout.strip()
except (BaseError, FileNotFoundError):
return here
def merge_base(root, base):
"""The commit where this work left `base`. Says so plainly when a shallow clone hides it."""
candidates = [base] if base and not re.fullmatch(r"0+", base) else list(DEFAULT_BASES)
for rev in candidates:
if git(root, "rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}", check=False).returncode:
continue
done = git(root, "merge-base", rev, "HEAD", check=False)
if done.returncode == 0 and done.stdout.strip():
return rev, done.stdout.strip()
raise BaseError(
f"no common commit between {rev} and HEAD. In a shallow clone, fetch more: "
f"git fetch --unshallow (or fetch-depth: 0 in the workflow's checkout).")
raise BaseError(
f"cannot find {' or '.join(candidates)}. Fetch it (git fetch origin main) or pass --base REV.")
def changed_files(root, mb):
"""Trail directories whose record or track files differ from commit mb, in the working tree."""
names = set(git(root, "diff", "--name-only", "--no-renames", mb).stdout.split("\n"))
names |= set(git(root, "ls-files", "--others", "--exclude-standard").stdout.split("\n"))
records, tracks = set(), set()
for name in names:
m = TOML_RE.match(name)
if m:
records.add(m.group(1))
continue
m = TRACK_FILE_RE.match(name)
if m:
tracks.add(m.group(1))
return sorted(records | tracks), tracks
def load_text(text):
with tempfile.NamedTemporaryFile("w", suffix=".toml", delete=False, encoding="utf-8") as f:
f.write(text)
try:
return build_index.load_toml(f.name)
finally:
os.unlink(f.name)
def base_record(root, mb, tid):
done = git(root, "show", f"{mb}:{tid}/trail.toml", check=False)
return load_text(done.stdout) if done.returncode == 0 else None
def current_record(root, tid):
path = os.path.join(root, tid, "trail.toml")
return build_index.load_toml(path) if os.path.isfile(path) else None
def entry_text(e):
"""One earlier entry, in a sentence."""
fields = ", ".join(e.get("fields", []))
who = e.get("asked_by", "?")
url = f" ({e['basis_url']})" if e.get("basis_url") else ""
verb = "A request to change" if e.get("outcome") == "declined" else "Changed"
return (f"{verb} {fields} on {e.get('date', '?')} at the request of {who}, because "
f"{str(e.get('basis', '')).rstrip('.')}{url}; outcome {e.get('outcome', '?')}.")
def split_history(base_hist, new_hist):
"""(entries added, whether the earlier ones are untouched)."""
if new_hist[:len(base_hist)] == base_hist:
return new_hist[len(base_hist):], True
rest = list(new_hist)
for e in base_hist:
if e in rest:
rest.remove(e)
return rest, False
def analyse(tid, old, new, track_changed=False, allow_edits=False):
"""Return (failures, loud, notes) for one trail: lists of lines to print."""
failures, loud, notes = [], [], []
if new is None:
notes.append(f"{tid}: the record was removed; nothing to check.")
return failures, loud, notes
new_hist = [e for e in new.get("history", []) if isinstance(e, dict)]
old_hist = [e for e in (old or {}).get("history", []) if isinstance(e, dict)]
added, intact = split_history(old_hist, new_hist)
if not intact and not allow_edits:
failures.append(f"{tid}: earlier history entries were changed or removed. History is only "
"added to. Put the change back, and add a new entry that corrects it "
"(or pass --allow-history-edits for a typing mistake).")
if old is None:
if not any(e.get("fields") == [H.RECORD] for e in added):
failures.append(f"{tid}: a new record needs a history entry with fields = [\"record\"].")
notes.append(f"{tid}: new record, with {len(added)} history entr{'y' if len(added) == 1 else 'ies'}.")
return failures, loud, notes
paths = H.changed_paths(old, new)
if track_changed and H.TRACK_FIELD not in paths:
paths = sorted(paths + [H.TRACK_FIELD])
facts = [p for p in paths if H.is_fact(p)]
others = [p for p in paths if not H.is_fact(p)]
if others:
notes.append(f"{tid}: not facts, so no history entry needed: {', '.join(others)}")
applied = [e for e in added if e.get("outcome") == "applied"]
uncovered = [p for p in facts if not any(H.entry_covers(e, p) for e in applied)]
if uncovered:
if not added:
failures.append(f"{tid}: facts changed and no new history entry was added. "
f"Changed: {', '.join(uncovered)}.")
else:
failures.append(f"{tid}: no new history entry with outcome \"applied\" names "
f"{', '.join(uncovered)}, which changed.")
failures.append(f" Add one to [[history]] in {tid}/trail.toml (docs/schema.md, section "
"[[history]]). `python3 tools/check_history.py --facts` lists the facts.")
for e in applied:
idle = [f for f in e.get("fields", []) if f != H.RECORD
and not any(H.covers(f, p) or H.covers(p, f) for p in paths)]
if idle:
notes.append(f"{tid}: the entry of {e.get('date')} says {', '.join(idle)} changed, "
"but it did not change here.")
for p in facts:
earlier = [e for e in old_hist if e.get("fields") != [H.RECORD] and H.entry_covers(e, p)]
for e in earlier:
quiet = e.get("outcome") == "applied" and H.is_own(e)
line = f"{p} of {tid}: " + entry_text(e)
if e is earlier[-1] and e.get("outcome") == "applied":
line = (f"{p} of {tid} was last changed on {e.get('date')} at the request of "
f"{e.get('asked_by')}, because {str(e.get('basis', '')).rstrip('.')}"
f"{' (' + e['basis_url'] + ')' if e.get('basis_url') else ''}; "
f"outcome {e.get('outcome')}.")
if quiet:
notes.append(line)
elif e.get("outcome") == "declined":
loud.append(f"{line} It was DECLINED. Read the reason before asking again.")
else:
loud.append(f"{line} It was NOT the dataset's own check who asked: this field "
"may be disputed.")
return failures, loud, notes
def run(root, base=None, allow_edits=False, out=print):
"""Check the work in `root` against `base`. Return the exit status."""
rev, mb = merge_base(root, base)
ids, tracks = changed_files(root, mb)
out(f"Checking the history of records changed since {rev} ({mb[:9]}).")
failed, count = False, 0
for tid in ids:
old, new = base_record(root, mb, tid), current_record(root, tid)
if old is None and new is None:
continue
count += 1
failures, loud, notes = analyse(tid, old, new, tid in tracks, allow_edits)
for line in notes:
out(f"note {line}")
for line in loud:
out(f"!! CONFLICT RISK: {line}")
if os.environ.get("GITHUB_ACTIONS"):
out(f"::warning file={tid}/trail.toml::{line}")
for line in failures:
out(f"FAIL {line}" if not line.startswith(" ") else line)
if os.environ.get("GITHUB_ACTIONS") and not line.startswith(" "):
out(f"::error file={tid}/trail.toml::{line}")
failed = failed or bool(failures)
if failed:
out("History check FAILED.")
return 1
out(f"OK history: {count} changed record{'s' if count != 1 else ''} checked.")
return 0
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("--base", help="revision to compare with (default origin/main, then main)")
parser.add_argument("--facts", action="store_true", help="print which fields count as facts and exit")
parser.add_argument("--allow-history-edits", action="store_true",
help="do not fail when an earlier history entry was changed")
args = parser.parse_args(argv)
if args.facts:
print("Facts (a change needs a new history entry):\n " + H.FACTS_TEXT)
print("Not facts (no entry needed):\n " + H.NOT_FACTS_TEXT)
return 0
try:
return run(repo_root(), args.base, args.allow_history_edits)
except BaseError as e:
print(f"ERROR {e}")
return 2
if __name__ == "__main__":
sys.exit(main())
+216
View File
@@ -0,0 +1,216 @@
#!/usr/bin/env python3
"""Turn a holder's GPX file into a trail's track files.
Reads a GPX file (1.0 or 1.1) and writes, in the trail's directory:
line.geojson one LineString per track segment, in file order
release.txt source, licence, attribution and date read
Only geometry is kept: longitude and latitude of each track point, rounded to
6 decimal places. Elevations, timestamps, point and track names, descriptions,
comments, links, extensions, device and author metadata are read past and
never written. Waypoints and routes are counted and reported, not written.
Python standard library only. Run from anywhere:
python3 tools/gpx_track.py FILE.gpx --id TRAIL_ID --source TEXT --licence TEXT --attribution TEXT
python3 tools/gpx_track.py FILE.gpx --id TRAIL_ID --dry print figures only
python3 tools/gpx_track.py FILE.gpx --id TRAIL_ID --out DIR write to DIR/TRAIL_ID
python3 tools/gpx_track.py FILE.gpx --id TRAIL_ID --force replace existing files
python3 tools/gpx_track.py FILE.gpx --id TRAIL_ID --route-name NAME
set the feature's route_name
Segments are joined in order: tracks in file order, segments within a track in
order, each segment one LineString (the files hoosier-heritage-trail and
black-canyon use). Nothing is reordered or reversed. The run prints tracks,
segments, points, waypoints, the measured length (the validator's own rule),
the parts left after joining ends within 100 m (the rule tools/elevation.py
uses), and every gap between consecutive segments larger than --gap-km
(default 1 km) with its size and where it lies. A file that is not GPX (an
HTML page saved with a .gpx ending, say) is refused. XML with a DOCTYPE is
refused, so no entity can be expanded.
--source, --licence and --attribution are the lines of release.txt. The output
depends only on the file and the options (release.txt carries the date read).
"""
import argparse
import datetime
import importlib.util
import json
import os
import sys
import xml.etree.ElementTree as ET
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
GAP_KM_DEFAULT = 1.0
class TrackError(Exception):
"""A reason to stop, shown to the user without a traceback."""
def _load(name, path):
spec = importlib.util.spec_from_file_location(name, os.path.join(ROOT, "tools", path))
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
haversine_km = _load("validate_for_gpx_track", "validate.py").haversine_km
join_parts = _load("osm_track_for_gpx_track", "osm_track.py").join_parts
JOIN_GAP_M = 100.0
def _local(tag):
return tag.rsplit("}", 1)[-1] if isinstance(tag, str) else ""
def parse(data):
"""GPX bytes -> dict: tracks (list of lists of segments of [lon, lat]),
waypoints, routes. Raises TrackError if it is not a GPX file."""
if isinstance(data, str):
data = data.encode("utf-8")
head = data[:4096].lstrip().lower()
if b"<!doctype" in head[:4096] and b"<!doctype html" in head:
raise TrackError("the file is an HTML page, not GPX")
if b"<!doctype" in data[:65536].lower() or b"<!entity" in data[:65536].lower():
raise TrackError("the file has a DOCTYPE or entity declaration; refused")
try:
root = ET.fromstring(data)
except ET.ParseError as e:
raise TrackError(f"the file is not well-formed XML ({e})") from e
if _local(root.tag) != "gpx":
raise TrackError(f"the root element is {_local(root.tag)!r}, not gpx")
tracks, waypoints, routes = [], 0, 0
for el in root:
kind = _local(el.tag)
if kind == "wpt":
waypoints += 1
elif kind == "rte":
routes += 1
elif kind == "trk":
segs = []
for seg in el:
if _local(seg.tag) != "trkseg":
continue
pts = []
for p in seg:
if _local(p.tag) != "trkpt":
continue
try:
lat, lon = float(p.get("lat")), float(p.get("lon"))
except (TypeError, ValueError) as e:
raise TrackError("a track point has no valid lat/lon") from e
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
raise TrackError(f"a track point is out of range ({lat}, {lon})")
pt = [round(lon, 6), round(lat, 6)]
if not pts or pts[-1] != pt: # drop repeats of the same point
pts.append(pt)
if len(pts) >= 2:
segs.append(pts)
tracks.append(segs)
segments = [s for t in tracks for s in t]
if not segments:
raise TrackError("the file has no track segment with two or more points")
return {"tracks": tracks, "segments": segments, "waypoints": waypoints,
"routes": routes}
def figures(parsed, gap_km=GAP_KM_DEFAULT):
segs = parsed["segments"]
gaps = []
for i in range(len(segs) - 1):
a, b = segs[i][-1], segs[i + 1][0]
d = haversine_km([a, b])
if d > gap_km:
gaps.append({"after_segment": i + 1, "km": d, "from": a, "to": b})
return {"tracks": len(parsed["tracks"]), "segments": len(segs),
"points": sum(len(s) for s in segs), "waypoints": parsed["waypoints"],
"routes": parsed["routes"],
"measured_km": sum(haversine_km(s) for s in segs),
"parts": len(join_parts(segs)), "gaps": gaps}
def geojson_text(segments, route_name=None):
props = {"route_name": route_name} if route_name else {}
feats = [json.dumps({"type": "Feature", "properties": props,
"geometry": {"type": "LineString", "coordinates": s}},
separators=(",", ":"), ensure_ascii=False) for s in segments]
return '{"type":"FeatureCollection","features":[' + ",".join(feats) + "]}\n"
def release_text(source, licence, attribution, date, fig):
return (f"Source: {source}\n"
f"Licence: {licence}\n"
f"Attribution: {attribution}\n"
f"Source read: {date}\n"
f"Published copy: the {fig['segments']} track segment"
f"{'s' if fig['segments'] != 1 else ''} of the GPX file ({fig['points']:,} points) "
"as LineStrings in file order; geometry only (longitude and latitude, no "
"elevation, time, name or other metadata); coordinates rounded to 6 decimal "
"places and written as compact JSON.\n")
def run(args, today=None, out=print):
tdir = os.path.join(os.path.abspath(args.out), args.id)
if not os.path.isdir(tdir):
raise TrackError(f"{tdir} does not exist: create the trail directory and "
"trail.toml first")
names = ("line.geojson", "release.txt")
if not args.dry and not args.force:
have = [n for n in names if os.path.exists(os.path.join(tdir, n))]
if have:
raise TrackError(f"{', '.join(have)} already in {tdir}: use --force to replace")
if not args.dry and not (args.source and args.licence and args.attribution):
raise TrackError("--source, --licence and --attribution are needed to write release.txt")
with open(args.gpx, "rb") as f:
parsed = parse(f.read())
fig = figures(parsed, args.gap_km)
out(f"tracks: {fig['tracks']}")
out(f"segments: {fig['segments']}")
out(f"points: {fig['points']}")
out(f"waypoints: {fig['waypoints']} (not written)")
out(f"routes: {fig['routes']} (not written)")
out(f"measured_km: {fig['measured_km']:.1f}")
out(f"parts (ends within {JOIN_GAP_M:.0f} m): {fig['parts']}")
for g in fig["gaps"]:
out(f"gap after segment {g['after_segment']}: {g['km']:.1f} km "
f"from ({g['from'][1]}, {g['from'][0]}) to ({g['to'][1]}, {g['to'][0]})")
if args.dry:
out("dry run: nothing written")
return fig
date = (today or datetime.date.today()).isoformat()
files = {"line.geojson": geojson_text(parsed["segments"], args.route_name),
"release.txt": release_text(args.source, args.licence, args.attribution,
date, fig)}
for name, text in files.items():
with open(os.path.join(tdir, name), "w", encoding="utf-8", newline="\n") as f:
f.write(text)
out("wrote " + ", ".join(files) + f" in {tdir}")
return fig
def main(argv=None):
ap = argparse.ArgumentParser(description="Turn a GPX file into a trail's track files.")
ap.add_argument("gpx", help="the GPX file")
ap.add_argument("--id", required=True, help="trail id (the directory name)")
ap.add_argument("--out", default=ROOT, help="directory holding the trail directories "
"(default: the repository root)")
ap.add_argument("--source", help="release.txt Source line")
ap.add_argument("--licence", help="release.txt Licence line")
ap.add_argument("--attribution", help="release.txt Attribution line")
ap.add_argument("--route-name", help="route_name property of the features")
ap.add_argument("--gap-km", type=float, default=GAP_KM_DEFAULT,
help="report gaps between segments larger than this (default 1)")
ap.add_argument("--dry", action="store_true", help="print the figures, write nothing")
ap.add_argument("--force", action="store_true", help="replace existing files")
args = ap.parse_args(argv)
try:
run(args)
except (TrackError, OSError) as e:
print(f"error: {e}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+145
View File
@@ -0,0 +1,145 @@
"""Tests for tools/gpx_track.py: no network.
Run from the repository root:
python3 -m unittest discover tools/tests
"""
import argparse
import json
import os
import sys
import tempfile
import unittest
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import gpx_track as G # noqa: E402
GPX = """<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Some Device 9000" xmlns="http://www.topografix.com/GPX/1/1">
<metadata><name>Jane Doe's hikes</name><author><name>Jane Doe</name></author></metadata>
<wpt lat="40.5" lon="-100.5"><name>Camp</name></wpt>
<trk><name>Day 1 by Jane</name><desc>private note</desc>
<trkseg>
<trkpt lat="40.0" lon="-100.0"><ele>12.5</ele><time>2020-01-01T10:00:00Z</time></trkpt>
<trkpt lat="40.0" lon="-100.0"><ele>12.5</ele><time>2020-01-01T10:00:05Z</time></trkpt>
<trkpt lat="40.001" lon="-100.0"><ele>13</ele><time>2020-01-01T10:01:00Z</time></trkpt>
<trkpt lat="40.002" lon="-100.0000004"><ele>14</ele></trkpt>
</trkseg>
<trkseg>
<trkpt lat="40.002" lon="-100.0"/>
<trkpt lat="40.003" lon="-100.0"/>
</trkseg>
</trk>
<trk><trkseg>
<trkpt lat="41.0" lon="-100.0"/>
<trkpt lat="41.001" lon="-100.0"/>
</trkseg></trk>
</gpx>"""
def args_for(tmp, gpx, **kw):
d = dict(gpx=gpx, id="t", out=tmp, source="S", licence="L", attribution="A",
route_name=None, gap_km=1.0, dry=False, force=False)
d.update(kw)
return argparse.Namespace(**d)
class ParseTests(unittest.TestCase):
def test_counts_and_order(self):
p = G.parse(GPX)
self.assertEqual(len(p["tracks"]), 2)
self.assertEqual([len(s) for s in p["segments"]], [3, 2, 2]) # repeat dropped
self.assertEqual(p["waypoints"], 1)
self.assertEqual(p["segments"][0][0], [-100.0, 40.0])
self.assertEqual(p["segments"][2][0], [-100.0, 41.0])
def test_rounding(self):
self.assertEqual(G.parse(GPX)["segments"][0][-1], [-100.0, 40.002])
def test_html_refused(self):
with self.assertRaises(G.TrackError):
G.parse("<!DOCTYPE html>\n<html><body>lost</body></html>")
def test_doctype_refused(self):
with self.assertRaises(G.TrackError):
G.parse('<?xml version="1.0"?><!DOCTYPE gpx [<!ENTITY a "b">]><gpx/>')
def test_not_gpx_and_empty_refused(self):
with self.assertRaises(G.TrackError):
G.parse("<kml/>")
with self.assertRaises(G.TrackError):
G.parse('<gpx><trk><trkseg><trkpt lat="1" lon="1"/></trkseg></trk></gpx>')
with self.assertRaises(G.TrackError):
G.parse("not xml")
def test_bad_point_refused(self):
with self.assertRaises(G.TrackError):
G.parse('<gpx><trk><trkseg><trkpt lat="95" lon="1"/><trkpt lat="1" lon="1"/>'
"</trkseg></trk></gpx>")
def test_gpx_10_namespace(self):
p = G.parse('<gpx xmlns="http://www.topografix.com/GPX/1/0"><trk><trkseg>'
'<trkpt lat="1" lon="1"/><trkpt lat="1.001" lon="1"/></trkseg></trk></gpx>')
self.assertEqual(len(p["segments"]), 1)
class FigureTests(unittest.TestCase):
def test_gap_and_parts(self):
f = G.figures(G.parse(GPX))
self.assertEqual((f["tracks"], f["segments"], f["points"]), (2, 3, 7))
self.assertEqual(f["parts"], 2) # first two join, third is ~111 km away
self.assertEqual(len(f["gaps"]), 1)
self.assertEqual(f["gaps"][0]["after_segment"], 2)
self.assertAlmostEqual(f["gaps"][0]["km"], 110.6, delta=1)
self.assertAlmostEqual(f["measured_km"], 0.4448, delta=0.01)
class RunTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
os.mkdir(os.path.join(self.tmp, "t"))
self.gpx = os.path.join(self.tmp, "in.gpx")
with open(self.gpx, "w") as f:
f.write(GPX)
self.log = []
def test_writes_geometry_only(self):
G.run(args_for(self.tmp, self.gpx, route_name="The Trail"),
today=__import__("datetime").date(2026, 11, 16), out=self.log.append)
text = open(os.path.join(self.tmp, "t", "line.geojson")).read()
doc = json.loads(text)
self.assertEqual(len(doc["features"]), 3)
self.assertEqual(doc["features"][0]["properties"], {"route_name": "The Trail"})
for leak in ("Jane", "Device", "2020", "Camp", "private", "12.5", "ele", "time"):
self.assertNotIn(leak, text)
rel = open(os.path.join(self.tmp, "t", "release.txt")).read()
self.assertIn("Source read: 2026-11-16", rel)
self.assertNotIn("Jane", rel)
self.assertTrue(any(l.startswith("gap after segment 2") for l in self.log))
def test_dry_writes_nothing(self):
G.run(args_for(self.tmp, self.gpx, dry=True), out=self.log.append)
self.assertEqual(os.listdir(os.path.join(self.tmp, "t")), [])
def test_force_and_missing_dir(self):
G.run(args_for(self.tmp, self.gpx), out=self.log.append)
with self.assertRaises(G.TrackError):
G.run(args_for(self.tmp, self.gpx), out=self.log.append)
G.run(args_for(self.tmp, self.gpx, force=True), out=self.log.append)
with self.assertRaises(G.TrackError):
G.run(args_for(self.tmp, self.gpx, id="nope"), out=self.log.append)
def test_needs_release_fields(self):
with self.assertRaises(G.TrackError):
G.run(args_for(self.tmp, self.gpx, licence=None), out=self.log.append)
def test_main_reports_html_cleanly(self):
bad = os.path.join(self.tmp, "bad.gpx")
with open(bad, "w") as f:
f.write("<!DOCTYPE html><html></html>")
self.assertEqual(G.main([bad, "--id", "t", "--out", self.tmp, "--dry"]), 1)
if __name__ == "__main__":
unittest.main()
+43
View File
@@ -0,0 +1,43 @@
"""[[guide]] on a trail that is not a route: its holder's own guide or map set."""
import os
import sys
import unittest
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import validate as V # noqa: E402
GOOD = {"title": "Guide and Map Set", "author": "An Association", "access": "free",
"url": "https://example.org/mapset.pdf", "format": "PDF"}
def check(guides):
errors = []
V.check_guides("t", guides, errors)
return errors
class GuideTest(unittest.TestCase):
def test_no_guide_is_fine(self):
self.assertEqual(check(None), [])
def test_a_complete_guide_passes(self):
self.assertEqual(check([dict(GOOD)]), [])
def test_each_required_field(self):
for field in ("title", "author", "access", "url"):
errors = check([{k: v for k, v in GOOD.items() if k != field}])
self.assertTrue(errors, field)
def test_access_and_url_are_checked(self):
self.assertTrue(check([dict(GOOD, access="gift")]))
self.assertTrue(check([dict(GOOD, url="ftp://example.org/x")]))
def test_price_needs_its_date(self):
self.assertTrue(check([dict(GOOD, price="$5")]))
self.assertEqual(check([dict(GOOD, price="$5", price_checked="2026-11-16")]), [])
if __name__ == "__main__":
unittest.main()
+378
View File
@@ -0,0 +1,378 @@
"""Tests for [[history]]: the validator's checks and tools/check_history.py.
No network. The check runs against small git repositories made in a temporary directory.
Run from the repository root:
python3 -m unittest discover tools/tests
"""
import contextlib
import io
import os
import subprocess
import sys
import tempfile
import unittest
sys.dont_write_bytecode = True
TOOLS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, TOOLS)
import build_index # noqa: E402
import check_history as C # noqa: E402
import trail_history as H # noqa: E402
OWN = H.OWN_CHECK
def entry(date="2026-11-10", change="Changed it.", fields=("length_km",), basis="A page said so.",
url="https://example.org/page", who=OWN, outcome="applied"):
lines = ["[[history]]", f'date = "{date}"', f'change = "{change}"',
"fields = [" + ", ".join(f'"{f}"' for f in fields) + "]", f'basis = "{basis}"']
if url:
lines.append(f'basis_url = "{url}"')
lines += [f'asked_by = "{who}"', f'outcome = "{outcome}"']
return "\n".join(lines) + "\n"
ADDED = entry("2026-11-01", "The record was added.", ("record",), "The record's own source entry.", None)
def record(length=100, summary="A trail.", measured=99.0, extra="", history=ADDED, line_file=""):
return f'''id = "t"
name = "Test Trail"
length_km = {length}
[source]
line_file = "{line_file}"
[verification]
measured_km = {measured}
[hike]
summary = "{summary}"
caution = "Water is scarce."
{extra}
{history}'''
class Repo:
"""A scratch git repository with one trail, `t`, committed as the base."""
def __init__(self, test, text):
self.dir = tempfile.TemporaryDirectory()
test.addCleanup(self.dir.cleanup)
self.root = self.dir.name
self.git("init", "-q")
os.makedirs(os.path.join(self.root, "t"))
self.write(text)
self.git("add", "-A")
self.commit("base")
self.base = self.git("rev-parse", "HEAD").strip()
def git(self, *args):
done = subprocess.run(["git", "-C", self.root, "-c", "user.name=t", "-c", "user.email=t@example.invalid",
*args], capture_output=True, text=True, check=True)
return done.stdout
def commit(self, message):
self.git("commit", "-q", "-m", message)
def write(self, text, name="trail.toml", tid="t"):
os.makedirs(os.path.join(self.root, tid), exist_ok=True)
with open(os.path.join(self.root, tid, name), "w", encoding="utf-8") as f:
f.write(text)
def run(self, **kwargs):
lines = []
status = C.run(self.root, self.base, out=lines.append, **kwargs)
return status, "\n".join(lines)
class ClassifyTest(unittest.TestCase):
def test_facts_and_not_facts(self):
for path in ("name", "length_km", "length_note", "kind", "source.licence", "source.line_file",
"source.publisher_url", "route.creator", "route.line_policy", "hike.start", "hike.caution",
"hike.official_url", "shield.logo_file", "shield.logo_owner", "short_name_url", "guide.url",
"osm.relation", "a_field_added_later"):
self.assertTrue(H.is_fact(path), path)
for path in ("history", "history.outcome", "verification.measured_km", "verification.date",
"source.source_checked", "hike.summary", "hike.checked", "hike.source.url", "guide.price",
"link.url", "shield.note", "osm.note", "wave"):
self.assertFalse(H.is_fact(path), path)
def test_every_schema_field_is_classified_somewhere(self):
self.assertIn("source.licence", H.SCHEMA_FIELDS)
self.assertNotIn("history", H.SCHEMA_FIELDS)
self.assertNotIn("record", H.SCHEMA_FIELDS)
def test_changed_paths_handles_tables_and_lists(self):
old = {"name": "A", "regions": ["VT"], "guide": [{"title": "x", "url": "u"}], "history": [{"date": "1"}]}
new = {"name": "A", "regions": ["VT", "NH"], "guide": [{"title": "x", "url": "u"}, {"title": "y", "url": "v"}],
"history": [{"date": "1"}, {"date": "2"}], "route": {"creator": "C"}}
self.assertEqual(H.changed_paths(old, new), ["guide.title", "guide.url", "regions", "route.creator"])
def test_an_entry_covers_its_field_and_what_is_under_a_table(self):
e = {"fields": ["source"]}
self.assertTrue(H.entry_covers(e, "source.licence"))
self.assertFalse(H.entry_covers({"fields": ["source.licence"]}, "source.licence_text"))
self.assertFalse(H.entry_covers({"fields": ["record"]}, "name"))
class EntryShapeTest(unittest.TestCase):
def check(self, history, **kw):
errors = []
rec = {"history": history} if history is not None else {}
H.check_entries("t", rec, errors)
return errors
def good(self, **kw):
e = {"date": "2026-11-01", "change": "Added.", "fields": ["record"], "basis": "Source.",
"asked_by": OWN, "outcome": "applied"}
e.update(kw)
return e
def second(self, **kw):
e = {"date": "2026-11-02", "change": "Changed.", "fields": ["length_km"], "basis": "A page.",
"basis_url": "https://example.org/", "asked_by": "a hiker", "outcome": "declined"}
e.update(kw)
return e
def test_good(self):
self.assertEqual(self.check([self.good(), self.second()]), [])
def test_the_added_entry_may_leave_out_the_address(self):
self.assertEqual(self.check([self.good()]), [])
second = self.second()
del second["basis_url"]
self.assertTrue(any("missing basis_url" in e for e in self.check([self.good(), second])))
def test_no_history_is_an_error(self):
self.assertTrue(any("no [[history]]" in e for e in self.check(None)))
self.assertTrue(any("no [[history]]" in e for e in self.check([])))
def test_missing_and_unknown_fields(self):
e = self.good()
del e["asked_by"]
e["extra"] = 1
errors = self.check([e])
self.assertTrue(any("missing asked_by" in x for x in errors))
self.assertTrue(any("unknown field extra" in x for x in errors))
def test_outcome(self):
errors = self.check([self.good(), self.second(outcome="maybe")])
self.assertTrue(any("outcome must be one of applied, declined" in x for x in errors))
def test_dates(self):
self.assertTrue(any("YYYY-MM-DD" in x for x in self.check([self.good(date="11/01/2026")])))
self.assertTrue(any("not a real date" in x for x in self.check([self.good(date="2026-02-30")])))
errors = self.check([self.good(date="2026-11-05"), self.second(date="2026-11-02")])
self.assertTrue(any("earlier than the entry before" in x for x in errors))
self.assertEqual(self.check([self.good(date="2026-11-02"), self.second(date="2026-11-02")]), [])
def test_fields(self):
self.assertTrue(any("non-empty list" in x for x in self.check([self.good(fields=[])])))
errors = self.check([self.good(), self.second(fields=["lenght_km"])])
self.assertTrue(any("not a field of the record" in x for x in errors))
self.assertTrue(any("not a field of the record" in x for x in self.check([self.good(), self.second(fields=["history"])])))
self.assertEqual(self.check([self.good(), self.second(fields=["source", "hike.source", "guide.price"])]), [])
def test_record_entry_comes_first_and_alone(self):
self.assertTrue(any("first entry must be" in x for x in self.check([self.second()])))
self.assertTrue(any("only the first entry" in x for x in self.check([self.good(), self.good(date="2026-11-03")])))
self.assertTrue(any("cannot be listed with other" in x for x in self.check([self.good(fields=["record", "name"])])))
def test_basis_url_is_an_address(self):
self.assertTrue(any("http(s) address" in x for x in self.check([self.good(), self.second(basis_url="page")])))
def test_real_records_all_have_valid_history(self):
root = os.path.dirname(TOOLS)
errors = []
for tid in build_index.trail_dirs(root):
H.check_entries(tid, build_index.load_toml(os.path.join(root, tid, "trail.toml")), errors)
self.assertEqual(errors, [])
class CheckTest(unittest.TestCase):
def test_a_fact_changed_with_no_entry_fails_and_names_record_and_field(self):
repo = Repo(self, record())
repo.write(record(length=120))
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn("FAIL t: facts changed and no new history entry was added. Changed: length_km.", out)
def test_a_fact_changed_with_its_entry_passes(self):
repo = Repo(self, record())
repo.write(record(length=120, history=ADDED + "\n" + entry("2026-11-12", fields=("length_km",))))
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("OK history", out)
def test_an_entry_for_another_field_does_not_cover(self):
repo = Repo(self, record())
repo.write(record(length=120, history=ADDED + "\n" + entry("2026-11-12", fields=("name",))))
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn('no new history entry with outcome "applied" names length_km', out)
def test_a_declined_entry_does_not_cover_a_change(self):
repo = Repo(self, record())
repo.write(record(length=120, history=ADDED + "\n" + entry("2026-11-12", outcome="declined")))
self.assertEqual(repo.run()[0], 1)
def test_a_declined_entry_alone_is_fine(self):
repo = Repo(self, record())
repo.write(record(history=ADDED + "\n" + entry("2026-11-12", outcome="declined", who="a hiker")))
status, out = repo.run()
self.assertEqual(status, 0, out)
def test_not_facts_need_no_entry(self):
repo = Repo(self, record())
repo.write(record(summary="A different sentence.", measured=95.5))
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("not facts", out)
self.assertIn("hike.summary", out)
def test_a_hiker_fact_needs_an_entry(self):
repo = Repo(self, record())
repo.write(record().replace("Water is scarce.", "Water is scarce in August."))
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn("Changed: hike.caution", out)
def test_a_changed_track_file_counts_as_a_change_to_source_line_file(self):
repo = Repo(self, record(line_file="line.geojson"))
repo.write("{}", "line.geojson")
repo.git("add", "-A")
repo.commit("track")
repo.base = repo.git("rev-parse", "HEAD").strip()
repo.write('{"type":"FeatureCollection"}', "line.geojson")
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn("Changed: source.line_file", out)
repo.write(record(line_file="line.geojson", history=ADDED + "\n" + entry(
"2026-11-12", fields=("source.line_file",), change="A newer track.")))
self.assertEqual(repo.run()[0], 0)
def test_earlier_entry_for_the_same_field_is_printed(self):
past = ADDED + "\n" + entry("2026-11-05", change="Changed the length.", basis="The holder's page says 100 km.",
url="https://holder.example/trail")
repo = Repo(self, record(history=past))
repo.write(record(length=120, history=past + "\n" + entry("2026-11-12")))
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("length_km of t was last changed on 2026-11-05 at the request of the dataset's own check, "
"because The holder's page says 100 km (https://holder.example/trail); outcome applied.", out)
self.assertNotIn("!!", out)
def test_an_earlier_request_by_someone_else_is_printed_loudly(self):
past = ADDED + "\n" + entry("2026-11-05", who="the trail association's president")
repo = Repo(self, record(history=past))
repo.write(record(length=120, history=past + "\n" + entry("2026-11-12")))
status, out = repo.run()
self.assertEqual(status, 0, out)
loud = [line for line in out.split("\n") if line.startswith("!!")]
self.assertEqual(len(loud), 1, out)
self.assertIn("the trail association's president", loud[0])
self.assertIn("NOT the dataset's own check", loud[0])
def test_an_earlier_declined_request_is_printed_loudly(self):
past = ADDED + "\n" + entry("2026-11-05", who="a hiker", outcome="declined",
basis="The holder's page says 100 km.")
repo = Repo(self, record(history=past))
repo.write(record(length=120, history=past + "\n" + entry("2026-11-12")))
status, out = repo.run()
self.assertEqual(status, 0, out)
loud = [line for line in out.split("\n") if line.startswith("!!")]
self.assertEqual(len(loud), 1, out)
self.assertIn("DECLINED", loud[0])
self.assertIn("A request to change length_km on 2026-11-05 at the request of a hiker", loud[0])
def test_earlier_entries_about_other_fields_are_not_printed(self):
past = ADDED + "\n" + entry("2026-11-05", fields=("name",), who="a hiker", outcome="declined")
repo = Repo(self, record(history=past))
repo.write(record(length=120, history=past + "\n" + entry("2026-11-12")))
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertNotIn("!!", out)
self.assertNotIn("a hiker", out)
def test_github_annotations(self):
past = ADDED + "\n" + entry("2026-11-05", who="a hiker", outcome="declined")
repo = Repo(self, record(history=past))
repo.write(record(length=120))
os.environ["GITHUB_ACTIONS"] = "true"
self.addCleanup(os.environ.pop, "GITHUB_ACTIONS", None)
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn("::error file=t/trail.toml::", out)
self.assertIn("::warning file=t/trail.toml::", out)
def test_earlier_entries_cannot_be_rewritten(self):
past = ADDED + "\n" + entry("2026-11-05")
repo = Repo(self, record(history=past))
repo.write(record(history=ADDED + "\n" + entry("2026-11-05", basis="Another reason.")))
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn("earlier history entries were changed or removed", out)
self.assertEqual(repo.run(allow_edits=True)[0], 0)
def test_a_new_record_needs_its_added_entry(self):
repo = Repo(self, record())
repo.write(record(history=entry("2026-11-12")).replace('id = "t"', 'id = "u"'), tid="u")
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn('a new record needs a history entry with fields = ["record"]', out)
repo.write(record(history=ADDED).replace('id = "t"', 'id = "u"'), tid="u")
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("new record", out)
def test_an_entry_naming_a_field_that_did_not_change_is_noted(self):
repo = Repo(self, record())
repo.write(record(history=ADDED + "\n" + entry("2026-11-12", fields=("name",))))
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("says name changed, but it did not change here", out)
def test_only_changed_records_are_looked_at(self):
repo = Repo(self, record())
repo.write(record(length=999, history=""), tid="u") # untracked, a new record without history
repo.git("add", "-A")
repo.commit("u")
repo.base = repo.git("rev-parse", "HEAD").strip()
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("0 changed records", out)
def test_work_is_compared_with_the_merge_base(self):
repo = Repo(self, record())
repo.git("checkout", "-q", "-b", "other")
repo.write(record(length=120, history=ADDED + "\n" + entry("2026-11-12")))
repo.git("add", "-A")
repo.commit("someone else's change")
repo.git("checkout", "-q", "-")
repo.base = "other" # the work here leaves the record as it was
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("0 changed records", out)
def test_a_base_that_cannot_be_read_says_so(self):
repo = Repo(self, record())
repo.base = "no-such-revision"
with self.assertRaises(C.BaseError):
repo.run()
with contextlib.redirect_stdout(io.StringIO()) as printed:
self.assertEqual(C.main(["--facts"]), 0)
self.assertIn("length_km", printed.getvalue())
def test_an_all_zero_base_falls_back_to_the_default(self):
repo = Repo(self, record())
repo.git("branch", "-m", "main")
repo.base = "0" * 40
status, out = repo.run()
self.assertEqual(status, 0, out)
if __name__ == "__main__":
unittest.main()
+130
View File
@@ -0,0 +1,130 @@
"""Tests for the left-out.toml checks in tools/validate.py: no network.
Run from the repository root:
python3 -m unittest discover tools/tests
"""
import os
import sys
import unittest
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import validate as V # noqa: E402
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
GOOD = {
"id": "example-trail",
"name": "Example Trail",
"country": "US",
"regions": ["PA"],
"length_mi": 42.0,
"length_km": 68,
"reason": "below-floor",
"note": "The holder gives it as 42 miles, below the 50 mile floor.",
"source_url": "https://example.org/example-trail",
"decided": "2026-11-14",
"was_listed": False,
}
WAITING = dict(
GOOD,
id="waiting-trail",
name="Waiting Trail",
reason="waiting",
waiting_for="The holder builds enough of it to walk through.",
)
TRAILS = [{"id": "long-trail", "name": "Long Trail (Vermont)"}]
def check(entries, trails=TRAILS):
errors = []
V.check_left_out_entries(entries, trails, errors)
return errors
class LeftOutTest(unittest.TestCase):
def test_good_entries_are_valid(self):
self.assertEqual(check([GOOD, WAITING]), [])
def test_every_required_field(self):
for field in ("id", "name", "country", "regions", "reason", "note",
"decided", "was_listed"):
entry = {k: v for k, v in GOOD.items() if k != field}
self.assertTrue(check([entry]), field)
self.assertTrue(check([dict(GOOD, **{field: ""})]), field)
self.assertTrue(check([dict(GOOD, **{field: " "})]), field)
def test_unknown_key(self):
self.assertTrue(any("unknown field rank" in e
for e in check([dict(GOOD, rank=1)])))
def test_unknown_reason(self):
errors = check([dict(GOOD, reason="too-short")])
self.assertTrue(any("reason" in e for e in errors))
def test_bad_country_and_region(self):
self.assertTrue(any("country" in e for e in check([dict(GOOD, country="MX")])))
self.assertTrue(any("region" in e for e in check([dict(GOOD, regions=["XX"])])))
self.assertTrue(any("regions" in e for e in check([dict(GOOD, regions="PA")])))
def test_bad_date(self):
for bad in ("2026-11-31", "November 2026", "2026/11/14"):
self.assertTrue(any("decided" in e
for e in check([dict(GOOD, decided=bad)])), bad)
def test_source_url_must_be_http(self):
self.assertTrue(any("http(s)" in e
for e in check([dict(GOOD, source_url="ftp://example.org/a")])))
def test_source_url_may_be_missing_only_when_the_note_says_why(self):
entry = {k: v for k, v in GOOD.items() if k != "source_url"}
self.assertTrue(check([entry]))
said = dict(entry, note="No page publishes it as one trail, so there is no source page to give.")
self.assertEqual(check([said]), [])
def test_waiting_needs_waiting_for_and_others_must_not_have_it(self):
entry = {k: v for k, v in WAITING.items() if k != "waiting_for"}
self.assertTrue(any("waiting_for" in e for e in check([entry])))
self.assertTrue(any("waiting_for" in e
for e in check([dict(GOOD, waiting_for="Something changes.")])))
def test_was_listed_must_be_a_boolean(self):
self.assertTrue(any("was_listed" in e
for e in check([dict(GOOD, was_listed="yes")])))
def test_lengths_must_agree_and_be_positive(self):
self.assertTrue(check([dict(GOOD, length_mi=42.0, length_km=420)]))
self.assertTrue(check([dict(GOOD, length_mi=-1)]))
no_length = {k: v for k, v in GOOD.items() if not k.startswith("length_")}
self.assertEqual(check([no_length]), [])
def test_entries_must_be_sorted_by_name(self):
errors = check([WAITING, GOOD])
self.assertTrue(any("sorted" in e for e in errors))
def test_no_duplicate_id_or_name(self):
self.assertTrue(any("duplicate" in e for e in check([GOOD, dict(GOOD)])))
def test_no_entry_matches_a_listed_trail(self):
by_id = dict(GOOD, id="long-trail")
self.assertTrue(any("listed" in e for e in check([by_id])))
by_name = dict(GOOD, name="Long Trail (Vermont)")
self.assertTrue(any("listed" in e for e in check([by_name])))
def test_the_real_file_passes(self):
errors = []
trails = []
import tomllib
for name in sorted(os.listdir(ROOT)):
path = os.path.join(ROOT, name, "trail.toml")
if os.path.isfile(path):
with open(path, "rb") as f:
rec = tomllib.load(f)
trails.append({"id": rec.get("id", name), "name": rec.get("name", "")})
V.check_left_out(ROOT, trails, errors)
self.assertEqual(errors, [])
if __name__ == "__main__":
unittest.main()
+79
View File
@@ -0,0 +1,79 @@
"""Tests for the [shield] checks in tools/validate.py: no network.
Run from the repository root:
python3 -m unittest discover tools/tests
"""
import os
import sys
import tempfile
import unittest
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import validate as V # noqa: E402
WITH_FILE = {"status": "use-real-logo", "logo_source": "https://example.org/logo.png", "contact": "Club",
"note": "The club's crest.", "logo_file": "shield.png", "logo_owner": "Club"}
NO_EMBLEM = {"status": "no-logo-exists", "logo_source": "", "contact": "", "note": "Looked at https://example.org/; no crest.",
"logo_file": "", "logo_owner": ""}
NOT_FOUND = dict(NO_EMBLEM, status="logo-not-found", note="A sign shows one; no artwork found at https://example.org/.")
def check(shield, files=()):
with tempfile.TemporaryDirectory() as d:
for f in files:
open(os.path.join(d, f), "wb").write(b"x")
errors = []
V.check_shield("t", shield, d, errors)
return errors
class ShieldStatusTest(unittest.TestCase):
def test_the_three_states_pass(self):
self.assertEqual(check(WITH_FILE, ["shield.png"]), [])
self.assertEqual(check(NO_EMBLEM), [])
self.assertEqual(check(NOT_FOUND), [])
def test_status_is_required(self):
errors = check({k: v for k, v in NO_EMBLEM.items() if k != "status"})
self.assertEqual(len(errors), 1)
self.assertIn("shield.status", errors[0])
def test_status_must_be_one_of_the_three(self):
for bad in ("no-logo", "logo not found", "use-logo", "none"):
errors = check(dict(NO_EMBLEM, status=bad))
self.assertTrue(any("not one of" in e for e in errors), bad)
def test_use_real_logo_needs_a_file(self):
errors = check(dict(WITH_FILE, logo_file=""))
self.assertTrue(any("use-real-logo" in e and "names no file" in e for e in errors), errors)
def test_use_real_logo_needs_the_file_on_disk(self):
errors = check(WITH_FILE)
self.assertTrue(any("does not exist" in e for e in errors), errors)
def test_logo_file_name_is_limited(self):
errors = check(dict(WITH_FILE, logo_file="crest.jpg"), ["crest.jpg"])
self.assertTrue(any("shield.svg or shield.png" in e for e in errors), errors)
def test_a_file_on_disk_means_use_real_logo(self):
for status in ("no-logo-exists", "logo-not-found"):
errors = check(dict(NO_EMBLEM, status=status), ["shield.svg"])
self.assertTrue(any("is use-real-logo" in e for e in errors), (status, errors))
errors = check(dict(NO_EMBLEM, status=status, logo_file="shield.png"), ["shield.png"])
self.assertTrue(any("is use-real-logo" in e for e in errors), (status, errors))
def test_a_trail_without_a_file_says_where_it_looked(self):
for base in (NO_EMBLEM, NOT_FOUND):
errors = check(dict(base, note=" "))
self.assertEqual(len(errors), 1, base["status"])
self.assertIn("shield.note", errors[0])
def test_logo_owner_is_still_required_with_a_file(self):
errors = check(dict(WITH_FILE, logo_owner=""), ["shield.png"])
self.assertTrue(any("logo_owner" in e for e in errors), errors)
if __name__ == "__main__":
unittest.main()
+186
View File
@@ -0,0 +1,186 @@
"""The [[history]] table of a trail record: its rules, and which fields count as facts.
Python 3 standard library only. Used by tools/validate.py (the shape of each entry) and by
tools/check_history.py (the check that a change to a fact comes with a history entry).
The table is documented in docs/schema.md, section "[[history]]".
"""
import datetime
import re
OWN_CHECK = "the dataset's own check"
OUTCOMES = ("applied", "declined")
RECORD = "record"
ENTRY_KEYS = ("date", "change", "fields", "basis", "basis_url", "asked_by", "outcome")
ENTRY_REQUIRED = ("date", "change", "fields", "basis", "asked_by", "outcome")
DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
URL_RE = re.compile(r"^https?://[^\s/]+\S*$")
# Every field a record can have, as the dotted path docs/schema.md uses. A history entry
# names these. A table name on its own ("source", "hike.source") names every field in it.
_TABLES = {
"": ("id", "name", "short_name", "short_name_url", "country", "regions", "length_km",
"length_note", "kind", "tier", "designation", "wave", "wave_note", "inclusion"),
"source": ("status", "publisher", "publisher_url", "url", "discovery", "format", "crs",
"licence", "licence_text", "permission_quote", "permission_by",
"permission_date", "permission_url", "attribution", "osm_only", "mainline",
"decision", "decision_text", "source_checked", "redistributable",
"line_source", "line_file", "line_absent_reason", "length_gap_note"),
"osm": ("relation", "note"),
"shield": ("status", "logo_source", "contact", "note", "logo_file", "logo_owner"),
"verification": ("verified", "date", "measured_km", "difference_percent", "parts", "note"),
"hike": ("summary", "official_url", "start", "end", "start_lonlat", "end_lonlat", "shape",
"days", "season", "months", "high_point", "high_point_m", "terrain", "travel",
"permit", "unfinished", "caution", "checked"),
"hike.source": ("url", "publisher", "facts"),
"route": ("creator", "year", "line_policy", "creator_words", "creator_words_url",
"creator_words_by", "note"),
"guide": ("title", "author", "access", "url", "format", "price", "price_checked",
"publisher", "isbn"),
"link": ("title", "publisher", "url", "note"),
}
SCHEMA_FIELDS = set()
for _table, _names in _TABLES.items():
if _table:
SCHEMA_FIELDS.add(_table)
SCHEMA_FIELDS.update(f"{_table}.{n}" if _table else n for n in _names)
# What counts as a fact about the trail or its track, and what does not.
# A change to a FACT needs a new history entry (tools/check_history.py). Anything not named
# in NOT_FACTS is a fact, so a field added to the schema later is a fact until it is listed.
# A name here covers every field under it ("verification" covers "verification.parts").
NOT_FACTS = (
"history", # the history itself
"verification", # figures and dates the tools refresh when they measure a track
"source.source_checked", "source.discovery", # when and how the source is read again
"source.format", "source.crs", "source.mainline", # how the source serves its track
"source.length_gap_note", # explains a measured gap, and is refreshed with it
"hike.summary", # our own wording of what the trail is; not a fact on its own
"hike.checked", # the date the hiker facts were read
"hike.source", # which pages the hiker facts were read on
"guide.price", "guide.price_checked", # a price read on a date, and refreshed
"osm.note", "shield.note", "route.note", "link", # notes and other pages about the trail
"wave", "wave_note", # the dataset's own bookkeeping
)
FACTS_TEXT = (
"name, short_name, short_name_url, country, regions, length_km, length_note, kind, tier, designation, "
"inclusion; source.* (status, publisher, publisher_url, url, licence, licence_text, "
"permission_*, attribution, osm_only, line_source, line_file, line_absent_reason, "
"decision, decision_text, redistributable); osm.relation; shield.* except note; "
"hike.* except summary, checked and source (start, end, official_url, days, season, terrain, "
"travel, high_point, permit, unfinished, caution and the rest); route.* except note; "
"guide.* except price. A replaced track file counts as a change to source.line_file."
)
NOT_FACTS_TEXT = (
"history; verification.*; source.source_checked, discovery, format, crs, mainline, "
"length_gap_note; hike.summary, hike.checked, hike.source; guide.price, "
"guide.price_checked; osm.note, shield.note, route.note; link; wave, wave_note."
)
TRACK_FIELD = "source.line_file"
def covers(listed, path):
"""True when the field name `listed` is `path` or a table that holds it."""
return path == listed or path.startswith(listed + ".")
def is_fact(path):
return not any(covers(name, path) for name in NOT_FACTS)
def _leaves(obj, prefix, out):
"""Collect path -> list of values. A list of tables adds one value per table, in order."""
if isinstance(obj, dict):
for key, value in obj.items():
_leaves(value, f"{prefix}.{key}" if prefix else key, out)
elif isinstance(obj, list) and obj and all(isinstance(x, dict) for x in obj):
for item in obj:
_leaves(item, prefix, out)
else:
out.setdefault(prefix, []).append(obj)
def leaves(rec):
out = {}
_leaves(rec, "", out)
return out
def changed_paths(old, new):
"""The field paths whose values differ between two records (history excluded)."""
a, b = leaves(old or {}), leaves(new or {})
return sorted(p for p in set(a) | set(b)
if a.get(p) != b.get(p) and not covers("history", p))
def entry_covers(entry, path):
return any(isinstance(f, str) and f != RECORD and covers(f, path) for f in entry.get("fields", []))
def is_own(entry):
return entry.get("asked_by") == OWN_CHECK
def check_entries(tid, rec, errors):
"""Check the shape of [[history]]: at least one entry, each well formed, oldest first."""
history = rec.get("history")
if history is None or history == []:
errors.append(f"{tid}: has no [[history]] entry (docs/schema.md, section [[history]])")
return
if not isinstance(history, list) or not all(isinstance(e, dict) for e in history):
errors.append(f"{tid}: history must be an array of tables ([[history]])")
return
previous = None
for i, e in enumerate(history, 1):
where = f"{tid}: history entry {i}"
for name in e:
if name not in ENTRY_KEYS:
errors.append(f"{where} has unknown field {name}")
for name in ENTRY_REQUIRED:
if name not in e:
errors.append(f"{where} is missing {name}")
for name in ("change", "basis", "asked_by"):
if name in e and (not isinstance(e[name], str) or not e[name].strip()):
errors.append(f"{where}: {name} must be a non-empty string")
date = e.get("date")
if "date" in e:
if not isinstance(date, str) or not DATE_RE.match(date):
errors.append(f"{where}: date must be YYYY-MM-DD")
else:
try:
datetime.date.fromisoformat(date)
except ValueError:
errors.append(f"{where}: date {date!r} is not a real date")
else:
if previous and date < previous:
errors.append(f"{where}: date {date} is earlier than the entry before it; "
"entries run oldest first")
previous = date
if "outcome" in e and e["outcome"] not in OUTCOMES:
errors.append(f"{where}: outcome must be one of {', '.join(OUTCOMES)}, not {e['outcome']!r}")
fields = e.get("fields")
if "fields" in e:
if not isinstance(fields, list) or not fields or not all(isinstance(f, str) for f in fields):
errors.append(f"{where}: fields must be a non-empty list of field names")
fields = None
else:
for f in fields:
if f != RECORD and f not in SCHEMA_FIELDS:
errors.append(f"{where}: fields names {f!r}, which is not a field of the record "
"(see docs/schema.md)")
if RECORD in fields and fields != [RECORD]:
errors.append(f"{where}: \"record\" cannot be listed with other fields")
is_added = fields == [RECORD]
if i == 1 and not is_added:
errors.append(f"{where}: the first entry must be the one that adds the record, "
'with fields = ["record"]')
if i > 1 and is_added:
errors.append(f"{where}: only the first entry may have fields = [\"record\"]")
if is_added and e.get("outcome") not in (None, "applied"):
errors.append(f"{where}: the entry that adds the record must have outcome \"applied\"")
url = e.get("basis_url")
if url is None:
if not is_added:
errors.append(f"{where} is missing basis_url (the page that was read, or the issue "
"or pull request address)")
elif not isinstance(url, str) or not URL_RE.match(url):
errors.append(f"{where}: basis_url must be an http(s) address")
+228 -32
View File
@@ -48,6 +48,11 @@ build_index = importlib.util.module_from_spec(spec)
spec.loader.exec_module(build_index)
load_toml = build_index.load_toml
spec = importlib.util.spec_from_file_location(
"trail_history", os.path.join(ROOT, "tools", "trail_history.py"))
trail_history = importlib.util.module_from_spec(spec)
spec.loader.exec_module(trail_history)
def haversine_km(coords):
total, R = 0.0, 6371.0088
@@ -135,6 +140,71 @@ def check_stated_permission(tid, src, errors):
errors.append(f"{tid}: licence stated-permission needs source.permission_url as an http(s) address")
SHIELD_STATUSES = ("use-real-logo", "no-logo-exists", "logo-not-found")
SHIELD_FILES = ("shield.svg", "shield.png")
def check_shield(tid, shield, tdir, errors):
"""The [shield] table: status, logo file and the words that go with each state.
use-real-logo: a logo file is included, and names its holder or source.
no-logo-exists: the trail has no emblem of its own; no file; the note says where that was checked.
logo-not-found: an emblem exists or may exist, but no usable artwork was found at an allowed
source; no file; the note says where it was looked for or seen.
"""
status = shield.get("status")
if not status:
errors.append(f"{tid}: missing required field shield.status")
elif status not in SHIELD_STATUSES:
errors.append(f"{tid}: shield.status {status!r} is not one of {', '.join(SHIELD_STATUSES)}")
logo_file = shield.get("logo_file") or ""
on_disk = [f for f in SHIELD_FILES if os.path.isfile(os.path.join(tdir, f))]
if logo_file and logo_file not in SHIELD_FILES:
errors.append(f"{tid}: shield.logo_file {logo_file!r} is not shield.svg or shield.png")
if status == "use-real-logo" and not logo_file:
errors.append(f"{tid}: shield.status is use-real-logo but shield.logo_file names no file "
"(a trail with no usable artwork is logo-not-found, or no-logo-exists when it has no emblem)")
if status in ("no-logo-exists", "logo-not-found"):
if logo_file or on_disk:
errors.append(f"{tid}: shield.status is {status} but a logo file is included; "
"a trail with a logo file is use-real-logo")
if not str(shield.get("note", "")).strip():
errors.append(f"{tid}: shield.status is {status} and shield.note does not say where an emblem was looked for")
if on_disk:
if logo_file not in on_disk:
errors.append(f"{tid}: logo file on disk {on_disk} but shield.logo_file is {logo_file!r}")
if not str(shield.get("logo_owner", "")).strip():
errors.append(f"{tid}: logo present but shield.logo_owner is empty")
if not str(shield.get("logo_source", "")).strip() and not str(shield.get("logo_owner", "")).strip():
errors.append(f"{tid}: logo present but its source and holder are not named")
if logo_file and not os.path.isfile(os.path.join(tdir, logo_file)):
errors.append(f"{tid}: declared logo file {logo_file} does not exist")
def check_guides(tid, guides, errors):
"""[[guide]]: a route needs at least one (checked with the route); any trail may have its holder's own."""
if guides is None:
return
if not isinstance(guides, list):
errors.append(f"{tid}: guide must be an array of tables")
return
for i, g in enumerate(guides, 1):
for field in ("title", "author", "access", "url"):
if not str(g.get(field, "")).strip():
errors.append(f"{tid}: guide {i} is missing {field}")
if g.get("access") not in ("free", "purchase"):
errors.append(
f"{tid}: guide {i} access must be \"free\" or \"purchase\", "
f"not {g.get('access')!r}")
if not str(g.get("url", "")).startswith(("https://", "http://")):
errors.append(f"{tid}: guide {i} url must be an http(s) URL")
if (str(g.get("price", "")).strip()
and not DATE_RE.match(str(g.get("price_checked", "")))):
errors.append(
f"{tid}: guide {i} has a price but no price_checked date "
"(YYYY-MM-DD)")
def check_hike(tid, rec, errors):
"""Check the optional [hike] table and its [[hike.source]] tables."""
hike = rec.get("hike")
@@ -447,6 +517,159 @@ def check_links(tid, rec, errors):
"that belongs in hike.official_url or source.publisher_url")
LEFT_OUT_FILE = "left-out.toml"
LEFT_OUT_REASONS = {
"below-floor", "rail-trail-or-towpath", "driving-route", "not-mainly-walking",
"network", "cannot-be-walked-through", "mostly-unbuilt",
"not-published-as-route", "waiting",
}
LEFT_OUT_KEYS = {
"id", "name", "country", "regions", "length_mi", "length_km", "length_note",
"reason", "note", "source_url", "decided", "was_listed", "waiting_for",
}
LEFT_OUT_REQUIRED = ("id", "name", "country", "regions", "reason", "note",
"decided", "was_listed")
LEFT_OUT_REGIONS = {
"AK", "AL", "AR", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "HI",
"IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MI", "MN",
"MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH",
"OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VT", "WA",
"WI", "WV", "WY",
"AB", "BC", "MB", "NB", "NL", "NS", "NT", "NU", "ON", "PE", "QC", "SK", "YT",
"all provinces and territories", "contiguous United States",
}
KM_PER_MI = 1.609344
def _left_out_name_key(name):
return " ".join(re.sub(r"[^a-z0-9]+", " ", str(name).lower()).split())
def check_left_out_entries(entries, trails, errors, where=LEFT_OUT_FILE):
"""Check the entries of left-out.toml against the listed trails.
entries is the file's [[trail]] list; trails the records in the dataset.
"""
if not isinstance(entries, list) or not entries:
errors.append(f"{where}: must hold at least one [[trail]] entry")
return
listed_ids = {r.get("id") for r in trails}
listed_names = {_left_out_name_key(r.get("name", "")) for r in trails}
seen_ids, seen_names = set(), set()
names = []
for i, e in enumerate(entries, 1):
if not isinstance(e, dict):
errors.append(f"{where}: entry {i} must be a table ([[trail]])")
continue
who = e.get("id") or f"entry {i}"
for field in LEFT_OUT_REQUIRED:
value = e.get(field)
if value in ("", None, []) or (isinstance(value, str) and not value.strip()):
errors.append(f"{where}: {who} is missing required field {field}")
for name in sorted(set(e) - LEFT_OUT_KEYS):
errors.append(f"{where}: {who} has unknown field {name}")
for field in ("id", "name", "note"):
value = e.get(field)
if field in e and (not isinstance(value, str) or not value.strip()):
errors.append(f"{where}: {who} {field} must be a non-empty string")
eid = e.get("id")
if isinstance(eid, str) and eid:
if not re.fullmatch(r"[a-z0-9]+(-[a-z0-9]+)*", eid):
errors.append(f"{where}: {eid!r} is not a plain id of lower case words and hyphens")
if eid in seen_ids:
errors.append(f"{where}: duplicate id {eid}")
seen_ids.add(eid)
if eid in listed_ids:
errors.append(f"{where}: {eid} matches a trail that is listed in the dataset")
ename = e.get("name")
if isinstance(ename, str) and ename.strip():
names.append(ename)
key = _left_out_name_key(ename)
if key in seen_names:
errors.append(f"{where}: duplicate name {ename}")
seen_names.add(key)
if key in listed_names:
errors.append(f"{where}: {ename} matches a trail that is listed in the dataset")
if "country" in e and e.get("country") not in ("US", "CA"):
errors.append(f"{where}: {who} country must be US or CA")
regions = e.get("regions")
if "regions" in e and regions not in ("", None, []):
if not isinstance(regions, list) or not regions:
errors.append(f"{where}: {who} regions must be a non-empty list of region codes")
else:
for code in regions:
if code not in LEFT_OUT_REGIONS:
errors.append(f"{where}: {who} region {code!r} is not a known state or province code")
if len(set(map(str, regions))) != len(regions):
errors.append(f"{where}: {who} regions repeats a code")
if "reason" in e and e.get("reason") not in LEFT_OUT_REASONS and str(e.get("reason")).strip():
errors.append(
f"{where}: {who} reason must be one of "
f"{', '.join(sorted(LEFT_OUT_REASONS))}, not {e.get('reason')!r}")
decided = e.get("decided")
if "decided" in e and str(decided).strip():
if not isinstance(decided, str) or not DATE_RE.match(decided):
errors.append(f"{where}: {who} decided must be a date (YYYY-MM-DD)")
else:
try:
datetime.date.fromisoformat(decided)
except ValueError:
errors.append(f"{where}: {who} decided {decided!r} is not a real date")
if "was_listed" in e and e.get("was_listed") not in ("", None):
if not isinstance(e.get("was_listed"), bool):
errors.append(f"{where}: {who} was_listed must be true or false")
url = e.get("source_url")
if "source_url" in e:
if not isinstance(url, str) or not url.startswith(("https://", "http://")):
errors.append(f"{where}: {who} source_url must be an http(s) URL")
elif "no page" not in str(e.get("note", "")).lower():
errors.append(
f"{where}: {who} has no source_url, and its note does not say that no page exists")
if e.get("reason") == "waiting":
waiting_for = e.get("waiting_for")
if not isinstance(waiting_for, str) or not waiting_for.strip():
errors.append(f"{where}: {who} reason is waiting, so waiting_for must say what would change the decision")
elif "waiting_for" in e:
errors.append(f"{where}: {who} waiting_for belongs to reason waiting only")
lengths = {}
for field in ("length_mi", "length_km"):
if field in e:
value = e[field]
if (not isinstance(value, (int, float)) or isinstance(value, bool)
or value <= 0):
errors.append(f"{where}: {who} {field} must be a positive number")
else:
lengths[field] = float(value)
if len(lengths) == 2:
km_from_mi = lengths["length_mi"] * KM_PER_MI
if abs(km_from_mi - lengths["length_km"]) > max(1.5, 0.02 * lengths["length_km"]):
errors.append(
f"{where}: {who} length_mi {e['length_mi']} and length_km "
f"{e['length_km']} do not agree")
if "length_note" in e:
note = e["length_note"]
if not isinstance(note, str) or not note.strip():
errors.append(f"{where}: {who} length_note must be a non-empty string")
if names != sorted(names, key=str.lower):
errors.append(f"{where}: entries must be sorted by name")
def check_left_out(root, trails, errors):
"""Check left-out.toml at the top level: trails considered and left out."""
path = os.path.join(root, LEFT_OUT_FILE)
if not os.path.isfile(path):
errors.append(f"{LEFT_OUT_FILE}: missing")
return
try:
doc = load_toml(path)
except Exception as e: # noqa: BLE001 - report and continue
errors.append(f"{LEFT_OUT_FILE}: does not parse: {e}")
return
for name in sorted(set(doc) - {"trail"}):
errors.append(f"{LEFT_OUT_FILE}: unknown top level field {name}")
check_left_out_entries(doc.get("trail"), trails, errors)
def main():
errors = []
trail_ids = build_index.trail_dirs(ROOT)
@@ -539,20 +762,7 @@ def main():
elif not str(src.get("line_absent_reason", "")).strip():
errors.append(f"{tid}: no line file, and source.line_absent_reason is empty")
shield = rec.get("shield", {})
if not shield.get("status"):
errors.append(f"{tid}: missing required field shield.status")
logo_file = shield.get("logo_file") or ""
on_disk = [f for f in ("shield.svg", "shield.png") if os.path.isfile(os.path.join(tdir, f))]
if on_disk:
if logo_file not in on_disk:
errors.append(f"{tid}: logo file on disk {on_disk} but shield.logo_file is {logo_file!r}")
if not str(shield.get("logo_owner", "")).strip():
errors.append(f"{tid}: logo present but shield.logo_owner is empty")
if not str(shield.get("logo_source", "")).strip() and not str(shield.get("logo_owner", "")).strip():
errors.append(f"{tid}: logo present but its source and holder are not named")
if logo_file and not os.path.isfile(os.path.join(tdir, logo_file)):
errors.append(f"{tid}: declared logo file {logo_file} does not exist")
check_shield(tid, rec.get("shield", {}), tdir, errors)
osm = rec.get("osm", {})
if "relation" not in osm:
@@ -583,22 +793,6 @@ def main():
"route.creator_words_url is missing")
if not isinstance(guides, list) or not guides:
errors.append(f"{tid}: kind is \"route\" but there is no [[guide]] table")
else:
for i, g in enumerate(guides, 1):
for field in ("title", "author", "access", "url"):
if not str(g.get(field, "")).strip():
errors.append(f"{tid}: guide {i} is missing {field}")
if g.get("access") not in ("free", "purchase"):
errors.append(
f"{tid}: guide {i} access must be \"free\" or \"purchase\", "
f"not {g.get('access')!r}")
if not str(g.get("url", "")).startswith(("https://", "http://")):
errors.append(f"{tid}: guide {i} url must be an http(s) URL")
if (str(g.get("price", "")).strip()
and not DATE_RE.match(str(g.get("price_checked", "")))):
errors.append(
f"{tid}: guide {i} has a price but no price_checked date "
"(YYYY-MM-DD)")
if policy in NO_LINE_POLICIES:
if src.get("line_file"):
errors.append(
@@ -617,12 +811,14 @@ def main():
else:
if route is not None:
errors.append(f"{tid}: [route] table present but kind is not \"route\"")
if guides:
errors.append(f"{tid}: [[guide]] present but kind is not \"route\"")
check_guides(tid, guides, errors)
check_links(tid, rec, errors)
check_hike(tid, rec, errors)
check_elevation(tid, tdir, rec, errors)
trail_history.check_entries(tid, rec, errors)
check_left_out(ROOT, trails, errors)
for dirpath, dirnames, filenames in os.walk(ROOT):
if ".git" in dirpath: