#!/usr/bin/env python3
# $Id: verify-scope 274 2026-10-21 09:35:59Z peter $
#
# Copyright (C) 2026 Péter Felecan
# Assisted by Claude Sonnet 5.5 (Anthropic)
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

"""verify-scope -- which verification does this release need?

ADDED 2026-10-16 (0.72.93). The full regression takes 35 to 60 minutes per configuration, two configurations, and its slow phases exercise the library's code. A release that
changes only documents, the document toolchain or the lists of what is archived exercises none of that code again: rerunning it can only repeat the previous answer. What such
a release does need is a clean build of the documents, the archive with its name diff, and a CLEAN EXTRACTION (it rebuilds the generated files: 0.72.92 edited batch-init.el
instead of batch-init.el.in, and the archive build refused three .lol files, neither of which the regression would have found). This script decides, mechanically, which case a
tree is in. "We did not touch the core" is then a fact, not a belief.

THE BASELINE is the last release that passed the FULL regression in both configurations (not merely the last one delivered: a chain of small releases must not let code drift
unverified), written as a manifest, verified-baseline.txt: one hash per shipped file, one per check function of the test scripts, one per remainder of a test script (helpers,
imports, the lists of checks), one per region of Makefile.am. The set of shipped files is the one make-archive ships: `tar --exclude-from=.tar-exclude .`.

THE RULE. Tier A (documents build, archive and its name diff, clean extraction, and the checks this script lists) is enough when every change is in
  - documents (*.org, *.1, *.5) and the sources of their figures (fig-*.dot, fig-*.cmd), the document toolchain (batch-init.el.in, Preamble.tex, man2htmldoc, version.org.in), .tar-exclude, the release files (VERSION, ChangeLog, NEWS, README,
    AUTHORS, COPYING), the maintainer scripts (make-archive, verify-scope, make-figures, stale-files);
  - a test script, when only checks were ADDED or CHANGED (they run, and are listed) and nothing else in it changed;
  - Makefile.am, when only regions that name documents, manual pages, clean files or archive contents changed;
  - configure.ac, when only blocks that concern the document tools changed (the probes of emacs, lualatex, latexmk and groff, the INDEX link, their substitutions, the list of generated
    files): a block counts only if it mentions nothing the regression depends on (python, bash, kicad, make, the package and automake initialisation).
Anything else is Tier B, the full regression in both configurations: a code module, a tool, test data, a block of configure.ac that is not on that list, a region of Makefile.am that is not on the list
(above all the check phases: they decide WHAT the regression verifies), a removed check, a change to the helpers of a test script (they can affect every check), any other file added or removed.

USAGE
  verify-scope                         compare the tree with the baseline; exit 0 when Tier A is enough, 1 when Tier B is required, 2 on an error
  verify-scope --update-baseline       write the baseline from the tree: run it right after a release passed the FULL regression
  verify-scope --update-baseline --from-archive ARCHIVE
                                       write it from a delivered archive (to start from a release that was fully verified earlier)
  verify-scope --root DIR              work on another tree (the tests do)
  verify-scope --baseline FILE         another baseline file
"""

import argparse
import ast
import hashlib
import os
import re
import subprocess
import sys
import tarfile

BASELINE = "verified-baseline.txt"
RELEASE_FILES = {"VERSION", "ChangeLog", "NEWS", "README", "AUTHORS", "COPYING"}
DOC_TOOLCHAIN = {"batch-init.el.in", "Preamble.tex", "man2htmldoc", "version.org.in"}
ARCHIVE_LISTS = {".tar-exclude"}
# what make-archive adds to an archive and a tree does not ship (.tar-exclude lists it): the reader of an archive leaves it out as the reader of a tree does (0.72.117)
ARCHIVE_ADDED = {"MANIFEST"}
MAINTAINER_TOOLS = {"make-archive", "verify-scope", "make-figures", "stale-files"}
DOCUMENT = re.compile(r"\.(org|1|5)$")
TEST_SCRIPT = re.compile(r"^pptest_[a-z_]+$")
# the regions of Makefile.am whose change cannot change what the regression verifies: the lists of documents, manual pages, clean files and archive contents, and the rules that build the documents
MAKE_ALLOWED = {"ORG_DOCS", "dist_doc_DATA", "EXTRA_DIST", "CLEANFILES", "MAINTAINERCLEANFILES", "MAN_PAGES", "MAN5_PAGES", "MAN_HTML", "PDF_DOCS", "HTML_DOCS", "BATCH_INIT", "ORGDOC_ENV",
                "SUFFIXES", "pdf-local", "html-local", "Index.html", "$(PDF_DOCS)", ".org.pdf", ".1.html", "man-html", "breadboard_config.5.html", "PACKPAY_VERSION", "HTML_EXPORT_ARCHIVE",
                "HTML_EXPORT_FILES", "html-export", "$(HTML_EXPORT_ARCHIVE)", "html-export-clean", "FIGURE_SRCS", "FIGURE_NAMES", "FIGURE_SVGS", "FIGURE_PDFS", "FIGURES", "fig-%.svg", "fig-%.pdf", "figures", "stale", "stale-warn"}
