authors.toml gains a summary, a biography, the author's own site and the pages each was read on, for people only. An author's page now opens with the name and the summary, shows a joint credit only on the route it applies to, and carries an About section after the routes. People with three or more routes lead the authors page. Organisations get no biography. 35 people have a summary and a biography and 4 a summary only, each statement checked against the page it cites. Wilderness Mindset is recorded as two people. The Sawtooth Wilderness High Route is credited to Eric Poulin, who names himself as the author of Seeking Lost. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
305 lines
14 KiB
Python
305 lines
14 KiB
Python
"""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
|
|
[[list]] key, home (the lists the home page shows, and their order)
|
|
authors.toml [[author]] name, credits, optional kind, url, summary, bio, checked,
|
|
[[author.source]] (url, publisher)
|
|
|
|
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 datetime
|
|
import os
|
|
import re
|
|
import sys
|
|
import tomllib
|
|
|
|
ID_RE = re.compile(r"[a-z0-9]+(-[a-z0-9]+)*")
|
|
DASH_RE = re.compile(r"[–—]| - ")
|
|
DATE_RE = re.compile(r"\d{4}-\d{2}-\d{2}")
|
|
|
|
# authors.toml: what an [[author]] entry may hold, and the limits on its words.
|
|
# person (the default): one named person. people: human, but not one full name (a pair credited
|
|
# together, or a person known by a blog's name). organisation: credited, but given nothing more.
|
|
AUTHOR_KINDS = ("person", "people", "organisation")
|
|
AUTHOR_ABOUT = ("summary", "bio", "checked", "source") # for people only; refused on an organisation
|
|
AUTHOR_KEYS = {"name", "credits", "kind", "url", "summary", "bio", "checked", "source"}
|
|
AUTHOR_SOURCE_KEYS = {"url", "publisher"}
|
|
SUMMARY_MAX = 160 # characters
|
|
BIO_WORDS = (40, 130)
|
|
|
|
|
|
def built_in_list_keys():
|
|
"""The keys of the lists defined in web/olt/browse.py, or None when the generator cannot be read."""
|
|
web = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "web")
|
|
sys.path.insert(0, web)
|
|
try:
|
|
from olt import browse
|
|
return {lst.key for lst in browse.LISTS}
|
|
except Exception: # noqa: BLE001 - without the generator the keys are not checked
|
|
return None
|
|
finally:
|
|
sys.path.remove(web)
|
|
|
|
|
|
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_list_entries(entries, list_keys, errors, where="collections.toml"):
|
|
"""The [[list]] entries: a list's key and its place on the home page. Optional.
|
|
list_keys: the keys of the lists defined in web/olt/browse.py."""
|
|
if entries is None:
|
|
return
|
|
if not isinstance(entries, list):
|
|
errors.append(f"{where}: [[list]] must be an array of tables")
|
|
return
|
|
seen_keys, seen_home = set(), {}
|
|
for i, e in enumerate(entries, 1):
|
|
if not isinstance(e, dict):
|
|
errors.append(f"{where}: [[list]] entry {i} must be a table")
|
|
continue
|
|
who = f"{where}: [[list]] {e.get('key') or 'entry ' + str(i)}"
|
|
check_unknown(e, {"key", "home"}, who, errors)
|
|
key = _text(e, "key", who, errors)
|
|
if key and list_keys is not None and key not in list_keys:
|
|
errors.append(f"{who} is not the key of a list in web/olt/browse.py")
|
|
if key in seen_keys:
|
|
errors.append(f"{who} appears twice")
|
|
seen_keys.add(key)
|
|
home = e.get("home")
|
|
if home is None:
|
|
continue
|
|
if isinstance(home, bool) or not isinstance(home, int) or home < 1:
|
|
errors.append(f"{who} home must be a whole number from 1")
|
|
elif home in seen_home:
|
|
errors.append(f"{who} home {home} is also the place of {seen_home[home]}")
|
|
else:
|
|
seen_home[home] = key
|
|
|
|
|
|
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, AUTHOR_KEYS, who, errors)
|
|
if a.get("kind", "person") not in AUTHOR_KINDS:
|
|
errors.append(f"{who} kind must be one of {', '.join(AUTHOR_KINDS)}")
|
|
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")
|
|
if a.get("kind") == "organisation":
|
|
for k in AUTHOR_ABOUT:
|
|
if k in a:
|
|
errors.append(f"{who} is an organisation: {k} is for people only")
|
|
_url(a, "url", who, errors)
|
|
else:
|
|
check_author_about(a, name, who, errors)
|
|
|
|
|
|
def _date(value, where, field, errors):
|
|
"""A date written YYYY-MM-DD (a string, or a TOML date), real and not in the future."""
|
|
text = value.isoformat() if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime) else value
|
|
if not isinstance(text, str) or not DATE_RE.fullmatch(text):
|
|
errors.append(f"{where} {field} must be a date (YYYY-MM-DD)")
|
|
return
|
|
try:
|
|
day = datetime.date.fromisoformat(text)
|
|
except ValueError:
|
|
errors.append(f"{where} {field} {text!r} is not a real date")
|
|
return
|
|
if day > datetime.date.today():
|
|
errors.append(f"{where} {field} {text} is in the future")
|
|
|
|
|
|
def check_author_about(a, name, who, errors):
|
|
"""The words about an author: url, summary, bio, checked and [[author.source]]."""
|
|
_url(a, "url", who, errors)
|
|
summary = _text(a, "summary", who, errors, required=False)
|
|
bio = _text(a, "bio", who, errors, required=False)
|
|
if summary:
|
|
if len(summary) > SUMMARY_MAX:
|
|
errors.append(f"{who} summary is {len(summary)} characters; at most {SUMMARY_MAX}")
|
|
if name and not summary.lower().startswith(name.lower()):
|
|
errors.append(f"{who} summary must begin with the name {name!r}")
|
|
if "\n" in summary or not summary.endswith("."):
|
|
errors.append(f"{who} summary must be one sentence on one line, ending with a full stop")
|
|
if DASH_RE.search(summary):
|
|
errors.append(f"{who} summary uses a dash as punctuation")
|
|
if bio:
|
|
n = len(bio.split())
|
|
if not BIO_WORDS[0] <= n <= BIO_WORDS[1]:
|
|
errors.append(f"{who} bio is {n} words; it must be {BIO_WORDS[0]} to {BIO_WORDS[1]}")
|
|
if "\n" in bio.strip():
|
|
errors.append(f"{who} bio must be one paragraph on one line")
|
|
if not bio.rstrip().endswith((".", "?", "!")):
|
|
errors.append(f"{who} bio must end with a full stop")
|
|
if DASH_RE.search(bio):
|
|
errors.append(f"{who} bio uses a dash as punctuation")
|
|
about = bool(summary or bio)
|
|
if "checked" in a:
|
|
_date(a["checked"], who, "checked", errors)
|
|
elif about:
|
|
errors.append(f"{who} has a summary or bio but no checked date")
|
|
sources = a.get("source")
|
|
if sources is None:
|
|
if about:
|
|
errors.append(f"{who} has a summary or bio but no [[author.source]]")
|
|
elif not isinstance(sources, list) or not sources or not all(isinstance(x, dict) for x in sources):
|
|
errors.append(f"{who} source must be one or more [[author.source]] tables")
|
|
else:
|
|
for i, src in enumerate(sources, 1):
|
|
where = f"{who} source {i}"
|
|
check_unknown(src, AUTHOR_SOURCE_KEYS, where, errors)
|
|
_url(src, "url", where, errors, required=True)
|
|
_text(src, "publisher", where, errors)
|
|
urls = [x.get("url") for x in sources]
|
|
if len(set(urls)) != len(urls):
|
|
errors.append(f"{who} lists a source twice")
|
|
if not about and ("checked" in a or sources is not None):
|
|
errors.append(f"{who} has checked or [[author.source]] but no summary or bio")
|
|
|
|
|
|
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", "list"}):
|
|
errors.append(f"collections.toml: unknown top level field {name}")
|
|
check_collection_entries(doc.get("collection"), {r.get("id") for r in trails}, errors)
|
|
check_list_entries(doc.get("list"), built_in_list_keys(), 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)
|