#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Read the family's manifests and report what has not reached whom. python3 lineage.py # the report, to stdout python3 lineage.py --out report.md python3 lineage.py --for play-md # one project and everything it comes from python3 lineage.py --online # and ask GitHub how far each outside reference has moved Standard library only (Python 3.11+ for ``tomllib``). It reads each project's manifest in ``projects/`` and that project's local clone (``local``, relative to this file), and never fetches: run ``git fetch`` in the clones first for an up-to-date answer. Three kinds of edge (README.md): - **depends** -- built on another project at a pin. The pin is read from the file the dependent declares it in (``declared_in``), never copied into the manifest: a git revision (``name @ git+...@REV`` in pyproject.toml, ``git = ".../name", rev = "REV"`` or ``tag = "T"`` in Cargo.toml), a version (``name>=X``, ``name==X``), or, for a file of no standard shape such as a fetch script or a README, whatever the edge's ``pattern`` (a regex with one group) finds. ``relation`` says what the pin means: ``pins`` (a dependency, the default), ``transcribes`` (a port to another language, from the reference at that commit) or ``forks`` (a speed fork, synced to upstream at that commit). A ``forks`` edge with no ``declared_in`` shares upstream's history and takes it by merging, so what it lacks is upstream's commits outside its own history. An edge's ``settled`` table names upstream commits that are not owed (the short hash, and why: where it was carried by hand, or why it does not apply); they are counted, not listed. The report lists the upstream commits the pin does not have; for a floor, the upstream commits since its newest release (``released``), what a user of the release lacks; for ``==X``, the commits since the tag ``vX``. Which of them are fixes is for a reader to judge: subjects do not say reliably. - **copied** -- a file taken or adapted from a sibling. The report lists the source's commits since the copy was made (its first commit in the dependent), and the notes on what the copy does differently (``diverged``) or still shares (``shared``). - **evidence** -- what a project is certified against; listed, not checked. And the outside world: **reference** edges name the outside repositories a project is judged against or reads (MAME, Nuked-*, SingleStepTests, other emulators), each at the revision the project pins, read from the file that pins it: a ``pinned_repos.json`` list as the boards keep it, or a ``pattern`` over a fetch script (named groups ``url`` and ``rev``, or one group for the revision with ``url`` on the edge; ``rev_format`` turns a captured version into a tag, as ``mame0{}`` does for MAME's). The report always lists them, grouped by repository, so two projects on different revisions of the same reference show. Only with ``--online`` does it ask GitHub (the REST API, with ``GITHUB_TOKEN``/``GH_TOKEN`` or ``gh auth token`` if present) how many commits each reference has gained since the pin and what its newest release is: the one part of the report that goes online, and the only way to learn that the state of the art has moved. """ from __future__ import annotations import argparse import json import os import re import shutil import subprocess import sys import tomllib import urllib.error import urllib.request from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from datetime import date from pathlib import Path HERE = Path(__file__).resolve().parent @dataclass class Project: name: str data: dict @property def clone(self) -> Path: return (HERE / self.data["local"]).resolve() @property def branch(self) -> str: return self.data.get("branch", "main") def load(folder: Path) -> dict[str, Project]: projects = {} for path in sorted(folder.glob("*.toml")): data = tomllib.loads(path.read_text(encoding="utf-8")) projects[data["name"]] = Project(data["name"], data) return projects def git(clone: Path, *args: str) -> str: result = subprocess.run(["git", "-C", str(clone), *args], capture_output=True, text=True) if result.returncode: raise RuntimeError(f"git {' '.join(args)} in {clone}: {result.stderr.strip()}") return result.stdout.strip() def tip(project: Project) -> str: """The branch to compare against: the remote-tracking one if the clone has it.""" for ref in (f"origin/{project.branch}", project.branch): try: git(project.clone, "rev-parse", "--verify", "--quiet", ref) return ref except RuntimeError: continue raise RuntimeError(f"{project.name}: no branch {project.branch}") def commits(project: Project, since: str, path: str | None = None) -> list[str]: """``hash subject`` lines of ``since..tip`` (``since`` a revision, or ``--since=DATE``), oldest first.""" args = ["log", "--reverse", "--no-merges", "--format=%h %s"] if since.startswith("--since="): args += [since, tip(project)] else: args.append(f"{since}..{tip(project)}") if path: args += ["--", path] out = git(project.clone, *args) return out.splitlines() if out else [] def declared_pin(dependent: Project, upstream: str, dep: dict) -> tuple[str, str]: """(``git``, revision), (``floor``, version) or (``exact``, version), read from the dependent's file.""" declared_in = dep["declared_in"] path = dependent.clone / declared_in if not path.exists(): # renamed or removed in the dependent: reported as stale, not a crash raise RuntimeError(f"{dependent.name}: no {declared_in}") text = path.read_text(encoding="utf-8") if dep.get("pattern"): found = re.search(dep["pattern"], text) if found: return "git", found.group(1) raise RuntimeError(f"{dependent.name}: {dep['pattern']!r} not found in {declared_in}") git_pin = re.search(rf'"{re.escape(upstream)}\s*@\s*git\+[^"@]+@([0-9a-f]{{7,40}})"', text) if git_pin: return "git", git_pin.group(1) # Cargo.toml: { git = "https://.../upstream", rev = "..." } or tag = "...", on one line. cargo = re.search(rf'git\s*=\s*"[^"]*/{re.escape(upstream)}(?:\.git)?"[^}}\n]*\b(?:rev|tag)\s*=\s*"([^"]+)"', text) if cargo: return "git", cargo.group(1) floor = re.search(rf'"{re.escape(upstream)}\s*(>=|==)\s*([0-9][^",;\s]*)', text) if floor: return ("floor" if floor.group(1) == ">=" else "exact"), floor.group(2) raise RuntimeError(f"{dependent.name}: no pin for {upstream} in {declared_in}") def resolve(project: Project, rev: str) -> str | None: """The full hash of a revision or tag in the project's clone, or None.""" try: return git(project.clone, "rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}") except RuntimeError: return None def outside_history(fork: Project, upstream: Project) -> list[str]: """Upstream's commits that are not in the fork's history: what a fork that takes upstream by merging has not merged. Read from both clones; nothing is fetched.""" have = set(git(fork.clone, "rev-list", tip(fork)).split()) out = git(upstream.clone, "log", "--reverse", "--no-merges", "--format=%H %h %s", tip(upstream)) return [line.split(" ", 1)[1] for line in out.splitlines() if line.split(" ", 1)[0] not in have] def upstream_of(projects: dict[str, Project], name: str) -> dict[str, Project]: """The project and every project it pins, transcribes or forks, transitively, in manifest order. Copies are not followed: a script taken from a sibling does not put the sibling's code in the project.""" keep, todo = set(), [name] while todo: n = todo.pop() if n in keep or n not in projects: continue keep.add(n) d = projects[n].data todo += [e["on"] for e in d.get("depends", [])] return {n: p for n, p in projects.items() if n in keep} def report(projects: dict[str, Project], shown: dict[str, Project] | None = None, online: bool = False) -> str: """The report on ``shown`` (default: all), looking edges up in ``projects``.""" family, projects = projects, shown or projects out = ["# The family: what has not reached whom", ""] out += ["| project | kind | role | language | visibility | status | at |", "| --- | --- | --- | --- | --- | --- | --- |"] # fmt: skip for p in projects.values(): d = p.data try: at = git(p.clone, "rev-parse", "--short", tip(p)) except RuntimeError: at = "no local clone" # renamed, moved or removed: the row says so, the report goes on out.append(f"| {p.name} | {d['kind']} | {d['role']} | {d['language']} | " f"{d['visibility']} | {d.get('status', 'built')} | `{at}` |") # fmt: skip out += ["", "## Dependencies behind their upstream", ""] found = False for p in projects.values(): for dep in p.data.get("depends", []): upstream = family.get(dep["on"]) relation = dep.get("relation", "pins") if upstream is None: out.append(f"- {p.name} -> {dep['on']}: not in the family's manifests") continue try: note = "" if relation == "forks" and not dep.get("declared_in"): behind = outside_history(p, upstream) label = "forks, merging upstream" else: kind, value = declared_pin(p, dep["on"], dep) if kind == "git": full = resolve(upstream, value) if full is None: out.append(f"- {p.name} -> {upstream.name} ({relation} `{value}`): " f"not in {upstream.name}'s clone; fetch it") # fmt: skip continue behind = commits(upstream, full) label = f"{relation} `{value[:7]}`" if re.fullmatch(r"[0-9a-f]{7,40}", value) else f"{relation} `{value}` = `{full[:7]}`" try: git(upstream.clone, "merge-base", "--is-ancestor", full, tip(upstream)) except RuntimeError: note = f" -- the pin is not on {upstream.name}'s {upstream.branch}" elif kind == "exact": tag = f"v{value}" if resolve(upstream, tag) is None: out.append(f"- {p.name} -> {upstream.name} == {value}: no tag {tag}") continue behind = commits(upstream, tag) label = f"{relation} == {value}, and upstream since `{tag}`" else: release = upstream.data.get("released") if release is None: out.append(f"- {p.name} -> {upstream.name} >= {value}: no release recorded") continue behind = commits(upstream, release) label = f"needs >= {value}; newest release `{release}`, and upstream since it" except RuntimeError as error: # a pin the manifest names but the file no longer declares, or a clone that # is gone: the edge is reported as stale and the report goes on out.append(f"- {p.name} -> {dep['on']}: {error} (the manifest may be out of date)") continue # ``settled``: upstream commits that are not owed, each with why -- carried # by hand (a fork that took a fix in its own form) or not applicable. settled = dep.get("settled", {}) done = [line for line in behind if any(line.startswith(h[:7]) for h in settled)] behind = [line for line in behind if line not in done] if done: note += f" ({len(done)} more settled: carried by hand or not applicable)" if behind: found = True out.append(f"### {p.name} -> {upstream.name} ({label}): {len(behind)} commits{note}") if dep.get("why"): out.append(f"_{dep['why']}_") out += [f"- {line}" for line in behind] + [""] else: out.append(f"- {p.name} -> {upstream.name} ({label}): up to date{note}") if not found: out.append("Nothing.") out += ["", "## Copies whose source has moved on", ""] for p in projects.values(): for copy in p.data.get("copied", []): source = family.get(copy["from"]) if source is None: out.append(f"- {p.name}/{copy['path']}: {copy['from']} is not in the family's manifests") continue # When the copy is a shape a project adopted into a file it already # had, the file's birth is the wrong date: `since` names the commit # that adopted it, and the source's movement is measured from there. if copy.get("since"): adopted = git(p.clone, "log", "-1", "--format=%cI", copy["since"]).strip() if not adopted: out.append(f"- {p.name}/{copy['path']}: no commit {copy['since']}") continue copied_at = adopted else: first = git(p.clone, "log", "--diff-filter=A", "--follow", "--format=%cI", "--", copy["path"]).splitlines() # fmt: skip if not first: out.append(f"- {p.name}/{copy['path']}: not in its history") continue copied_at = first[-1] try: moved = commits(source, f"--since={copied_at}", copy["from_path"]) except RuntimeError as error: # source clone gone, renamed or not yet committed out.append(f"- {p.name}/{copy['path']}: {error} (the manifest may be out of date)") continue head = (f"- **{p.name}/{copy['path']}** ({copy['how']} from " f"{source.name}/{copy['from_path']}, {copied_at[:10]}): ") # fmt: skip out.append(head + (f"{len(moved)} source commits since" if moved else "source unchanged since")) out += [f" - {line}" for line in moved] if copy.get("diverged"): out.append(f" - diverged, a candidate to flow back: {copy['diverged']}") if copy.get("shared"): out.append(f" - shared, to settle in both: {copy['shared']}") out += ["", "## Evidence recorded", ""] for p in projects.values(): for ev in p.data.get("evidence", []): out.append(f"- {p.name}: {ev['what']} ({ev['where']})") out += charter_section(projects, whole_family=shown is None) out += references_section(projects, online) return "\n".join(out) + "\n" def charter_section(projects: dict[str, Project], whole_family: bool) -> list[str]: """Drift from docs/charter.md: READMEs without the lineage line or the charter link, the installed CLAUDE.md against this repository's, and the open provenance items in docs/families.md (the last two on the whole family's report only).""" out = ["", "## The charter", ""] missing = [] for p in projects.values(): if p.data.get("status") == "planned": continue readme = p.clone / "README.md" if not p.clone.is_dir(): missing.append(f"{p.name} (no local clone)") continue if not readme.is_file(): missing.append(f"{p.name} (no README.md)") continue text = readme.read_text(encoding="utf-8", errors="replace") lacks = [what for what, ok in (("lineage line", "**Lineage:**" in text), ("charter link", "docs/charter.md" in text)) if not ok] # fmt: skip if lacks: missing.append(f"{p.name} ({', '.join(lacks)})") built = sum(p.data.get("status") != "planned" for p in projects.values()) out.append(f"READMEs that open with the lineage line and link the charter: " f"{built - len(missing)} of {built}.") # fmt: skip if missing: out += ["", "Missing:", ""] + [f"- {m}" for m in missing] # the licence contract (charter, licences points 1 and 2): a LICENSE file per repository unlicensed = [p.name for p in projects.values() if p.clone.is_dir() and not any(p.clone.glob("LICENSE*"))] # fmt: skip present = [p for p in projects.values() if p.clone.is_dir()] out += ["", f"Repositories with a LICENSE file: {len(present) - len(unlicensed)} of " f"{len(present)}" + (f" (missing: {', '.join(unlicensed)})" if unlicensed else "") + "."] # fmt: skip # SPDX headers (charter, licences point 2; the scope is methodology.md, "Provenance in # practice"): tracked files of the kinds below without the line in their first lines lacking = [] for p in present: missing_files = spdx_missing(p.clone) if missing_files: lacking.append(f"{p.name} ({len(missing_files)}: {', '.join(missing_files[:3])}" + (", ..." if len(missing_files) > 3 else "") + ")") # fmt: skip out += ["", f"Repositories whose code, test, script and CI files all carry an SPDX header: " f"{len(present) - len(lacking)} of {len(present)}."] # fmt: skip if lacking: out += ["", "Without one:", ""] + [f"- {item}" for item in lacking] if not whole_family: return out ours, installed = HERE / "docs" / "CLAUDE.md", HERE.parent / "CLAUDE.md" if not installed.is_file(): state = f"not installed: `cp {ours} {installed}`" elif installed.read_bytes() == ours.read_bytes(): state = "installed, identical to docs/CLAUDE.md" else: state = f"installed but **different** from docs/CLAUDE.md: `cp {ours} {installed}`" out += ["", f"{installed}: {state}."] families = HERE / "docs" / "families.md" if families.is_file(): open_items = [line.split("|")[1].strip() for line in families.read_text(encoding="utf-8").splitlines() if line.startswith("|") and "Provenance open" in line] # fmt: skip if open_items: out += ["", f"Provenance questions open in docs/families.md: {', '.join(open_items)}."] return out # The files that must start with an SPDX header (methodology.md, "Provenance in practice"): # source code, tests, scripts, build glue and CI workflows. Documents, data, lockfiles and the # LICENSE file itself do not (they may: a Markdown file takes it as an HTML comment). SPDX_SUFFIXES = { ".py", ".rs", ".js", ".mjs", ".ts", ".c", ".h", ".cc", ".cpp", ".hpp", ".sh", ".bash", ".asm", ".s", ".inc", ".v", ".sv", ".vhd", ".vhdl", ".html", ".css", ".wgsl", ".glsl", } SPDX_PATHS = (".github/workflows/",) SPDX_LINES = 5 # the header is in the first lines (after a shebang, an encoding line, a doctype) SPDX_EXPAT = re.compile(r"SPDX-License-Identifier:.*\bExpat\b", re.IGNORECASE) def spdx_missing(clone: Path) -> list[str]: """Tracked files of a clone that should carry an SPDX header and do not. A header naming `Expat` counts as missing: SPDX has no such identifier, its `MIT` entry is the Expat text (Aubrey's decision L8, 2026-11-25). Those files are listed as `name (Expat)`. """ try: listed = git(clone, "ls-files", "-z").split("\0") except RuntimeError: return [] out = [] for name in listed: path = Path(name) wanted = path.suffix.lower() in SPDX_SUFFIXES or ( name.startswith(SPDX_PATHS) and path.suffix in (".yml", ".yaml")) # fmt: skip if not name or not wanted or "/vendor/" in f"/{name}" or "third_party/" in name: continue try: with (clone / name).open(encoding="utf-8", errors="replace") as handle: head = [handle.readline() for _ in range(SPDX_LINES)] except OSError: continue if not any("SPDX-License-Identifier:" in line for line in head): out.append(name) elif any(SPDX_EXPAT.search(line) for line in head): out.append(f"{name} (Expat)") return out @dataclass(frozen=True) class Reference: project: str url: str rev: str declared_in: str def references(project: Project) -> list[Reference]: """The outside repositories a project pins, read from the files that pin them.""" found = [] for edge in project.data.get("reference", []): path = project.clone / edge["declared_in"] if not path.exists(): raise RuntimeError(f"{project.name}: no {edge['declared_in']}") text = path.read_text(encoding="utf-8") pairs = [] if edge.get("pattern"): for m in re.finditer(edge["pattern"], text): groups = m.groupdict() pairs.append((groups.get("url") or edge["url"], groups.get("rev") or m.group(1))) if not pairs: raise RuntimeError(f"{project.name}: {edge['pattern']!r} not found in {edge['declared_in']}") else: # a pinned_repos.json list: [{"url": ..., "rev": ...}, ...] pairs = [(e["url"], e["rev"]) for e in json.loads(text) if e.get("url") and e.get("rev")] for url, rev in pairs: if edge.get("rev_format"): rev = edge["rev_format"].format(rev) found.append(Reference(project.name, url.removesuffix(".git").rstrip("/"), rev, edge["declared_in"])) return list(dict.fromkeys(found)) def short(rev: str) -> str: return rev[:7] if re.fullmatch(r"[0-9a-f]{40}", rev) else rev def github_token() -> str | None: for name in ("GITHUB_TOKEN", "GH_TOKEN"): if os.environ.get(name): return os.environ[name] if shutil.which("gh"): result = subprocess.run(["gh", "auth", "token"], capture_output=True, text=True) if result.returncode == 0 and result.stdout.strip(): return result.stdout.strip() return None class GitHub: """The few REST calls the online check needs; stdlib only.""" def __init__(self, token: str | None): self.token = token def get(self, path: str): request = urllib.request.Request(f"https://api.github.com/{path}", headers={ "Accept": "application/vnd.github+json", "User-Agent": "emulator-lineage", **({"Authorization": f"Bearer {self.token}"} if self.token else {})}) # fmt: skip try: with urllib.request.urlopen(request, timeout=60) as response: return json.load(response) except urllib.error.HTTPError as error: if error.code == 404: return None raise RuntimeError(f"GitHub {path}: HTTP {error.code} {error.reason}") from None def repo(self, slug: str) -> dict: """Default branch, its newest commit's date, the newest release, archived.""" info = self.get(f"repos/{slug}") if info is None: return {"missing": True} branch = info["default_branch"] head = self.get(f"repos/{slug}/commits/{branch}") release = self.get(f"repos/{slug}/releases/latest") newest = None if release: newest = (release["tag_name"], release["published_at"][:10]) else: tags = self.get(f"repos/{slug}/tags?per_page=1") if tags: newest = (tags[0]["name"], None) return {"branch": branch, "head_date": head["commit"]["committer"]["date"][:10], "archived": info.get("archived", False), "newest": newest} # fmt: skip def since(self, slug: str, rev: str, branch: str) -> dict: """How far the default branch has moved past a pinned revision.""" pinned = self.get(f"repos/{slug}/commits/{rev}") if pinned is None: return {"error": "revision not found"} compare = self.get(f"repos/{slug}/compare/{rev}...{branch}?per_page=1") return {"sha": pinned["sha"], "pin_date": pinned["commit"]["committer"]["date"][:10], "ahead": compare["ahead_by"] if compare else None, "behind": compare["behind_by"] if compare else None} # fmt: skip def references_section(projects: dict[str, Project], online: bool) -> list[str]: refs, stale = [], [] for p in projects.values(): try: refs += references(p) except RuntimeError as error: # a pin the manifest names but the file no longer has stale.append(f"- {error} (the manifest may be out of date)") if not refs and not stale: return [] by_url: dict[str, dict[str, list[str]]] = {} for r in refs: by_url.setdefault(r.url, {}).setdefault(r.rev, []).append(r.project) out = ["", "## Outside references", ""] if stale: out += ["References the report could not read:", ""] + stale + [""] if not online: out += ["Pinned revisions, by repository; `--online` asks GitHub how far each has moved.", ""] for url in sorted(by_url, key=str.lower): revs = by_url[url] pins = "; ".join(f"`{short(rev)}` ({', '.join(sorted(set(ps)))})" for rev, ps in revs.items()) flag = "" if len(revs) > 1: flag = (" -- **different revisions in the family**" if all(re.fullmatch(r"[0-9a-f]{40}", r) for r in revs) else " -- a tag and a commit: `--online` says whether they are one") # fmt: skip out.append(f"- {url.removeprefix('https://')}: {pins}{flag}") return out token = github_token() hub = GitHub(token) slugs = {url: m.group(1) for url in by_url if (m := re.match(r"https://github\.com/([^/]+/[^/]+)$", url))} with ThreadPoolExecutor(8) as pool: repos = dict(zip(slugs, pool.map(lambda u: _safe(hub.repo, slugs[u]), slugs))) jobs = [(u, rev) for u in slugs for rev in by_url[u] if "error" not in repos[u] and not repos[u].get("missing")] moved = dict(zip(jobs, pool.map(lambda j: _safe(hub.since, slugs[j[0]], j[1], repos[j[0]]["branch"]), jobs))) out += [f"Asked GitHub on {date.today().isoformat()}{'' if token else ' (no token: 60 requests an hour)'}. " "\"Since pin\" counts commits on the default branch after the pinned revision; " "whether any of them matters is for a reader to judge.", "", "| reference | pinned at (by) | pin date | since pin | newest release | last commit |", "| --- | --- | --- | --- | --- | --- |"] # fmt: skip rows = [] for url in sorted(by_url, key=str.lower): name = url.removeprefix("https://github.com/").removeprefix("https://") info = repos.get(url) # A tag and a commit that are one revision become one row, named by both. merged: dict[str, tuple[str, list[str]]] = {} for rev, ps in by_url[url].items(): key = moved.get((url, rev), {}).get("sha", rev) if key in merged: first, others = merged[key] merged[key] = (f"{short(first)} = {short(rev)}" if first != rev else first, others + ps) else: merged[key] = (rev, list(ps)) for key, (label, ps) in merged.items(): rev = next(r for r in by_url[url] if moved.get((url, r), {}).get("sha", r) == key) who = ", ".join(sorted(set(ps))) if info is None: rows.append((0, f"| {name} | `{short(rev)}` ({who}) | | not on GitHub: not checked | | |")) continue if "error" in info or info.get("missing"): rows.append((0, f"| {name} | `{short(rev)}` ({who}) | | {info.get('error', 'repository not found')} | | |")) continue m = moved.get((url, rev), {}) if "error" in m: rows.append((0, f"| {name} | `{short(rev)}` ({who}) | | {m['error']} | | {info['head_date']} |")) continue ahead = m.get("ahead") newest = info["newest"] release = f"{newest[0]}" + (f" ({newest[1]})" if newest and newest[1] else "") if newest else "none" # A release dated after the pin is newer content only if commits followed the pin. if newest and newest[1] and ahead and newest[1] > m.get("pin_date", "9999") and newest[0] != rev: release = f"**{release}, after the pin**" since = "?" if ahead is None else ("up to date" if ahead == 0 else f"**{ahead}**") if m.get("behind"): since += f" (pin off {info['branch']})" if info.get("archived"): since += ", archived" rows.append((ahead or 0, f"| {name} | `{short(label) if label == rev else label}` ({who}) | {m.get('pin_date', '')} | {since} | {release} | {info['head_date']} |")) out += [row for _, row in rows] return out def _safe(function, *args): try: return function(*args) except Exception as error: # one unreachable reference must not sink the report return {"error": str(error)[:120]} def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--projects", type=Path, default=HERE / "projects") parser.add_argument("--out", type=Path) parser.add_argument("--for", dest="target", metavar="PROJECT", help="only this project and everything upstream of it") parser.add_argument("--online", action="store_true", help="ask GitHub how far each outside reference has moved since its pin") args = parser.parse_args() projects = load(args.projects) shown = None if args.target: if args.target not in projects: parser.error(f"no manifest for {args.target}") shown = upstream_of(projects, args.target) text = report(projects, shown, args.online) # Commit subjects carry dashes, arrows and accents; a Windows console's code page # would refuse them. if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8") if args.out: args.out.write_text(text, encoding="utf-8") else: sys.stdout.write(text) return 0 if __name__ == "__main__": sys.exit(main())