CONF_DOC_KEY = re.compile(r"^(AC_CHECK_PROGS:(EMACS|LUALATEX|LATEXMK|GROFF|DOT)|AC_SUBST:(EMACS|LUALATEX|LATEXMK|GROFF|ORGDOC_PDF_PROCESS_KIND)|AC_ARG_VAR:INDEX|AS_IF(:.*)?|AC_MSG_CHECKING(:.*)?|AC_CONFIG_FILES(:.*)?|AC_OUTPUT)(#\d+)?$")
CONF_DOC_WORDS = re.compile(r"EMACS|LUALATEX|LATEXMK|GROFF|DOT|CAIROSVG|ORGDOC|INDEX|version\.org|batch-init|AC_OUTPUT")
CONF_DANGER = re.compile(r"PYTHON3|BASH|KICAD|kicad|GNU make|gnu_make|AM_INIT|AC_INIT|AC_PROG|AC_PATH_PROG|MAKE")
REGION_HEAD = re.compile(r"^([A-Za-z_.$][^\s=:#]*(?:\([^)]*\)[^\s=:#]*)*)\s*(?:\+=|:=|::=|=|::|:)")


def sha1(data):
    return hashlib.sha1(data if isinstance(data, bytes) else data.encode("utf-8")).hexdigest()


