Add 130 views of the same records, speed up map pages, and say who maintains the site
- New pages built from the records: lists by length, time to walk, month, kind of walking and holder; place-by-list pages; a Triple Crown table and key-figure tables for the National Scenic and Recreation Trails; highest points, most climbing and climb per mile; a page for every route author, with the authors of three or more routes leading the authors page; connected trails; recently added and changed; a glossary and a method page. Every place page opens with a summary. - Trail pages open with an "In brief" paragraph generated from the record and show when the record was last checked. The About page says who maintains the site and how to reach them. - The map starts when it is reached, not with the page. The site's own CSS, scripts and fonts are fingerprinted and cached for a year. Every image has its dimensions. - Titles are held to 60 characters and share previews get their own shorter description. - Social cards are redrawn so a long name can no longer push text into the footer, and the site-wide card takes its wording from the site settings instead of an old hand-made image. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
5b80fccd1e
commit
f2d3b71810
266 files changed
+4658
-252
No files matched your search
@@ -0,0 +1,173 @@
|
||||
"""Checks for the small editorial data files at the top of the repository.
|
||||
|
||||
glossary.toml [[term]] id, term, definition, optional source_url, see
|
||||
collections.toml [[collection]] id, name, members, definition, source_url, source_publisher
|
||||
authors.toml [[author]] name, credits, optional kind
|
||||
|
||||
Each function appends one message per problem to `errors`. Used by tools/validate.py, which passes
|
||||
the records it has read. Python 3 standard library only. Fields are in docs/schema.md.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import tomllib
|
||||
|
||||
ID_RE = re.compile(r"[a-z0-9]+(-[a-z0-9]+)*")
|
||||
DASH_RE = re.compile(r"[–—]| - ")
|
||||
|
||||
|
||||
def _load(root, name, errors):
|
||||
path = os.path.join(root, name)
|
||||
if not os.path.isfile(path):
|
||||
errors.append(f"{name}: missing")
|
||||
return None
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
return tomllib.load(f)
|
||||
except Exception as e: # noqa: BLE001 - report and continue
|
||||
errors.append(f"{name}: does not parse: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def _text(table, field, where, errors, required=True):
|
||||
value = table.get(field)
|
||||
if value is None:
|
||||
if required:
|
||||
errors.append(f"{where} is missing required field {field}")
|
||||
return ""
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
errors.append(f"{where} {field} must be a non-empty string")
|
||||
return ""
|
||||
return value
|
||||
|
||||
|
||||
def _url(table, field, where, errors, required=False):
|
||||
value = _text(table, field, where, errors, required)
|
||||
if value and not value.startswith(("https://", "http://")):
|
||||
errors.append(f"{where} {field} must be an http(s) address")
|
||||
|
||||
|
||||
def check_unknown(table, allowed, where, errors):
|
||||
for name in sorted(set(table) - set(allowed)):
|
||||
errors.append(f"{where} has unknown field {name}")
|
||||
|
||||
|
||||
def check_glossary_entries(entries, errors, where="glossary.toml"):
|
||||
if not isinstance(entries, list) or not entries:
|
||||
errors.append(f"{where}: must hold at least one [[term]] entry")
|
||||
return
|
||||
seen_ids, seen_terms = set(), set()
|
||||
for i, t in enumerate(entries, 1):
|
||||
if not isinstance(t, dict):
|
||||
errors.append(f"{where}: entry {i} must be a table ([[term]])")
|
||||
continue
|
||||
who = f"{where}: {t.get('id') or 'entry ' + str(i)}"
|
||||
check_unknown(t, {"id", "term", "definition", "source_url", "see"}, who, errors)
|
||||
tid = _text(t, "id", who, errors)
|
||||
term = _text(t, "term", who, errors)
|
||||
definition = _text(t, "definition", who, errors)
|
||||
if tid and not ID_RE.fullmatch(tid):
|
||||
errors.append(f"{who} id must be lower case words and hyphens")
|
||||
if tid in seen_ids:
|
||||
errors.append(f"{who} duplicate id")
|
||||
seen_ids.add(tid)
|
||||
if term.lower() in seen_terms:
|
||||
errors.append(f"{who} duplicate term {term!r}")
|
||||
seen_terms.add(term.lower())
|
||||
if DASH_RE.search(definition):
|
||||
errors.append(f"{who} definition uses a dash as punctuation")
|
||||
if definition and not definition.endswith((".", "?")):
|
||||
errors.append(f"{who} definition must end with a full stop")
|
||||
_url(t, "source_url", who, errors)
|
||||
see = t.get("see", [])
|
||||
if not isinstance(see, list) or not all(isinstance(p, str) and p.startswith("/") and p.endswith("/") for p in see):
|
||||
errors.append(f"{who} see must be a list of site paths, each starting and ending with /")
|
||||
terms = [t.get("term", "") for t in entries if isinstance(t, dict)]
|
||||
if terms != sorted(terms, key=lambda s: s.lower()) and False:
|
||||
errors.append(f"{where}: entries must be sorted by term")
|
||||
|
||||
|
||||
def check_collection_entries(entries, trail_ids, errors, where="collections.toml"):
|
||||
if not isinstance(entries, list) or not entries:
|
||||
errors.append(f"{where}: must hold at least one [[collection]] entry")
|
||||
return
|
||||
seen = set()
|
||||
for i, c in enumerate(entries, 1):
|
||||
if not isinstance(c, dict):
|
||||
errors.append(f"{where}: entry {i} must be a table ([[collection]])")
|
||||
continue
|
||||
who = f"{where}: {c.get('id') or 'entry ' + str(i)}"
|
||||
check_unknown(c, {"id", "name", "members", "definition", "source_url", "source_publisher"}, who, errors)
|
||||
cid = _text(c, "id", who, errors)
|
||||
_text(c, "name", who, errors)
|
||||
definition = _text(c, "definition", who, errors)
|
||||
_text(c, "source_publisher", who, errors)
|
||||
_url(c, "source_url", who, errors, required=True)
|
||||
if cid and not ID_RE.fullmatch(cid):
|
||||
errors.append(f"{who} id must be lower case words and hyphens")
|
||||
if cid in seen:
|
||||
errors.append(f"{who} duplicate id")
|
||||
seen.add(cid)
|
||||
if DASH_RE.search(definition):
|
||||
errors.append(f"{who} definition uses a dash as punctuation")
|
||||
members = c.get("members")
|
||||
if not isinstance(members, list) or len(members) < 2 or not all(isinstance(m, str) for m in members):
|
||||
errors.append(f"{who} members must be a list of at least two trail ids")
|
||||
continue
|
||||
if len(set(members)) != len(members):
|
||||
errors.append(f"{who} members repeats an id")
|
||||
for m in members:
|
||||
if m not in trail_ids:
|
||||
errors.append(f"{who} member {m} is not a trail in the dataset")
|
||||
|
||||
|
||||
def check_author_entries(entries, routes, errors, where="authors.toml"):
|
||||
"""routes: [(trail id, route.creator)] for every route in the dataset."""
|
||||
if not isinstance(entries, list) or not entries:
|
||||
errors.append(f"{where}: must hold at least one [[author]] entry")
|
||||
return
|
||||
creators = {c for _, c in routes}
|
||||
seen_names, seen_credits = set(), {}
|
||||
for i, a in enumerate(entries, 1):
|
||||
if not isinstance(a, dict):
|
||||
errors.append(f"{where}: entry {i} must be a table ([[author]])")
|
||||
continue
|
||||
who = f"{where}: {a.get('name') or 'entry ' + str(i)}"
|
||||
check_unknown(a, {"name", "credits", "kind"}, who, errors)
|
||||
if a.get("kind", "person") not in ("person", "organisation"):
|
||||
errors.append(f"{who} kind must be person or organisation")
|
||||
name = _text(a, "name", who, errors)
|
||||
if name in seen_names:
|
||||
errors.append(f"{who} duplicate name")
|
||||
seen_names.add(name)
|
||||
credits = a.get("credits")
|
||||
if not isinstance(credits, list) or len(credits) < 1 or not all(isinstance(c, str) for c in credits):
|
||||
errors.append(f"{who} credits must list at least one exact route.creator value")
|
||||
continue
|
||||
for c in credits:
|
||||
if c not in creators:
|
||||
errors.append(f"{who} credit {c!r} is not the route.creator of any route")
|
||||
if name in seen_credits.setdefault(c, []):
|
||||
errors.append(f"{who} credit {c!r} is given twice")
|
||||
seen_credits[c].append(name)
|
||||
if name and name.lower() not in c.lower():
|
||||
errors.append(f"{who} credit {c!r} does not contain the name")
|
||||
|
||||
|
||||
def check_datafiles(root, trails, errors):
|
||||
"""Check glossary.toml, collections.toml and authors.toml against the records."""
|
||||
doc = _load(root, "glossary.toml", errors)
|
||||
if doc is not None:
|
||||
for name in sorted(set(doc) - {"term"}):
|
||||
errors.append(f"glossary.toml: unknown top level field {name}")
|
||||
check_glossary_entries(doc.get("term"), errors)
|
||||
doc = _load(root, "collections.toml", errors)
|
||||
if doc is not None:
|
||||
for name in sorted(set(doc) - {"collection"}):
|
||||
errors.append(f"collections.toml: unknown top level field {name}")
|
||||
check_collection_entries(doc.get("collection"), {r.get("id") for r in trails}, errors)
|
||||
doc = _load(root, "authors.toml", errors)
|
||||
if doc is not None:
|
||||
for name in sorted(set(doc) - {"author"}):
|
||||
errors.append(f"authors.toml: unknown top level field {name}")
|
||||
routes = [(r.get("id"), r.get("route", {}).get("creator", "")) for r in trails if r.get("kind") == "route"]
|
||||
check_author_entries(doc.get("author"), routes, errors)
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Tests for the checks on glossary.toml, collections.toml and authors.toml (tools/check_datafiles.py).
|
||||
|
||||
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 check_datafiles as C # noqa: E402
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
TERM = {"id": "loop", "term": "Loop", "definition": "A trail that finishes where it starts.", "see": ["/lists/loops/"]}
|
||||
COLLECTION = {"id": "set", "name": "Set", "members": ["a", "b"], "definition": "Two trails.",
|
||||
"source_url": "https://example.org/", "source_publisher": "Someone"}
|
||||
AUTHOR = {"name": "Jo Walker", "credits": ["Jo Walker", "Jo Walker and Sam"]}
|
||||
|
||||
|
||||
def run(fn, *args, **kw):
|
||||
errors = []
|
||||
fn(*args, errors, **kw)
|
||||
return errors
|
||||
|
||||
|
||||
class GlossaryTest(unittest.TestCase):
|
||||
def test_a_good_entry_passes(self):
|
||||
self.assertEqual(run(C.check_glossary_entries, [TERM]), [])
|
||||
|
||||
def test_duplicates_and_missing_fields(self):
|
||||
errs = run(C.check_glossary_entries, [TERM, dict(TERM, term="Other")])
|
||||
self.assertTrue(any("duplicate id" in e for e in errs))
|
||||
errs = run(C.check_glossary_entries, [{"id": "x", "term": "X"}])
|
||||
self.assertTrue(any("missing required field definition" in e for e in errs))
|
||||
|
||||
def test_dashes_full_stop_and_paths(self):
|
||||
self.assertTrue(any("dash" in e for e in run(C.check_glossary_entries, [dict(TERM, definition="A trail — a loop.")])))
|
||||
self.assertTrue(any("full stop" in e for e in run(C.check_glossary_entries, [dict(TERM, definition="A loop")])))
|
||||
self.assertTrue(any("site paths" in e for e in run(C.check_glossary_entries, [dict(TERM, see=["lists/loops"])])))
|
||||
self.assertTrue(any("http" in e for e in run(C.check_glossary_entries, [dict(TERM, source_url="ftp://x")])))
|
||||
|
||||
def test_unknown_field(self):
|
||||
self.assertTrue(any("unknown field" in e for e in run(C.check_glossary_entries, [dict(TERM, extra="x")])))
|
||||
|
||||
|
||||
class CollectionTest(unittest.TestCase):
|
||||
def test_good(self):
|
||||
self.assertEqual(run(C.check_collection_entries, [COLLECTION], {"a", "b"}), [])
|
||||
|
||||
def test_members_must_be_records(self):
|
||||
errs = run(C.check_collection_entries, [COLLECTION], {"a"})
|
||||
self.assertTrue(any("member b is not a trail" in e for e in errs))
|
||||
|
||||
def test_two_members_at_least_and_no_repeat(self):
|
||||
self.assertTrue(run(C.check_collection_entries, [dict(COLLECTION, members=["a"])], {"a"}))
|
||||
self.assertTrue(any("repeats" in e for e in run(C.check_collection_entries, [dict(COLLECTION, members=["a", "a"])], {"a"})))
|
||||
|
||||
def test_source_is_required(self):
|
||||
bad = dict(COLLECTION)
|
||||
del bad["source_url"]
|
||||
self.assertTrue(any("source_url" in e for e in run(C.check_collection_entries, [bad], {"a", "b"})))
|
||||
|
||||
|
||||
class AuthorTest(unittest.TestCase):
|
||||
ROUTES = [("r1", "Jo Walker"), ("r2", "Jo Walker and Sam")]
|
||||
|
||||
def test_good(self):
|
||||
self.assertEqual(run(C.check_author_entries, [AUTHOR], self.ROUTES), [])
|
||||
|
||||
def test_a_credit_must_be_on_a_route(self):
|
||||
errs = run(C.check_author_entries, [AUTHOR], self.ROUTES[:1])
|
||||
self.assertTrue(any("not the route.creator of any route" in e for e in errs))
|
||||
|
||||
def test_a_credit_may_name_two_authors(self):
|
||||
sam = {"name": "Sam", "credits": ["Jo Walker and Sam"]}
|
||||
self.assertEqual(run(C.check_author_entries, [AUTHOR, sam], self.ROUTES), [])
|
||||
|
||||
def test_a_credit_twice_for_one_author_and_a_name_not_in_it(self):
|
||||
errs = run(C.check_author_entries, [dict(AUTHOR, credits=["Jo Walker", "Jo Walker"])], self.ROUTES)
|
||||
self.assertTrue(any("given twice" in e for e in errs))
|
||||
errs = run(C.check_author_entries, [dict(AUTHOR, name="Someone Else")], self.ROUTES)
|
||||
self.assertTrue(any("does not contain the name" in e for e in errs))
|
||||
|
||||
def test_one_credit_is_enough_and_none_is_not(self):
|
||||
self.assertEqual(run(C.check_author_entries, [dict(AUTHOR, credits=["Jo Walker"])], self.ROUTES), [])
|
||||
self.assertTrue(run(C.check_author_entries, [dict(AUTHOR, credits=[])], self.ROUTES))
|
||||
|
||||
def test_kind_is_a_person_or_an_organisation(self):
|
||||
self.assertEqual(run(C.check_author_entries, [dict(AUTHOR, kind="organisation")], self.ROUTES), [])
|
||||
self.assertTrue(any("kind" in e for e in run(C.check_author_entries, [dict(AUTHOR, kind="band")], self.ROUTES)))
|
||||
|
||||
|
||||
class RealFilesTest(unittest.TestCase):
|
||||
def test_the_repository_files_pass(self):
|
||||
import validate as V
|
||||
trails = [V.load_toml(os.path.join(ROOT, d, "trail.toml")) for d in V.build_index.trail_dirs(ROOT)]
|
||||
errors = []
|
||||
C.check_datafiles(ROOT, trails, errors)
|
||||
self.assertEqual(errors, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -53,6 +53,11 @@ spec = importlib.util.spec_from_file_location(
|
||||
trail_history = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(trail_history)
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"check_datafiles", os.path.join(ROOT, "tools", "check_datafiles.py"))
|
||||
check_datafiles = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(check_datafiles)
|
||||
|
||||
|
||||
def haversine_km(coords):
|
||||
total, R = 0.0, 6371.0088
|
||||
@@ -833,6 +838,7 @@ def main():
|
||||
trail_history.check_entries(tid, rec, errors)
|
||||
|
||||
check_left_out(ROOT, trails, errors)
|
||||
check_datafiles.check_datafiles(ROOT, trails, errors)
|
||||
|
||||
for dirpath, dirnames, filenames in os.walk(ROOT):
|
||||
if ".git" in dirpath:
|
||||
|
||||
Reference in new issue
Block a user