wobblyhead hg > wobbly_ssg
comparison tools/update_index.py @ 0:71dd8d58a8e5 default tip
cleaned up re-init from net_wobblyhead_www project tooling
| author | ark |
|---|---|
| date | 2026-10-22 14:59 +0200 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| -1:000000000000 | 0:71dd8d58a8e5 |
|---|---|
| 1 #!/usr/bin/env python3 | |
| 2 """rewrite the entry lists of the index pages in src/ from the headers of the | |
| 3 sources they list. | |
| 4 | |
| 5 an index.md below src/ lists the published sources in its own directory. an | |
| 6 entry is a link line to a .md file, optionally followed by a date, then a | |
| 7 definition line with the subtitle, or the description if there is no | |
| 8 subtitle. the date in the existing entries decides which header is shown: a | |
| 9 full date (dd.mm.yyyy) means created_at, anything else means timeframe. | |
| 10 entries are sorted newest first, by created_at or by the start of the | |
| 11 timeframe, then by updated_at, then by file modification time, and finally by | |
| 12 title. | |
| 13 | |
| 14 the root index.md has one section per entry in the index_sections setting of | |
| 15 config.txt, each listing the newest entries of a directory, as many as | |
| 16 index_recent says. a section runs from its heading to the next heading; text | |
| 17 around the entries, such as a "more" link, is kept. without index_sections the | |
| 18 root index.md is left alone. | |
| 19 | |
| 20 a changed index gets today's date as updated_at.""" | |
| 21 | |
| 22 import argparse | |
| 23 import datetime | |
| 24 import difflib | |
| 25 import re | |
| 26 import sys | |
| 27 | |
| 28 from make_site import (CONFIG, SRC, BuildError, error, parse_header_block, | |
| 29 read_config, warn) | |
| 30 | |
| 31 # an entry starts with a link to a .md file and an optional date beginning | |
| 32 # with a digit. links to anything else, such as a directory, are not entries. | |
| 33 ENTRY = re.compile(r"\[[^\]]*\]\([^)\s]+\.md\)(?:[ \t]+(\d.*?))?[ \t]*$") | |
| 34 DEFINITION = re.compile(r":[ \t]") | |
| 35 CONTINUATION = re.compile(r"[ \t]+\S") | |
| 36 FULL_DATE = re.compile(r"\d{2}\.\d{2}\.\d{4}$") | |
| 37 # the start of a timeframe: mm.yyyy or yyyy | |
| 38 TIMEFRAME_START = re.compile(r"\s*(?:(\d{1,2})\.)?(\d{4})") | |
| 39 HEADING = re.compile(r"#+[ \t]+(.*?)[ \t]*$") | |
| 40 | |
| 41 | |
| 42 def header_end(lines): | |
| 43 """the index of the blank line that ends the header block.""" | |
| 44 for i, line in enumerate(lines): | |
| 45 if not line.strip(): | |
| 46 return i | |
| 47 return len(lines) | |
| 48 | |
| 49 | |
| 50 def find_entries(lines, start, end): | |
| 51 """the run of entries in lines[start:end] as (first line, line after the | |
| 52 last entry, dates of the entries), or None when there is no entry. the | |
| 53 run may contain other lines between entries; they are part of the run.""" | |
| 54 first = None | |
| 55 stop = None | |
| 56 dates = [] | |
| 57 i = start | |
| 58 while i < end: | |
| 59 match = ENTRY.match(lines[i]) | |
| 60 if not match: | |
| 61 i += 1 | |
| 62 continue | |
| 63 if first is None: | |
| 64 first = i | |
| 65 dates.append(match.group(1) or "") | |
| 66 # the definition and its folded lines belong to the entry | |
| 67 i += 1 | |
| 68 if i < end and DEFINITION.match(lines[i]): | |
| 69 i += 1 | |
| 70 while i < end and CONTINUATION.match(lines[i]): | |
| 71 i += 1 | |
| 72 stop = i | |
| 73 if first is None: | |
| 74 return None | |
| 75 return first, stop, dates | |
| 76 | |
| 77 | |
| 78 def sort_key(value, mode): | |
| 79 """a sortable form of a created_at or timeframe value, or None if the | |
| 80 value is empty or not understood.""" | |
| 81 if mode == "created_at": | |
| 82 try: | |
| 83 return datetime.datetime.fromisoformat(value).date() | |
| 84 except ValueError: | |
| 85 return None | |
| 86 match = TIMEFRAME_START.match(value) | |
| 87 if not match: | |
| 88 return None | |
| 89 return int(match.group(2)), int(match.group(1) or 0) | |
| 90 | |
| 91 | |
| 92 def read_entries(directory, mode): | |
| 93 """the published sources in directory except index.md, newest first. | |
| 94 each entry has the file name, title, date as shown and text.""" | |
| 95 entries = [] | |
| 96 for source in sorted(directory.glob("*.md")): | |
| 97 if source.name == "index.md": | |
| 98 continue | |
| 99 where = source.relative_to(SRC).as_posix() | |
| 100 try: | |
| 101 headers, _ = parse_header_block( | |
| 102 source.read_text(encoding="utf-8"), where) | |
| 103 except BuildError as failure: | |
| 104 warn(f"{failure}, not listed") | |
| 105 continue | |
| 106 if headers.get("is_published", "").strip() != "1": | |
| 107 continue | |
| 108 if not headers.get("title"): | |
| 109 warn(f"{where}: missing title, not listed") | |
| 110 continue | |
| 111 | |
| 112 value = headers.get(mode, "") | |
| 113 key = sort_key(value, mode) | |
| 114 if key is None: | |
| 115 warn(f"{where}: no valid {mode}, listed last") | |
| 116 shown = value | |
| 117 if mode == "created_at" and key is not None: | |
| 118 shown = key.strftime("%d.%m.%Y") | |
| 119 | |
| 120 text = headers.get("subtitle") or headers.get("description") or "" | |
| 121 if not text: | |
| 122 warn(f"{where}: no subtitle or description") | |
| 123 | |
| 124 entries.append({ | |
| 125 "file": source.name, | |
| 126 "title": headers["title"], | |
| 127 "date": shown, | |
| 128 "text": text, | |
| 129 "key": key, | |
| 130 "updated": sort_key(headers.get("updated_at", ""), "created_at"), | |
| 131 "mtime": source.stat().st_mtime, | |
| 132 }) | |
| 133 | |
| 134 # by title, then newest first by date, updated_at and modification time; | |
| 135 # entries without a date or updated_at go last among their equals | |
| 136 entries.sort(key=lambda e: e["title"]) | |
| 137 entries.sort(key=lambda e: (e["key"] is not None, e["key"] or 0, | |
| 138 e["updated"] is not None, e["updated"] or 0, | |
| 139 e["mtime"]), | |
| 140 reverse=True) | |
| 141 return entries | |
| 142 | |
| 143 | |
| 144 def render(entries, prefix=""): | |
| 145 """entries as definition list lines, separated by blank lines. prefix is | |
| 146 put before each link target.""" | |
| 147 lines = [] | |
| 148 for entry in entries: | |
| 149 if lines: | |
| 150 lines.append("") | |
| 151 link = f"[{entry['title']}]({prefix}{entry['file']})" | |
| 152 lines.append(f"{link} {entry['date']}" if entry["date"] else link) | |
| 153 if entry["text"]: | |
| 154 lines.append(": " + entry["text"]) | |
| 155 return lines | |
| 156 | |
| 157 | |
| 158 def set_updated(lines, stamp): | |
| 159 """set the updated_at header to stamp, dropping folded continuations of | |
| 160 the old value. without updated_at, add it as the last header.""" | |
| 161 end = header_end(lines) | |
| 162 for i in range(end): | |
| 163 if re.match(r"updated_at[ \t]*:", lines[i]): | |
| 164 j = i + 1 | |
| 165 while j < end and lines[j][:1] in (" ", "\t"): | |
| 166 j += 1 | |
| 167 lines[i:j] = ["updated_at: " + stamp] | |
| 168 return | |
| 169 lines.insert(end, "updated_at: " + stamp) | |
| 170 | |
| 171 | |
| 172 def save(path, old, new, dry_run): | |
| 173 """write new lines to path if they differ from old, with updated_at set | |
| 174 to today. a dry run prints the difference instead. returns whether the | |
| 175 file differs.""" | |
| 176 if new == old: | |
| 177 return False | |
| 178 set_updated(new, datetime.date.today().isoformat()) | |
| 179 where = path.relative_to(SRC.parent).as_posix() | |
| 180 if dry_run: | |
| 181 for line in difflib.unified_diff(old, new, where, where, lineterm=""): | |
| 182 print(line) | |
| 183 else: | |
| 184 path.write_text("\n".join(new), encoding="utf-8") | |
| 185 print(f"{where}: updated") | |
| 186 return True | |
| 187 | |
| 188 | |
| 189 def read_index(path): | |
| 190 """the lines of an index and the index of its first body line, or None | |
| 191 if it has no valid header block with a title.""" | |
| 192 where = path.relative_to(SRC).as_posix() | |
| 193 text = path.read_text(encoding="utf-8") | |
| 194 try: | |
| 195 headers, _ = parse_header_block(text, where) | |
| 196 except BuildError as failure: | |
| 197 warn(f"{failure}, skipped") | |
| 198 return None | |
| 199 if not headers.get("title"): | |
| 200 warn(f"{where}: missing title, skipped") | |
| 201 return None | |
| 202 lines = text.split("\n") | |
| 203 return lines, header_end(lines) + 1 | |
| 204 | |
| 205 | |
| 206 def update_directory(index, dry_run): | |
| 207 """rewrite the entry list of a directory index. returns (changed, sorted | |
| 208 entries), or None if the index is skipped.""" | |
| 209 where = index.relative_to(SRC).as_posix() | |
| 210 read = read_index(index) | |
| 211 if read is None: | |
| 212 return None | |
| 213 old, body = read | |
| 214 | |
| 215 run = find_entries(old, body, len(old)) | |
| 216 if run is None: | |
| 217 warn(f"{where}: no entry list, skipped") | |
| 218 return None | |
| 219 first, stop, dates = run | |
| 220 | |
| 221 dates = [date for date in dates if date] | |
| 222 if not dates: | |
| 223 warn(f"{where}: no dates in the entry list, cannot tell created_at " | |
| 224 "from timeframe, skipped") | |
| 225 return None | |
| 226 mode = "created_at" if FULL_DATE.match(dates[0]) else "timeframe" | |
| 227 | |
| 228 entries = read_entries(index.parent, mode) | |
| 229 if not entries: | |
| 230 warn(f"{where}: no published sources, list left alone") | |
| 231 return None | |
| 232 | |
| 233 new = old[:first] + render(entries) + old[stop:] | |
| 234 return save(index, old, new, dry_run), entries | |
| 235 | |
| 236 | |
| 237 def parse_sections(spec): | |
| 238 """the index_sections setting as a list of (heading, directory) pairs. the | |
| 239 setting is a comma-separated list of <directory>:<heading> items.""" | |
| 240 sections = [] | |
| 241 for item in spec.split(","): | |
| 242 item = item.strip() | |
| 243 if not item: | |
| 244 continue | |
| 245 directory, _, heading = item.partition(":") | |
| 246 if not directory.strip() or not heading.strip(): | |
| 247 error(f"{CONFIG.name}: bad index section {item!r}") | |
| 248 sections.append((heading.strip(), directory.strip().strip("/"))) | |
| 249 return sections | |
| 250 | |
| 251 | |
| 252 def update_root(index, lists, sections, recent, dry_run): | |
| 253 """rewrite the sections of the root index from the sorted entries of the | |
| 254 directory indexes. sections is a list of (heading, directory) pairs, recent | |
| 255 the number of entries per section. returns whether the file changed, or | |
| 256 None if it is skipped.""" | |
| 257 read = read_index(index) | |
| 258 if read is None: | |
| 259 return None | |
| 260 old, body = read | |
| 261 new = list(old) | |
| 262 | |
| 263 for heading, directory in sections: | |
| 264 if directory not in lists: | |
| 265 warn(f"index.md: no entries for {directory}/, section " | |
| 266 f"{heading!r} left alone") | |
| 267 continue | |
| 268 | |
| 269 start = None | |
| 270 for i in range(body, len(new)): | |
| 271 match = HEADING.match(new[i]) | |
| 272 if match and match.group(1).lower() == heading.lower(): | |
| 273 start = i + 1 | |
| 274 break | |
| 275 if start is None: | |
| 276 warn(f"index.md: no section {heading!r}") | |
| 277 continue | |
| 278 end = start | |
| 279 while end < len(new) and not HEADING.match(new[end]): | |
| 280 end += 1 | |
| 281 | |
| 282 lines = render(lists[directory][:recent], directory + "/") | |
| 283 run = find_entries(new, start, end) | |
| 284 if run is None: | |
| 285 new[start:start] = [""] + lines | |
| 286 else: | |
| 287 first, stop, _ = run | |
| 288 new[first:stop] = lines | |
| 289 | |
| 290 return save(index, old, new, dry_run) | |
| 291 | |
| 292 | |
| 293 def main(argv): | |
| 294 parser = argparse.ArgumentParser( | |
| 295 description="rewrite the entry lists of the index pages in src/ from " | |
| 296 "the headers of the sources they list. a changed index " | |
| 297 "gets today's date as updated_at.") | |
| 298 parser.add_argument("-n", "--dry-run", action="store_true", | |
| 299 help="print the changes, write nothing") | |
| 300 args = parser.parse_args(argv) | |
| 301 | |
| 302 config = read_config() | |
| 303 sections = parse_sections(config["index_sections"]) | |
| 304 if not config["index_recent"].strip().isdigit(): | |
| 305 error(f"{CONFIG.name}: index_recent is not a number") | |
| 306 recent = int(config["index_recent"]) | |
| 307 | |
| 308 checked = 0 | |
| 309 changed = 0 | |
| 310 lists = {} | |
| 311 for index in sorted(SRC.rglob("index.md")): | |
| 312 if index.parent == SRC: | |
| 313 continue | |
| 314 checked += 1 | |
| 315 result = update_directory(index, args.dry_run) | |
| 316 if result is None: | |
| 317 continue | |
| 318 differs, entries = result | |
| 319 changed += differs | |
| 320 lists[index.parent.relative_to(SRC).as_posix()] = entries | |
| 321 | |
| 322 root = SRC / "index.md" | |
| 323 if sections and root.exists(): | |
| 324 checked += 1 | |
| 325 changed += bool(update_root(root, lists, sections, recent, | |
| 326 args.dry_run)) | |
| 327 elif sections: | |
| 328 warn("index.md: not found") | |
| 329 | |
| 330 if args.dry_run: | |
| 331 print(f"checked {checked} index files, {changed} would be modified") | |
| 332 else: | |
| 333 print(f"checked {checked} index files, modified {changed}") | |
| 334 return 0 | |
| 335 | |
| 336 | |
| 337 if __name__ == "__main__": | |
| 338 try: | |
| 339 sys.exit(main(sys.argv[1:])) | |
| 340 except BuildError as failure: | |
| 341 print("error: " + str(failure), file=sys.stderr) | |
| 342 sys.exit(1) |