def shipped_names(root):
    """The files make-archive ships: the members of `tar --exclude-from=.tar-exclude .`."""
    proc = subprocess.Popen(["tar", "cf", "-", "--exclude-from=.tar-exclude", "."], cwd=root, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
    names = []
    with tarfile.open(fileobj=proc.stdout, mode="r|") as tar:
        for m in tar:
            if m.isfile():
                names.append(m.name[2:] if m.name.startswith("./") else m.name)
    proc.wait()
    return sorted(names)


def check_hashes(text):
    """({check name: hash of its source}, hash of everything else), for a Python test script: the else being the helpers, the imports and the lists of checks with the entries of the checks left out."""
    tree = ast.parse(text)
    segments, spans = {}, []
    for node in tree.body:
        if isinstance(node, ast.FunctionDef) and node.name.startswith("check_"):
            segments[node.name] = ast.get_source_segment(text, node)
            spans.append((node.lineno, node.end_lineno))
    keep = []
    for i, line in enumerate(text.split("\n"), 1):
        if any(a <= i <= b for a, b in spans):
            continue
        if re.match(r'^\s+"check_\w+"(?::\s*\d+(?:\.\d+)?)?,\s*$', line):
            continue
        keep.append(line.rstrip())
    rest = re.sub(r"\n{3,}", "\n\n", "\n".join(keep)).strip()
    return {name: sha1(seg) for name, seg in segments.items()}, sha1(rest)


def makefile_regions(text):
    """{region name: hash}: a region is a variable assignment or a rule, from its first line to the line before the next one; a name that repeats gets #2, #3."""
    regions, name, buf, previous_continues = {}, "(preamble)", [], False
    seen = {}

    def close():
        if buf:
            key = name
            seen[key] = seen.get(key, 0) + 1
            if seen[key] > 1:
                key = f"{key}#{seen[key]}"
            regions[key] = sha1("\n".join(buf))
    for line in text.split("\n"):
        m = REGION_HEAD.match(line) if (line and line[0] not in " \t#" and not previous_continues) else None
        if m:
            close()
            name, buf = m.group(1), []
        buf.append(line)
        previous_continues = line.rstrip().endswith("\\")
    close()
    return regions


def configure_blocks(text):
    """The blocks of configure.ac as [(hash, base key, safe)]: a block is a run of lines between blank lines, keyed by its first line that is not a comment (the macro and its first argument: AC_CHECK_PROGS:EMACS).
    A block is SAFE when its key is one of the document tools' and its text names a document tool and nothing the regression depends on. Blocks are compared by CONTENT, not by position or by a number: a block that is still there is
    unchanged, whatever was inserted before it (an earlier scheme numbered the blocks that share a key, and a new block shifted the numbers of the KiCad probes after it: a Tier B for nothing)."""
    blocks, cur = [], []
    for line in text.split("\n"):
        if line.strip() == "":
            if cur:
                blocks.append(cur)
                cur = []
        else:
            cur.append(line)
    if cur:
        blocks.append(cur)
    out = []
    for b in blocks:
        first = next((ln for ln in b if not ln.lstrip().startswith(("#", "dnl"))), None)
        if first is None:
            key = "(comments)"
        else:
            m = re.match(r"\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?:\(\s*\[?([A-Za-z0-9_.$-]*))?", first)
            key = m.group(1) + (":" + m.group(2) if m.group(2) else "")
        body = "\n".join(b)
        safe = key.startswith("(comments)") or bool(CONF_DOC_KEY.match(key) and CONF_DOC_WORDS.search(body) and not CONF_DANGER.search(body))
        out.append((sha1(body), key, safe))
    return out


def scan(read, names):
    """The manifest of a set of shipped files: read(name) gives the bytes of a file."""
    state = {"files": {}, "checks": {}, "rest": {}, "regions": {}, "cblocks": []}
    for n in names:
        if n == BASELINE:
            continue
        data = read(n)
        state["files"][n] = sha1(data)
        if TEST_SCRIPT.match(n):
            try:
                checks, rest = check_hashes(data.decode("utf-8"))
            except (SyntaxError, UnicodeDecodeError):
                continue
            for c, h in checks.items():
                state["checks"][f"{n}::{c}"] = h
            state["rest"][n] = rest
        elif n == "Makefile.am":
            for r, h in makefile_regions(data.decode("utf-8")).items():
                state["regions"][f"{n}::{r}"] = h
        elif n == "configure.ac":
            state["cblocks"] = configure_blocks(data.decode("utf-8"))
    return state


def scan_tree(root):
    return scan(lambda n: open(os.path.join(root, n), "rb").read(), shipped_names(root))


def scan_archive(path):
    with tarfile.open(path) as tar:
        members = {(m.name[2:] if m.name.startswith("./") else m.name): m for m in tar if m.isfile()}
        for n in ARCHIVE_ADDED:
            members.pop(n, None)
        return scan(lambda n: tar.extractfile(members[n]).read(), sorted(members))


def release_of(version_text):
    lines = version_text.split("\n")
    return lines[1].strip() if len(lines) > 1 else "?"


def write_baseline(path, release, state):
    out = [f"# {BASELINE} -- written by verify-scope --update-baseline; the manifest of the last release that passed the FULL regression in both configurations.",
           "# One hash per shipped file, per check function, per remainder of a test script and per region of Makefile.am. See verify-scope for the rule.", f"release {release}"]
    for kind, key in (("file", "files"), ("check", "checks"), ("rest", "rest"), ("region", "regions")):
        for n in sorted(state[key]):
            out.append(f"{kind} {state[key][n]} {n}")
    for h, key, safe in state["cblocks"]:
        out.append(f"cblock {h} {'safe' if safe else 'unsafe'} {key}")
    with open(path, "w", encoding="utf-8") as f:
        f.write("\n".join(out) + "\n")


def read_baseline(path):
    state = {"files": {}, "checks": {}, "rest": {}, "regions": {}, "cblocks": []}
    release = "?"
    for line in open(path, encoding="utf-8"):
        line = line.rstrip("\n")
        if not line or line.startswith("#"):
            continue
        kind, rest = line.split(" ", 1)
        if kind == "release":
            release = rest
            continue
        if kind == "cblock":
            h, flag, key = rest.split(" ", 2)
            state["cblocks"].append((h, key, flag == "safe"))
            continue
        h, n = rest.split(" ", 1)
        state[{"file": "files", "check": "checks", "rest": "rest", "region": "regions"}[kind]][n] = h
    return release, state


def classify(path):
    if path in RELEASE_FILES:
        return "release file"
    if DOCUMENT.search(path):
        return "document"
    if re.match(r"fig-[\w-]+\.(dot|cmd)$", path):
        return "figure"
    if path in DOC_TOOLCHAIN:
        return "document toolchain"
    if path in ARCHIVE_LISTS:
        return "archive list"
    if path in MAINTAINER_TOOLS:
        return "maintainer script"
    if TEST_SCRIPT.match(path):
        return "test script"
    if path in ("Makefile.am", "configure.ac"):
        return "build file, by region"
    return "code, data or build"


def decide(old, new):
    """(verdict, reasons, report lines, the checks to run) for the change from the baseline state `old` to the state `new`."""
    reasons, report, classes = [], [], {}
    for n in sorted(set(old["files"]) | set(new["files"])):
        a, b = old["files"].get(n), new["files"].get(n)
        if a == b:
            continue
        change = "added" if a is None else "removed" if b is None else "changed"
        cls = classify(n)
        classes.setdefault(cls, []).append(f"{n} ({change})")
        if cls == "code, data or build":
            reasons.append(f"{n} ({change}) is code, data or build input")
        elif cls == "test script":
            if change == "removed":
                reasons.append(f"{n} was removed")
            elif old["rest"].get(n) != new["rest"].get(n) and a is not None:
                reasons.append(f"{n}: something other than the checks changed (helpers, imports, module code): it can affect every check")
        elif cls == "build file, by region":
            if change != "changed":
                reasons.append(f"{n} was {change}")
    # the checks
    to_run = []
    new_checks = sorted(k for k in new["checks"] if k not in old["checks"])
    changed_checks = sorted(k for k in new["checks"] if k in old["checks"] and old["checks"][k] != new["checks"][k])
    removed_checks = sorted(k for k in old["checks"] if k not in new["checks"])
    for k in removed_checks:
        reasons.append(f"the check {k} was removed")
    to_run += [k.split("::")[1] for k in new_checks + changed_checks if k.split("::")[0] == "pptest_regression"]
    # the Makefile.am regions
    regions = sorted(set(old["regions"]) | set(new["regions"]))
    changed_regions = [r for r in regions if old["regions"].get(r) != new["regions"].get(r)]
    cblocks_changed = sorted(h for h, _, _ in new["cblocks"]) != sorted(h for h, _, _ in old["cblocks"])
    for r in changed_regions:
        fname, head = r.split("::", 1)
        if fname == "Makefile.am" and re.sub(r"#\d+$", "", head) not in MAKE_ALLOWED:
            reasons.append(f"Makefile.am: the region {head!r} is not on the list of regions that cannot change what the regression verifies (the check phases above all)")
    # configure.ac: the blocks that are new, and those that are gone (compared by content; a changed block is a gone one and a new one)
    old_left = list(old["cblocks"])
    for h, key, safe in new["cblocks"]:
        hit = next((i for i, o in enumerate(old_left) if o[0] == h), None)
        if hit is not None:
            old_left.pop(hit)
        elif not safe:
            reasons.append(f"configure.ac: the block {key!r} is new or changed and is not one that concerns only the document tools (or it names something the regression depends on)")
    for h, key, safe in old_left:
        if not safe:
            reasons.append(f"configure.ac: the block {key!r} was removed or changed, and it was not one of the document tools'")
    for cls in sorted(classes):
        report.append(f"  {cls:20s} {', '.join(classes[cls])}")
    if new_checks or changed_checks or removed_checks:
        report.append(f"  checks               new: {[k.split('::')[1] for k in new_checks]}; changed: {[k.split('::')[1] for k in changed_checks]}; removed: {[k.split('::')[1] for k in removed_checks]}")
    if changed_regions:
        report.append(f"  build file regions   {[r for r in changed_regions]}")
    if cblocks_changed:
        report.append("  configure.ac blocks  " + str(sorted({k for h, k, _ in new["cblocks"] if h not in {o[0] for o in old["cblocks"]}})) + " new or changed")
    return ("A" if not reasons else "B"), reasons, report, sorted(set(to_run)), (new_checks + changed_checks)


def checks_naming(root, names):
    """The checks of pptest_regression that READ one of the changed files: the file's name is a string constant of its own in the check (read("Concept.org"), a list of document names, a path whose last part is the name). A name inside a longer text, in a docstring or a message, is a citation, not a read."""
    path = os.path.join(root, "pptest_regression")
    if not os.path.exists(path):
        return []
    text = open(path, encoding="utf-8").read()
    tree = ast.parse(text)
    wanted = {os.path.basename(n) for n in names}
    found = []
    for node in tree.body:
        if isinstance(node, ast.FunctionDef) and node.name.startswith("check_"):
            doc = ast.get_docstring(node, clean=False)
            consts = {os.path.basename(c.value) for c in ast.walk(node) if isinstance(c, ast.Constant) and isinstance(c.value, str) and c.value != doc and c.value.strip() == c.value and " " not in c.value and "\n" not in c.value}
            if wanted & consts:
                found.append(node.name)
    return found


def main():
    ap = argparse.ArgumentParser(prog="verify-scope", description="Decide which verification a release needs: Tier A (documents build, archive, clean extraction, listed checks) or Tier B (the full regression).")
    ap.add_argument("--root", default=os.path.dirname(os.path.abspath(__file__)))
    ap.add_argument("--baseline", default=None)
    ap.add_argument("--update-baseline", action="store_true", help="write the baseline from the tree (or from --from-archive); run it right after a FULL regression passed")
    ap.add_argument("--from-archive", default=None)
    args = ap.parse_args()
    root = os.path.abspath(args.root)
    base_path = args.baseline or os.path.join(root, BASELINE)
    try:
        if args.update_baseline:
            if args.from_archive:
                with tarfile.open(args.from_archive) as tar:
                    release = release_of(tar.extractfile("./VERSION").read().decode("utf-8"))
                state = scan_archive(args.from_archive)
            else:
                release = release_of(open(os.path.join(root, "VERSION"), encoding="utf-8").read())
                state = scan_tree(root)
            write_baseline(base_path, release, state)
            print(f"verify-scope: wrote {os.path.basename(base_path)} for release {release}: {len(state['files'])} files, {len(state['checks'])} checks, {len(state['regions'])} regions")
            return 0
        release, old = read_baseline(base_path)
        new = scan_tree(root)
    except (OSError, ValueError, KeyError) as e:
        print(f"verify-scope: {e}", file=sys.stderr)
        return 2
    verdict, reasons, report, to_run, _ = decide(old, new)
    version = release_of(open(os.path.join(root, "VERSION"), encoding="utf-8").read()) if os.path.exists(os.path.join(root, "VERSION")) else "?"
    changed = [n for n in sorted(set(old["files"]) | set(new["files"])) if old["files"].get(n) != new["files"].get(n)]
    print(f"verify-scope: baseline {release} (the last release verified in full) against the tree {version}: {len(changed)} files differ")
    for line in report:
        print(line)
    if verdict == "A":
        names = [n for n in changed if classify(n) in ("document", "figure", "document toolchain", "archive list", "maintainer script", "build file, by region")]
        to_run = sorted(set(to_run) | set(checks_naming(root, names)))
        print("VERDICT: Tier A is enough. Run: the strict build of the documents from a clean tree, make-archive and its name diff against the baseline release, a clean extraction (bootstrap, configure, and look at the generated files),")
        print("         and the checks below (make check1 check2 check3 are cheap and worth adding).")
        if to_run:
            print("         python3 pptest_regression --only " + ",".join(to_run))
        return 0
    print("VERDICT: Tier B is required: the full regression in both configurations, because")
    for r in reasons:
        print(f"  - {r}")
    print("         After it passes: verify-scope --update-baseline")
    return 1


if __name__ == "__main__":
    sys.exit(main())

# Local Variables:
# mode: python
# End:
