Give every trail a permanent number in trail-numbers.txt, and check it is only appended to

The Saved page's short links will be bit sets over these numbers, so a number
must never change or be reused. The registry is one id per line, seeded
alphabetically; build_index appends new records; the validator fails on a
record with no line, a repeated id or a malformed line; check_history fails
when an earlier line is changed, moved or removed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-19 15:19:50 -07:00
1 parent 6440e43176
commit 358f0c4928
10 files changed
+580 -7

No files matched your search

+12 -1
View File
@@ -16,7 +16,12 @@ try:
except ModuleNotFoundError: # Python < 3.11: minimal fallback for this repo's TOML subset
tomllib = None
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, HERE)
import trail_numbers # noqa: E402
BEGIN = "<!-- BEGIN TRAIL TABLE -->"
END = "<!-- END TRAIL TABLE -->"
COUNT_BEGIN = "<!-- BEGIN COUNTS -->"
@@ -271,9 +276,15 @@ def main():
f.write(idx_data)
with open(readme_path, "w", encoding="utf-8") as f:
f.write(readme_data)
appended = trail_numbers.append(ROOT, [t["id"] for t in trails])
with_line = sum(1 for t in trails if t.get("source", {}).get("line_file"))
print(f"Wrote trails.csv, index.geojson and README table: "
f"{len(trails)} trails, {with_line} with a track.")
if appended:
print(f"Appended {len(appended)} to {trail_numbers.FILE}, in sorted order: "
f"{', '.join(appended)}. Commit the file with the record.")
else:
print(f"{trail_numbers.FILE} is complete: every record has a number.")
return 0
+22 -1
View File
@@ -13,6 +13,8 @@ For every trail.toml (or track file) that differs from the base, it
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);
* FAILS when a line of trail-numbers.txt that was in the base was changed, moved or removed
(the registry is only appended to; tools/trail_numbers.py);
* 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.
@@ -37,6 +39,7 @@ HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import build_index # noqa: E402
import trail_numbers # noqa: E402
import trail_history as H # noqa: E402
DEFAULT_BASES = ("origin/main", "github/main", "main")
@@ -199,6 +202,18 @@ def analyse(tid, old, new, track_changed=False, allow_edits=False):
return failures, loud, notes
def check_numbers(root, mb, out=print):
"""Failure messages when trail-numbers.txt changed an earlier line. Appending is allowed."""
done = git(root, "show", f"{mb}:{trail_numbers.FILE}", check=False)
path = os.path.join(root, trail_numbers.FILE)
if done.returncode != 0:
return [] # the base has no registry yet: this change introduces it
if not os.path.isfile(path):
return [f"{trail_numbers.FILE} was deleted; a retired trail keeps its line and its number"]
with open(path, encoding="utf-8") as f:
return trail_numbers.only_appended(done.stdout, f.read())
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)
@@ -222,10 +237,16 @@ def run(root, base=None, allow_edits=False, out=print):
if os.environ.get("GITHUB_ACTIONS") and not line.startswith(" "):
out(f"::error file={tid}/trail.toml::{line}")
failed = failed or bool(failures)
for line in check_numbers(root, mb):
failed = True
out(f"FAIL {line}")
if os.environ.get("GITHUB_ACTIONS"):
out(f"::error file={trail_numbers.FILE}::{line}")
if failed:
out("History check FAILED.")
return 1
out(f"OK history: {count} changed record{'s' if count != 1 else ''} checked.")
out(f"OK history: {count} changed record{'s' if count != 1 else ''} checked, "
f"{trail_numbers.FILE} only appended to.")
return 0
+180
View File
@@ -0,0 +1,180 @@
"""Tests for trail-numbers.txt: the validator's check, build_index's append, and the append-only
check in tools/check_history.py. No network. Run from the repository root:
python3 -m unittest discover tools/tests
"""
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 check_history as C # noqa: E402
import trail_numbers as N # noqa: E402
HEAD = "# a comment\n# another\n"
class ParseTest(unittest.TestCase):
def test_numbers_are_line_indexes_among_the_id_lines(self):
ids, problems = N.parse(HEAD + "a\nb-c\nd2\n")
self.assertEqual((ids, problems), (["a", "b-c", "d2"], []))
def test_malformed_lines_are_problems(self):
for text in (HEAD + "a\n\nb\n", # a blank line
HEAD + "a\nB\n", # upper case
HEAD + "a\n b\n", # leading space
HEAD + "a\nb \n", # trailing space
HEAD + "a\nb--c\n", # double hyphen
HEAD + "a\n-b\n",
HEAD + "a\nb c\n",
HEAD + "a\n# late comment\nb\n",
HEAD + "a\nb"): # no newline at the end
self.assertTrue(N.parse(text)[1], repr(text))
def test_an_id_twice_is_a_problem(self):
ids, problems = N.parse("a\nb\na\n")
self.assertEqual(ids, ["a", "b"])
self.assertEqual(len(problems), 1)
self.assertIn("already on line 1", problems[0])
class Root:
def __init__(self, test, text=None):
self.dir = tempfile.TemporaryDirectory()
test.addCleanup(self.dir.cleanup)
self.root = self.dir.name
if text is not None:
self.write(text)
def write(self, text):
with open(os.path.join(self.root, N.FILE), "w", encoding="utf-8", newline="\n") as f:
f.write(text)
def read(self):
with open(os.path.join(self.root, N.FILE), encoding="utf-8") as f:
return f.read()
class ValidatorTest(unittest.TestCase):
def errors(self, text, ids):
errors = []
N.check(Root(self, text).root, ids, errors)
return errors
def test_complete_passes(self):
self.assertEqual(self.errors(HEAD + "a\nb\n", ["a", "b"]), [])
def test_a_record_with_no_line_fails(self):
errors = self.errors(HEAD + "a\n", ["a", "b"])
self.assertEqual(len(errors), 1)
self.assertTrue(errors[0].startswith("b: has no line"))
def test_a_retired_number_is_not_an_error(self):
self.assertEqual(self.errors(HEAD + "a\ngone\nb\n", ["a", "b"]), [])
def test_a_duplicate_and_a_malformed_line_fail(self):
self.assertTrue(self.errors(HEAD + "a\na\n", ["a"]))
self.assertTrue(self.errors(HEAD + "a\nNot An Id\n", ["a"]))
def test_a_missing_file_fails(self):
errors = []
N.check(Root(self).root, ["a"], errors)
self.assertTrue(errors)
class AppendTest(unittest.TestCase):
def test_creates_a_seeded_file_in_alphabetical_order(self):
r = Root(self)
self.assertEqual(N.append(r.root, ["c", "a", "b"]), ["a", "b", "c"])
self.assertEqual(N.parse(r.read()), (["a", "b", "c"], []))
self.assertTrue(r.read().startswith("# "))
def test_appends_only_the_missing_in_sorted_order_and_leaves_lines_alone(self):
text = HEAD + "m\ngone\na\n"
r = Root(self, text)
self.assertEqual(N.append(r.root, ["m", "a", "z", "d"]), ["d", "z"])
self.assertEqual(r.read(), text + "d\nz\n")
def test_second_run_changes_nothing(self):
r = Root(self, HEAD + "a\n")
N.append(r.root, ["a", "b"])
before = r.read()
self.assertEqual(N.append(r.root, ["a", "b"]), [])
self.assertEqual(r.read(), before)
def test_a_retired_trail_keeps_its_line(self):
r = Root(self, HEAD + "a\nb\nc\n")
N.append(r.root, ["a", "c", "d"])
self.assertEqual(N.parse(r.read())[0], ["a", "b", "c", "d"])
class OnlyAppendedTest(unittest.TestCase):
OLD = HEAD + "a\nb\nc\n"
def test_appending_is_allowed(self):
self.assertEqual(N.only_appended(self.OLD, self.OLD + "d\ne\n"), [])
def test_the_header_is_free(self):
self.assertEqual(N.only_appended(self.OLD, "# new words\na\nb\nc\nd\n"), [])
def test_changed_removed_and_reordered_fail(self):
self.assertTrue(N.only_appended(self.OLD, HEAD + "a\nx\nc\n")) # changed
self.assertTrue(N.only_appended(self.OLD, HEAD + "a\nc\n")) # removed in the middle
self.assertTrue(N.only_appended(self.OLD, HEAD + "a\nb\n")) # removed at the end
self.assertTrue(N.only_appended(self.OLD, HEAD + "a\nc\nb\n")) # reordered
self.assertTrue(N.only_appended(self.OLD, HEAD + "z\na\nb\nc\n")) # inserted at the front
self.assertTrue(N.only_appended(self.OLD, "")) # emptied
class GitCheckTest(unittest.TestCase):
"""C.check_numbers against a scratch repository."""
def repo(self, text):
r = Root(self, text)
self.git(r.root, "init", "-q")
self.git(r.root, "add", "-A")
self.git(r.root, "commit", "-q", "-m", "base")
mb = self.git(r.root, "rev-parse", "HEAD").strip()
return r, mb
@staticmethod
def git(root, *args):
done = subprocess.run(["git", "-C", root, "-c", "user.name=t", "-c", "user.email=t@example.invalid", *args],
capture_output=True, text=True, check=True)
return done.stdout
def test_append_passes_and_edits_fail(self):
r, mb = self.repo(HEAD + "a\nb\n")
self.assertEqual(C.check_numbers(r.root, mb), [])
r.write(HEAD + "a\nb\nc\n")
self.assertEqual(C.check_numbers(r.root, mb), [])
r.write(HEAD + "b\na\n")
self.assertTrue(C.check_numbers(r.root, mb))
r.write(HEAD + "a\n")
self.assertTrue(C.check_numbers(r.root, mb))
os.unlink(os.path.join(r.root, N.FILE))
self.assertTrue(C.check_numbers(r.root, mb))
def test_a_base_without_the_registry_allows_introducing_it(self):
r, mb = self.repo(HEAD + "a\n")
self.git(r.root, "rm", "-q", "--cached", N.FILE)
self.git(r.root, "commit", "-q", "-m", "without")
mb = self.git(r.root, "rev-parse", "HEAD").strip()
self.assertEqual(C.check_numbers(r.root, mb), [])
class RepositoryTest(unittest.TestCase):
def test_this_repository_has_a_number_for_every_record(self):
import build_index
root = os.path.dirname(TOOLS)
errors = []
N.check(root, build_index.trail_dirs(root), errors)
self.assertEqual(errors, [])
if __name__ == "__main__":
unittest.main()
+119
View File
@@ -0,0 +1,119 @@
"""The trail-number registry, trail-numbers.txt: a permanent number for every trail.
Python 3 standard library only. Used by tools/validate.py (every record has a line; no id twice;
no malformed line), by tools/build_index.py (appends the records that have none), and by
tools/check_history.py (an earlier line is never changed, removed or reordered). The file is
documented in docs/schema.md, section "trail-numbers.txt".
The file is one trail id per line. A trail's number is the zero-based index of its line among the
id lines. Lines starting with # are comments and may come only before the first id. Lines are only
ever appended: a trail that leaves the catalogue keeps its line, so its number is retired and is
never given to another trail. The Saved page's short links are bit sets over these numbers
(web/assets/app.js, "SavedCode").
"""
import os
import re
FILE = "trail-numbers.txt"
ID_RE = re.compile(r"[a-z0-9]+(-[a-z0-9]+)*")
HEADER = """\
# Trail numbers. One trail id per line; a trail's number is the zero-based index of its line
# among the id lines (comments are not counted). The Saved page's short links use these numbers,
# so a line is never changed, moved or removed, and a number is never reused: a trail that
# leaves the catalogue keeps its line. Only append. python3 tools/build_index.py appends the
# records that have no line yet, in sorted order. Seeded alphabetically by id.
"""
def parse(text):
"""(ids, problems) from the file's text. ids is the list of id lines, in order."""
ids, problems = [], []
seen = {}
if text and not text.endswith("\n"):
problems.append(f"{FILE}: the last line has no newline at its end")
lines = text.split("\n")
if lines and lines[-1] == "":
lines.pop()
for n, line in enumerate(lines, 1):
if line.startswith("#"):
if ids:
problems.append(f"{FILE}:{n}: a comment after the first id")
continue
if not ID_RE.fullmatch(line):
problems.append(f"{FILE}:{n}: not a trail id (lower-case words joined by hyphens, "
f"nothing else on the line): {line!r}")
continue
if line in seen:
problems.append(f"{FILE}:{n}: {line} is already on line {seen[line]}")
continue
seen[line] = n
ids.append(line)
return ids, problems
def read(root):
"""(ids, problems) from the registry in root; a missing file is one problem."""
path = os.path.join(root, FILE)
if not os.path.isfile(path):
return [], [f"{FILE} is missing: run python3 tools/build_index.py"]
with open(path, encoding="utf-8") as f:
return parse(f.read())
def check(root, trail_ids, errors):
"""Append one message per problem: a malformed line, an id twice, a record with no number.
An id with no record is a retired number and is fine."""
ids, problems = read(root)
errors.extend(problems)
have = set(ids)
for tid in sorted(trail_ids):
if tid not in have:
errors.append(f"{tid}: has no line in {FILE}: run python3 tools/build_index.py")
def missing(root, trail_ids):
"""The record ids with no line, sorted."""
ids, _ = read(root)
have = set(ids)
return sorted(t for t in trail_ids if t not in have)
def seed_text(trail_ids):
return HEADER + "".join(f"{t}\n" for t in sorted(trail_ids))
def append(root, trail_ids):
"""Append the records with no line, in sorted order, never touching an existing line.
Creates the file (seeded alphabetically, with its header) when there is none.
Returns the ids appended."""
path = os.path.join(root, FILE)
if not os.path.isfile(path):
with open(path, "w", encoding="utf-8", newline="\n") as f:
f.write(seed_text(trail_ids))
return sorted(trail_ids)
new = missing(root, trail_ids)
if new:
with open(path, "r+", encoding="utf-8", newline="\n") as f:
text = f.read()
f.seek(0, 2)
if text and not text.endswith("\n"):
f.write("\n")
f.write("".join(f"{t}\n" for t in new))
return new
def only_appended(old_text, new_text):
"""Problems (a list of sentences) when new_text changes, removes or reorders an id line of
old_text. Appending is the only change allowed; the comment header is free."""
old, _ = parse(old_text)
new, _ = parse(new_text)
problems = []
for i, tid in enumerate(old):
if i >= len(new):
problems.append(f"{FILE}: line {i} ({tid}) was removed; a retired trail keeps its line")
break
if new[i] != tid:
problems.append(f"{FILE}: id line {i} was {tid} and is now {new[i]}; "
f"lines are never changed, moved or removed, only appended")
return problems
+6
View File
@@ -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(
"trail_numbers", os.path.join(ROOT, "tools", "trail_numbers.py"))
trail_numbers = importlib.util.module_from_spec(spec)
spec.loader.exec_module(trail_numbers)
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)
@@ -928,6 +933,7 @@ def main():
check_left_out(ROOT, trails, errors)
check_datafiles.check_datafiles(ROOT, trails, errors)
trail_numbers.check(ROOT, trail_ids, errors)
for dirpath, dirnames, filenames in os.walk(ROOT):
if ".git" in dirpath: