# SPDX-License-Identifier: MIT """Write the site's third-party notices page from the build's dependency tree. Run with `python3 -I scripts/notices.py` from anywhere; scripts/build-dist.sh runs it before copying web/ into dist/. The same file is in every play-* site (play-md, play-nes, play-gb, play-pce, play-2600); keep the copies identical. What it does: - asks `cargo metadata` (offline, locked, for wasm32-unknown-unknown) for the resolved tree, and walks it from this crate along normal dependencies (not build or dev ones); - for every package reached, collects its LICENSE*, COPYING*, NOTICE* and UNLICENSE* files, verbatim; - for every family crate (a path or git dependency), also collects each comment block in its library sources that carries a licence text (a notice kept beside a table or function taken from a permissive source, such as SameBoy's colour curve), verbatim, with its file and line; - adds the site's own notices/ supplements (notices/*.md, *.txt), verbatim: notices a pinned dependency owes but does not carry at its pinned revision; - adds the games the site serves from web/games/, from the site's notices/games.json: each game's title, author, licence or permission and attribution, with the licence, notice and info files that travel with it, verbatim (a file in web/games/, or a member of a game's zip); - writes one plain HTML page (web/notices.html by default). It fails (exit 1) when a family crate has no LICENSE file, unless that crate is named with --allow-missing (for a local look at the page only; never in the build scripts). It also fails when a game is served without an entry in notices/games.json: a file in web/games/ that no entry names (as its game, one of its files, or in "also_served"), or a "games/..." file in web/app.js's INCLUDED list that has none. It fails when an entry's game or one of its files is missing, when a game's SHA-1 is not the entry's (a new build is a new file: read its terms again and update the entry), and when an entry lists parts whose terms are not recorded ("unrecorded"), unless that game's title is named with --allow-unrecorded (for a local look at the page only; never in the build scripts). notices/games.json: {"games": [{"title": ..., "file": "games/NAME", "sha1": ..., "author": ..., "terms": the licence or permission, "attribution": the attribution it asks for, "source": where the file came from, "links": [{"text": ..., "href": ...}], "notes": [...], "unrecorded": [parts whose terms are not recorded], "files": [{"path": "games/NAME" (served beside it, linked) or the game's zip, "member": NAME in that zip, "encoding": "cp437" (default utf-8), "title": ..., "verbatim": true to print it on the page}]}], "also_served": ["games/NAME", ...]} (files in web/games/ that are not a game's) Paths are relative to web/. With no notices/games.json, the site serves no games. Options: --out PATH the page (default web/notices.html, relative to the site root) --config VALUE passed to cargo as --config VALUE (play-pce's board override) --source-dir PKG=DIR read PKG's licence files and sources from DIR, not its manifest's directory (play-pce's staged board copy has none of its own) --allow-missing PKG do not fail on PKG's missing LICENSE (listed on the page as missing) --allow-unrecorded TITLE do not fail on the game's unrecorded terms (listed on the page as "terms not recorded") """ import argparse import hashlib import html import json import os import re import subprocess import sys import urllib.parse import zipfile ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LICENCE_PREFIXES = ("LICEN", "COPYING", "NOTICE", "UNLICENSE") # Text that only a licence's own wording carries: a comment block holding one is a kept notice. LICENCE_MARKERS = ( "Permission is hereby granted", "Redistribution and use in source and binary forms", "Permission to use, copy, modify, and/or distribute", "Permission to use, copy, modify, and distribute", "Licensed under the Apache License", "This software is provided 'as-is'", ) COMMENT = re.compile(r"^\s*//[/!]?(?: ?)(.*)$") def fail(message): print("notices: " + message, file=sys.stderr) sys.exit(1) def cargo_metadata(configs): cargo = os.environ.get("CARGO", "cargo") base = [cargo, "metadata", "--format-version", "1", "--locked", "--filter-platform", "wasm32-unknown-unknown"] for value in configs: base += ["--config", value] for extra in (["--offline"], []): run = subprocess.run(base + extra, cwd=ROOT, capture_output=True, text=True) if run.returncode == 0: return json.loads(run.stdout) fail("cargo metadata failed:\n" + run.stderr) def licence_files(directory, extra=None): found = [] try: names = sorted(os.listdir(directory)) except OSError: return found for name in names: path = os.path.join(directory, name) if os.path.isfile(path) and name.upper().startswith(LICENCE_PREFIXES): found.append(name) if extra and extra not in found and os.path.isfile(os.path.join(directory, extra)): found.append(extra) return found def read_text(path): with open(path, encoding="utf-8", errors="replace") as handle: return handle.read() def kept_notices(directory, lib_src): """Comment blocks in the library's sources that hold a licence text, verbatim.""" found = [] if not lib_src: return found src_dir = os.path.dirname(lib_src) for here, dirs, files in os.walk(src_dir): dirs[:] = sorted(d for d in dirs if not (here == src_dir and d == "bin")) for name in sorted(files): if not name.endswith(".rs"): continue path = os.path.join(here, name) lines = read_text(path).splitlines() run = [] for number, line in enumerate(lines + [""], 1): match = COMMENT.match(line) if match: run.append((number, match.group(1))) continue if run: text = "\n".join(t for _, t in run) if any(marker in text for marker in LICENCE_MARKERS): rel = os.path.relpath(path, directory) found.append(("%s, lines %d-%d" % (rel, run[0][0], run[-1][0]), text.strip("\n"))) run = [] return found def git_describe(directory): def git(*args): run = subprocess.run(["git", "-C", directory] + list(args), capture_output=True, text=True) return run.stdout.strip() if run.returncode == 0 else None commit = git("rev-parse", "--short=7", "HEAD") if commit is None: return None dirty = subprocess.run(["git", "-C", directory, "diff", "--quiet", "HEAD", "--", "."], capture_output=True).returncode != 0 return commit + ("-dirty" if dirty else "") def where(package, directory): """The package's origin, without any machine path: crates.io, a git URL and rev, or a path relative to the site root and its commit.""" source = package["source"] or "" if source.startswith("registry+"): return "crates.io" if source.startswith("git+"): url, _, commit = source[4:].partition("#") url = url.split("?")[0] return "%s at %s" % (url, commit[:7]) rel = os.path.relpath(directory, ROOT) if rel == ".": return "this site's repository" + (" at %s" % git_describe(directory) if git_describe(directory) else "") described = git_describe(directory) return "%s%s" % (rel, " at " + described if described else "") def sha1_of(path): digest = hashlib.sha1() with open(path, "rb") as handle: for block in iter(lambda: handle.read(1 << 20), b""): digest.update(block) return digest.hexdigest() def included_in_page(): """The "games/..." files web/app.js's INCLUDED list fetches, URL-decoded.""" path = os.path.join(ROOT, "web", "app.js") if not os.path.isfile(path): return [] found = re.findall(r"""\bfile:\s*["'](games/[^"']+)["']""", read_text(path)) return sorted({urllib.parse.unquote(f) for f in found}) def load_games(allow_unrecorded): """The served games and their terms, checked against web/games/ and web/app.js.""" web = os.path.join(ROOT, "web") data_path = os.path.join(ROOT, "notices", "games.json") data = {"games": [], "also_served": []} if os.path.isfile(data_path): with open(data_path, encoding="utf-8") as handle: data = json.load(handle) problems = [] claimed = set(data.get("also_served", [])) games = [] for entry in data.get("games", []): title = entry.get("title") or "(untitled)" for field in ("title", "file", "sha1", "author", "terms"): if not entry.get(field): problems.append("%s: no %s" % (title, field)) game_file = entry.get("file", "") claimed.add(game_file) path = os.path.join(web, game_file) if not os.path.isfile(path): problems.append("%s: %s is not in web/" % (title, game_file)) elif entry.get("sha1") and sha1_of(path) != entry["sha1"]: problems.append("%s: %s has SHA-1 %s, its entry says %s (a new file: read its " "terms again)" % (title, game_file, sha1_of(path), entry["sha1"])) files = [] for item in entry.get("files", []): fpath = os.path.join(web, item["path"]) claimed.add(item["path"]) text = None if "member" in item: try: with zipfile.ZipFile(fpath) as archive: raw = archive.read(item["member"]) except (OSError, KeyError, zipfile.BadZipFile): problems.append("%s: %s is not in %s" % (title, item["member"], item["path"])) continue text = raw.decode(item.get("encoding", "utf-8"), errors="replace") elif not os.path.isfile(fpath): problems.append("%s: %s is not in web/" % (title, item["path"])) continue elif item.get("verbatim"): with open(fpath, encoding=item.get("encoding", "utf-8"), errors="replace") as handle: text = handle.read() files.append(dict(item, text=text if item.get("verbatim") else None)) unrecorded = entry.get("unrecorded", []) if unrecorded and title not in allow_unrecorded: problems.append("%s: terms not recorded for: %s" % (title, "; ".join(unrecorded))) games.append(dict(entry, files=files, unrecorded=unrecorded, id="g-" + re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-"))) games_dir = os.path.join(web, "games") if os.path.isdir(games_dir): for here, dirs, names in os.walk(games_dir): dirs.sort() for name in sorted(names): rel = os.path.relpath(os.path.join(here, name), web).replace(os.sep, "/") if rel not in claimed: problems.append("web/%s is served but notices/games.json has no entry " "for it" % rel) for rel in included_in_page(): if rel not in claimed: problems.append("web/app.js includes %s but notices/games.json has no entry for " "it" % rel) if problems: fail("included games:\n " + "\n ".join(problems) + "\nthe build stops here so no " "game is served without its terms (notices/games.json)") return games def walk(meta): packages = {p["id"]: p for p in meta["packages"]} nodes = {n["id"]: n for n in meta["resolve"]["nodes"]} root = meta["resolve"]["root"] if root is None: fail("no root package (is this a workspace without a root crate?)") def is_macro(pid): return any("proc-macro" in t["kind"] for t in packages[pid]["targets"]) def reach(through_macros): seen, todo = set(), [root] while todo: pid = todo.pop() if pid in seen: continue seen.add(pid) if not through_macros and pid != root and is_macro(pid): continue for dep in nodes[pid]["deps"]: if any(k["kind"] is None for k in dep["dep_kinds"]): todo.append(dep["pkg"]) return seen every = reach(True) shipped = {pid for pid in reach(False) if pid == root or not is_macro(pid)} return packages, root, shipped, every - shipped def main(): parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--out", default="web/notices.html") parser.add_argument("--config", action="append", default=[]) parser.add_argument("--source-dir", action="append", default=[]) parser.add_argument("--allow-missing", action="append", default=[]) parser.add_argument("--allow-unrecorded", action="append", default=[]) args = parser.parse_args() games = load_games(args.allow_unrecorded) overrides = {} for item in args.source_dir: name, _, directory = item.partition("=") overrides[name] = os.path.abspath(os.path.join(ROOT, directory)) meta = cargo_metadata(args.config) packages, root, shipped, build_time = walk(meta) texts = {} # sha256 -> text: identical licence files are printed once entries = [] missing = [] for pid in sorted(shipped | build_time, key=lambda p: (p != root, (packages[p]["source"] or "").startswith( "registry+"), p in build_time, packages[p]["name"], packages[p]["version"])): package = packages[pid] name = package["name"] directory = overrides.get(name, os.path.dirname(package["manifest_path"])) family = not (package["source"] or "").startswith("registry+") files = [] for fname in licence_files(directory, package.get("license_file")): text = read_text(os.path.join(directory, fname)) digest = hashlib.sha256(text.encode()).hexdigest() texts.setdefault(digest, text) files.append((fname, digest)) has_licence = any(not f.upper().startswith("NOTICE") for f, _ in files) kept = [] if family: lib = next((t["src_path"] for t in package["targets"] if "lib" in t["kind"] or "cdylib" in t["kind"] or "rlib" in t["kind"]), None) if lib and name in overrides: lib = os.path.join(directory, os.path.relpath( lib, os.path.dirname(package["manifest_path"]))) kept = kept_notices(directory, lib) if not has_licence: missing.append(name) if family and name not in args.allow_missing: print("notices: %s (%s) has no LICENSE file" % (name, where(package, directory)), file=sys.stderr) entries.append({ "id": "c-" + re.sub(r"[^a-z0-9]+", "-", (name + "-" + package["version"]).lower()), "name": name, "version": package["version"], "licence": package.get("license") or "(none declared)", "where": where(package, directory), "family": family, "build_time": pid in build_time, "files": files, "kept": kept, "has_licence": has_licence, }) fatal = [m for m in missing if m not in args.allow_missing and next(e for e in entries if e["name"] == m)["family"]] if fatal: fail("family crates without a LICENSE file: %s; add one upstream (the build stops " "here so the site is not shipped without it)" % ", ".join(fatal)) supplements = [] sup_dir = os.path.join(ROOT, "notices") if os.path.isdir(sup_dir): for fname in sorted(os.listdir(sup_dir)): if fname.endswith((".md", ".txt")): supplements.append((fname, read_text(os.path.join(sup_dir, fname)))) site = packages[root]["name"] out = os.path.join(ROOT, args.out) os.makedirs(os.path.dirname(out), exist_ok=True) with open(out, "w", encoding="utf-8") as handle: handle.write(render(site, entries, texts, supplements, missing, games)) shipped_n = sum(1 for e in entries if not e["build_time"]) print("notices: wrote %s: %d games, %d components in the site, %d build-time only, %d " "kept notices in sources, %d supplements%s%s" % ( os.path.relpath(out, ROOT), len(games), shipped_n, len(entries) - shipped_n, sum(len(e["kept"]) for e in entries), len(supplements), "; no licence file: " + ", ".join(missing) if missing else "", "; terms not recorded: " + ", ".join(g["title"] for g in games if g["unrecorded"]) if any(g["unrecorded"] for g in games) else "")) def render_games(games, add): e = html.escape add("

Games included on this site

\n") if not games: add("

This site includes no games: it plays only the files its visitors choose.

\n") return add("

The games the site offers to play, served from games/. Each is its " "authors' work, under its own terms below, not under the site's licence. The files " "that travel with a game are named under it, and its licence and notice texts are " "quoted as they are served.

\n") add("\n\n") for game in games: add("\n" % ( game["id"], e(game["title"]), e(game["author"]), e(game["terms"]), " Terms not recorded for part of it." if game["unrecorded"] else "")) add("
GameByLicence or permission
%s%s%s%s
\n") for game in games: add("

%s

\n" % (game["id"], e(game["title"]))) add("

By %s. File: %s, SHA-1 %s.

\n" % ( e(game["author"]), e(urllib.parse.quote(game["file"])), e(game["file"]), e(game["sha1"]))) add("

Licence or permission: %s

\n" % e(game["terms"])) if game.get("attribution"): add("

Attribution: %s

\n" % e(game["attribution"])) if game.get("source"): add("

From: %s

\n" % e(game["source"])) for note in game.get("notes", []): add("

%s

\n" % e(note)) if game["unrecorded"]: add("

Terms not recorded: %s

\n" % e("; ".join(game["unrecorded"]))) if game.get("links"): add("

%s

\n" % " ยท ".join( "%s" % (e(link["href"]), e(link["text"])) for link in game["links"])) for item in game["files"]: label = item.get("title") or item.get("member") or item["path"] if "member" in item: where_ = "%s in %s" % ( e(item["member"]), e(urllib.parse.quote(item["path"])), e(item["path"])) else: where_ = "%s" % (e(urllib.parse.quote(item["path"])), e(item["path"])) add("

%s

\n

%s%s

\n" % ( e(label), where_, ", verbatim:" if item["text"] is not None else "")) if item["text"] is not None: add("
%s
\n" % e(item["text"].rstrip())) def render(site, entries, texts, supplements, missing, games): e = html.escape out = [] add = out.append add("\n\n" "\n" "\n\n\n" "\n") add("%s: licences and notices\n" % e(site)) add("\n\n\n") add("

Back to %s

\n" % e(site)) add("

Licences and notices

\n") add("

This site is %s, MIT licensed. The WebAssembly program it serves is built from the " "components below; each one's licence and notice files follow, as they are in the " "revision built. Notices that a component keeps in its source code, beside a table or " "function taken from another project, are quoted after its files. The JavaScript glue " "in pkg/ is generated by wasm-bindgen (listed below). Identical licence " "files are printed once and linked from each component that carries them.

\n" % e(site)) add("

The games the site includes, and their terms, come first: Games " "included on this site.

\n") render_games(games, add) if missing: add("

No licence file found for: %s (the licence named in their " "manifests applies).

\n" % e(", ".join(missing))) add("

Components

\n\n" "\n") for entry in entries: if entry["build_time"]: continue add("\n" % ( entry["id"], e(entry["name"]), e(entry["version"]), e(entry["licence"]), e(entry["where"]))) add("
ComponentLicenceFrom
%s %s%s%s
\n") build_time = [x for x in entries if x["build_time"]] if build_time: add("

Used only while building (procedural macros and what they " "use; their own code is not in the program, their licences are below too): %s.

\n" % ", ".join("%s %s" % (x["id"], e(x["name"]), e(x["version"])) for x in build_time)) printed = set() for entry in entries: add("

%s %s

\n" % (entry["id"], e(entry["name"]), e(entry["version"]))) add("

Licence: %s. From %s.%s

\n" % ( e(entry["licence"]), e(entry["where"]), " Used only while building." if entry["build_time"] else "")) if not entry["files"]: add("

No licence or notice file in this component.

\n") for fname, digest in entry["files"]: anchor = "t-" + digest[:12] if digest in printed: add("

%s

\n

The same text as printed " "above.

\n" % (e(fname), anchor)) else: printed.add(digest) add("

%s

\n
%s
\n" % (anchor, e(fname), e(texts[digest].rstrip()))) for place, text in entry["kept"]: add("

Notice kept in %s

\n
%s
\n" % (e(place), e(text))) if supplements: add("

Notices this site adds

\n

Notices a " "component owes for what its built revision holds but does not carry in that " "revision's own files; each says where it comes from.

\n") for fname, text in supplements: add("

%s

\n
%s
\n" % (e(fname), e(text.rstrip()))) add("\n\n") return "".join(out) if __name__ == "__main__": main()