#!/usr/bin/env python3 """Generate or check Mapa's Colophon inventory (Help, Colophon). The inventory is internal/mapa/credits/notices.json, embedded in the release and drawn by estilo's credits template at GET /help/open-source. Nothing in it is written by hand; each part is read from what ships: - Go modules: go list -deps of ./cmd/mapa for linux/arm64, the release build (make release), through estilo's cmd/oficina-notices and its credits/catalog, with the Go toolchain's own licence and estilo's Lucide notice (Mapa's icons are Lucide's). Mapa serves no webfont, so no typeface is listed. - JavaScript packages: the npm packages esbuild reads for the bundles in editor/bundles.mjs, the committed internal/mapa/static/editor.*.js, each with its own licence files, unaltered. `make credits` regenerates both files; `make credits-check` (in make ci) recomputes the Go half and the digest of the bundle's inputs and fails on any drift. The check needs Go only: the npm half is recorded in internal/mapa/credits/assets.json with the digest of what it was read from, and a changed lockfile, bundle list or bundle makes it stale. """ import hashlib import json import os from pathlib import Path import subprocess import sys import tempfile ROOT = Path(__file__).resolve().parent.parent OUT = ROOT / 'internal/mapa/credits' EDITOR = ROOT / 'editor' def pinned_toolchain(): """go.mod's toolchain line, which the Makefile pins too: the Go version is in the inventory, so a newer local Go must not win.""" for line in (ROOT / 'go.mod').read_text().splitlines(): if line.startswith('toolchain '): return line.split()[1] raise ValueError('go.mod names no toolchain') # Oficina's own modules: estilo, and the Notion import's client. Rastrillo # is listed, as every Oficina app lists it: it is its own project, with # its own licence. FIRST_PARTY = ['amadan.net/oficina/estilo.git', 'amadan.net/oficina/notion.git'] ENV = os.environ | {'GOPRIVATE': ','.join(FIRST_PARTY), 'GOTOOLCHAIN': pinned_toolchain()} NOTICE_WORDS = ['license', 'licence', 'copying', 'notice', 'copyright', 'patents'] CODE_SUFFIXES = ['.go', '.js', '.mjs', '.cjs', '.ts', '.map'] def run(args, cwd=ROOT, env=ENV): return subprocess.check_output(args, cwd=cwd, env=env) def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def inputs(): """What the npm half is read from, each file's digest.""" files = [EDITOR / name for name in ['package.json', 'package-lock.json', 'bundles.mjs']] files.extend(ROOT.glob('internal/mapa/static/editor.*.js')) return {str(path.relative_to(ROOT)): digest(path) for path in sorted(files) if path.is_file()} def notice_name(name): lower = name.lower() return any(lower == word or lower.startswith(word + separator) for word in NOTICE_WORDS for separator in '.-_') def notices(directory): """A package's own licence files, at its top level, unaltered.""" result = [] for path in sorted(directory.iterdir()): if path.suffix.lower() in CODE_SUFFIXES: continue if not (path.is_file() and notice_name(path.name)): continue if path.is_symlink() or path.stat().st_size > 2 * 1024 * 1024: raise ValueError('notice must be a bounded regular file') text = path.read_bytes().decode('utf-8') if not text.strip(): raise ValueError('empty notice: ' + str(path)) result.append({'Name': path.name, 'Text': text}) return result def go_inventory(): with tempfile.TemporaryDirectory() as temp: tool = str(Path(temp) / 'notices') host = json.loads(run(['go', 'env', '-json', 'GOHOSTOS', 'GOHOSTARCH'])) run(['go', 'build', '-o', tool, 'amadan.net/oficina/estilo.git/cmd/oficina-notices'], env=ENV | {'GOOS': host['GOHOSTOS'], 'GOARCH': host['GOHOSTARCH'], 'CGO_ENABLED': '0'}) return json.loads(run( [tool, '-package', './cmd/mapa', '-lucide', '-exclude', ','.join(FIRST_PARTY)], env=ENV | {'GOOS': 'linux', 'GOARCH': 'arm64', 'CGO_ENABLED': '0', 'GOWORK': 'off'})) # Prints every input esbuild reads for the shipped bundles, relative to # editor/, after checking each rebuilt bundle is the committed one. The # build is in memory: nothing is written. BUNDLED = r''' import { build } from 'esbuild' import { createHash } from 'node:crypto' import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { bundles, options } from './bundles.mjs' const here = process.cwd() const staticDir = join(here, '..', 'internal', 'mapa', 'static') const inputs = new Set() for (const { name, entry, format = 'esm' } of bundles) { const result = await build({ ...options, entryPoints: [join(here, entry)], format, outfile: join(staticDir, `${name}.js`), write: false, metafile: true, absWorkingDir: here }) const bytes = result.outputFiles.find(f => f.path.endsWith('.js')).contents const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 16) const committed = join(staticDir, `${name}.${hash}.js`) if (!existsSync(committed) || !Buffer.from(bytes).equals(readFileSync(committed))) { throw new Error(`${name}: the committed bundle is not this build`) } for (const path of Object.keys(result.metafile.inputs)) inputs.add(path) } console.log(JSON.stringify([...inputs].sort())) ''' def package_directory(name, node_root): directory = (EDITOR / name).resolve().parent while not (directory / 'package.json').is_file(): if directory == node_root or not directory.is_relative_to(node_root): raise ValueError('bundled file has no package: ' + name) directory = directory.parent return directory def npm_inventory(): run(['npm', 'ci', '--ignore-scripts', '--no-audit', '--no-fund', '--loglevel=error'], cwd=EDITOR) bundled = json.loads(run(['node', '--input-type=module', '-e', BUNDLED], cwd=EDITOR)) node_root = (EDITOR / 'node_modules').resolve() directories = {package_directory(name, node_root) for name in bundled if 'node_modules/' in name} components = [] for directory in sorted(directories): package = json.loads((directory / 'package.json').read_text()) texts = notices(directory) if not texts: raise ValueError(package['name'] + ' ships no licence file') components.append({ 'Name': package['name'], 'Version': package['version'], 'SourceURL': 'https://www.npmjs.com/package/' + package['name'] + '/v/' + package['version'], 'Notices': texts}) return {'inputs': inputs(), 'components': components} def main(): if sys.argv[1:] not in [[], ['--check']]: raise SystemExit('usage: scripts/credits.py [--check]') checking = sys.argv[1:] == ['--check'] assets_file = OUT / 'assets.json' assets = (json.loads(assets_file.read_text()) if checking else npm_inventory()) if assets['inputs'] != inputs(): raise SystemExit('the Colophon\'s JavaScript inventory is stale; ' 'run make credits') inventory = go_inventory() inventory['components'].extend(assets['components']) inventory['components'].sort(key=lambda item: item['Name']) target = OUT / 'notices.json' if checking: if json.loads(target.read_text()) != inventory: raise SystemExit('the embedded Colophon is stale; ' 'run make credits') else: OUT.mkdir(parents=True, exist_ok=True) assets_file.write_text(json.dumps(assets, indent=2) + '\n') target.write_text(json.dumps(inventory, indent=2) + '\n') print('credits: ' + ('checked' if checking else 'generated')) if __name__ == '__main__': main()