view 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
line wrap: on
line source

#!/usr/bin/env python3
"""rewrite the entry lists of the index pages in src/ from the headers of the
sources they list.

an index.md below src/ lists the published sources in its own directory. an
entry is a link line to a .md file, optionally followed by a date, then a
definition line with the subtitle, or the description if there is no
subtitle. the date in the existing entries decides which header is shown: a
full date (dd.mm.yyyy) means created_at, anything else means timeframe.
entries are sorted newest first, by created_at or by the start of the
timeframe, then by updated_at, then by file modification time, and finally by
title.

the root index.md has one section per entry in the index_sections setting of
config.txt, each listing the newest entries of a directory, as many as
index_recent says. a section runs from its heading to the next heading; text
around the entries, such as a "more" link, is kept. without index_sections the
root index.md is left alone.

a changed index gets today's date as updated_at."""

import argparse
import datetime
import difflib
import re
import sys

from make_site import (CONFIG, SRC, BuildError, error, parse_header_block,
                       read_config, warn)

# an entry starts with a link to a .md file and an optional date beginning
# with a digit. links to anything else, such as a directory, are not entries.
ENTRY = re.compile(r"\[[^\]]*\]\([^)\s]+\.md\)(?:[ \t]+(\d.*?))?[ \t]*$")
DEFINITION = re.compile(r":[ \t]")
CONTINUATION = re.compile(r"[ \t]+\S")
FULL_DATE = re.compile(r"\d{2}\.\d{2}\.\d{4}$")
# the start of a timeframe: mm.yyyy or yyyy
TIMEFRAME_START = re.compile(r"\s*(?:(\d{1,2})\.)?(\d{4})")
HEADING = re.compile(r"#+[ \t]+(.*?)[ \t]*$")


def header_end(lines):
    """the index of the blank line that ends the header block."""
    for i, line in enumerate(lines):
        if not line.strip():
            return i
    return len(lines)


def find_entries(lines, start, end):
    """the run of entries in lines[start:end] as (first line, line after the
    last entry, dates of the entries), or None when there is no entry. the
    run may contain other lines between entries; they are part of the run."""
    first = None
    stop = None
    dates = []
    i = start
    while i < end:
        match = ENTRY.match(lines[i])
        if not match:
            i += 1
            continue
        if first is None:
            first = i
        dates.append(match.group(1) or "")
        # the definition and its folded lines belong to the entry
        i += 1
        if i < end and DEFINITION.match(lines[i]):
            i += 1
            while i < end and CONTINUATION.match(lines[i]):
                i += 1
        stop = i
    if first is None:
        return None
    return first, stop, dates


def sort_key(value, mode):
    """a sortable form of a created_at or timeframe value, or None if the
    value is empty or not understood."""
    if mode == "created_at":
        try:
            return datetime.datetime.fromisoformat(value).date()
        except ValueError:
            return None
    match = TIMEFRAME_START.match(value)
    if not match:
        return None
    return int(match.group(2)), int(match.group(1) or 0)


def read_entries(directory, mode):
    """the published sources in directory except index.md, newest first.
    each entry has the file name, title, date as shown and text."""
    entries = []
    for source in sorted(directory.glob("*.md")):
        if source.name == "index.md":
            continue
        where = source.relative_to(SRC).as_posix()
        try:
            headers, _ = parse_header_block(
                source.read_text(encoding="utf-8"), where)
        except BuildError as failure:
            warn(f"{failure}, not listed")
            continue
        if headers.get("is_published", "").strip() != "1":
            continue
        if not headers.get("title"):
            warn(f"{where}: missing title, not listed")
            continue

        value = headers.get(mode, "")
        key = sort_key(value, mode)
        if key is None:
            warn(f"{where}: no valid {mode}, listed last")
        shown = value
        if mode == "created_at" and key is not None:
            shown = key.strftime("%d.%m.%Y")

        text = headers.get("subtitle") or headers.get("description") or ""
        if not text:
            warn(f"{where}: no subtitle or description")

        entries.append({
            "file": source.name,
            "title": headers["title"],
            "date": shown,
            "text": text,
            "key": key,
            "updated": sort_key(headers.get("updated_at", ""), "created_at"),
            "mtime": source.stat().st_mtime,
        })

    # by title, then newest first by date, updated_at and modification time;
    # entries without a date or updated_at go last among their equals
    entries.sort(key=lambda e: e["title"])
    entries.sort(key=lambda e: (e["key"] is not None, e["key"] or 0,
                                e["updated"] is not None, e["updated"] or 0,
                                e["mtime"]),
                 reverse=True)
    return entries


def render(entries, prefix=""):
    """entries as definition list lines, separated by blank lines. prefix is
    put before each link target."""
    lines = []
    for entry in entries:
        if lines:
            lines.append("")
        link = f"[{entry['title']}]({prefix}{entry['file']})"
        lines.append(f"{link} {entry['date']}" if entry["date"] else link)
        if entry["text"]:
            lines.append(":   " + entry["text"])
    return lines


def set_updated(lines, stamp):
    """set the updated_at header to stamp, dropping folded continuations of
    the old value. without updated_at, add it as the last header."""
    end = header_end(lines)
    for i in range(end):
        if re.match(r"updated_at[ \t]*:", lines[i]):
            j = i + 1
            while j < end and lines[j][:1] in (" ", "\t"):
                j += 1
            lines[i:j] = ["updated_at: " + stamp]
            return
    lines.insert(end, "updated_at: " + stamp)


def save(path, old, new, dry_run):
    """write new lines to path if they differ from old, with updated_at set
    to today. a dry run prints the difference instead. returns whether the
    file differs."""
    if new == old:
        return False
    set_updated(new, datetime.date.today().isoformat())
    where = path.relative_to(SRC.parent).as_posix()
    if dry_run:
        for line in difflib.unified_diff(old, new, where, where, lineterm=""):
            print(line)
    else:
        path.write_text("\n".join(new), encoding="utf-8")
        print(f"{where}: updated")
    return True


def read_index(path):
    """the lines of an index and the index of its first body line, or None
    if it has no valid header block with a title."""
    where = path.relative_to(SRC).as_posix()
    text = path.read_text(encoding="utf-8")
    try:
        headers, _ = parse_header_block(text, where)
    except BuildError as failure:
        warn(f"{failure}, skipped")
        return None
    if not headers.get("title"):
        warn(f"{where}: missing title, skipped")
        return None
    lines = text.split("\n")
    return lines, header_end(lines) + 1


def update_directory(index, dry_run):
    """rewrite the entry list of a directory index. returns (changed, sorted
    entries), or None if the index is skipped."""
    where = index.relative_to(SRC).as_posix()
    read = read_index(index)
    if read is None:
        return None
    old, body = read

    run = find_entries(old, body, len(old))
    if run is None:
        warn(f"{where}: no entry list, skipped")
        return None
    first, stop, dates = run

    dates = [date for date in dates if date]
    if not dates:
        warn(f"{where}: no dates in the entry list, cannot tell created_at "
             "from timeframe, skipped")
        return None
    mode = "created_at" if FULL_DATE.match(dates[0]) else "timeframe"

    entries = read_entries(index.parent, mode)
    if not entries:
        warn(f"{where}: no published sources, list left alone")
        return None

    new = old[:first] + render(entries) + old[stop:]
    return save(index, old, new, dry_run), entries


def parse_sections(spec):
    """the index_sections setting as a list of (heading, directory) pairs. the
    setting is a comma-separated list of <directory>:<heading> items."""
    sections = []
    for item in spec.split(","):
        item = item.strip()
        if not item:
            continue
        directory, _, heading = item.partition(":")
        if not directory.strip() or not heading.strip():
            error(f"{CONFIG.name}: bad index section {item!r}")
        sections.append((heading.strip(), directory.strip().strip("/")))
    return sections


def update_root(index, lists, sections, recent, dry_run):
    """rewrite the sections of the root index from the sorted entries of the
    directory indexes. sections is a list of (heading, directory) pairs, recent
    the number of entries per section. returns whether the file changed, or
    None if it is skipped."""
    read = read_index(index)
    if read is None:
        return None
    old, body = read
    new = list(old)

    for heading, directory in sections:
        if directory not in lists:
            warn(f"index.md: no entries for {directory}/, section "
                 f"{heading!r} left alone")
            continue

        start = None
        for i in range(body, len(new)):
            match = HEADING.match(new[i])
            if match and match.group(1).lower() == heading.lower():
                start = i + 1
                break
        if start is None:
            warn(f"index.md: no section {heading!r}")
            continue
        end = start
        while end < len(new) and not HEADING.match(new[end]):
            end += 1

        lines = render(lists[directory][:recent], directory + "/")
        run = find_entries(new, start, end)
        if run is None:
            new[start:start] = [""] + lines
        else:
            first, stop, _ = run
            new[first:stop] = lines

    return save(index, old, new, dry_run)


def main(argv):
    parser = argparse.ArgumentParser(
        description="rewrite the entry lists of the index pages in src/ from "
                    "the headers of the sources they list. a changed index "
                    "gets today's date as updated_at.")
    parser.add_argument("-n", "--dry-run", action="store_true",
                        help="print the changes, write nothing")
    args = parser.parse_args(argv)

    config = read_config()
    sections = parse_sections(config["index_sections"])
    if not config["index_recent"].strip().isdigit():
        error(f"{CONFIG.name}: index_recent is not a number")
    recent = int(config["index_recent"])

    checked = 0
    changed = 0
    lists = {}
    for index in sorted(SRC.rglob("index.md")):
        if index.parent == SRC:
            continue
        checked += 1
        result = update_directory(index, args.dry_run)
        if result is None:
            continue
        differs, entries = result
        changed += differs
        lists[index.parent.relative_to(SRC).as_posix()] = entries

    root = SRC / "index.md"
    if sections and root.exists():
        checked += 1
        changed += bool(update_root(root, lists, sections, recent,
                                    args.dry_run))
    elif sections:
        warn("index.md: not found")

    if args.dry_run:
        print(f"checked {checked} index files, {changed} would be modified")
    else:
        print(f"checked {checked} index files, modified {changed}")
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except BuildError as failure:
        print("error: " + str(failure), file=sys.stderr)
        sys.exit(1)