| 1 | #!/usr/bin/env python3 |
| 2 | """Generate or check Mapa's Colophon inventory (Help, Colophon). |
| 3 | |
| 4 | The inventory is internal/mapa/credits/notices.json, embedded in the |
| 5 | release and drawn by estilo's credits template at GET /help/open-source. |
| 6 | Nothing in it is written by hand; each part is read from what ships: |
| 7 | |
| 8 | - Go modules: go list -deps of ./cmd/mapa for linux/arm64, the release |
| 9 | build (make release), through estilo's cmd/oficina-notices and its |
| 10 | credits/catalog, with the Go toolchain's own licence and estilo's |
| 11 | Lucide notice (Mapa's icons are Lucide's). Mapa serves no webfont, |
| 12 | so no typeface is listed. |
| 13 | - JavaScript packages: the npm packages esbuild reads for the bundles |
| 14 | in editor/bundles.mjs, the committed internal/mapa/static/editor.*.js, |
| 15 | each with its own licence files, unaltered. |
| 16 | |
| 17 | `make credits` regenerates both files; `make credits-check` (in make ci) |
| 18 | recomputes the Go half and the digest of the bundle's inputs and fails |
| 19 | on any drift. The check needs Go only: the npm half is recorded in |
| 20 | internal/mapa/credits/assets.json with the digest of what it was read |
| 21 | from, and a changed lockfile, bundle list or bundle makes it stale. |
| 22 | """ |
| 23 | import hashlib |
| 24 | import json |
| 25 | import os |
| 26 | from pathlib import Path |
| 27 | import subprocess |
| 28 | import sys |
| 29 | import tempfile |
| 30 | |
| 31 | ROOT = Path(__file__).resolve().parent.parent |
| 32 | OUT = ROOT / 'internal/mapa/credits' |
| 33 | EDITOR = ROOT / 'editor' |
| 34 | |
| 35 | |
| 36 | def pinned_toolchain(): |
| 37 | """go.mod's toolchain line, which the Makefile pins too: the Go |
| 38 | version is in the inventory, so a newer local Go must not win.""" |
| 39 | for line in (ROOT / 'go.mod').read_text().splitlines(): |
| 40 | if line.startswith('toolchain '): |
| 41 | return line.split()[1] |
| 42 | raise ValueError('go.mod names no toolchain') |
| 43 | |
| 44 | |
| 45 | # Oficina's own modules: estilo, and the Notion import's client. Rastrillo |
| 46 | # is listed, as every Oficina app lists it: it is its own project, with |
| 47 | # its own licence. |
| 48 | FIRST_PARTY = ['amadan.net/oficina/estilo.git', |
| 49 | 'amadan.net/oficina/notion.git'] |
| 50 | ENV = os.environ | {'GOPRIVATE': ','.join(FIRST_PARTY), |
| 51 | 'GOTOOLCHAIN': pinned_toolchain()} |
| 52 | NOTICE_WORDS = ['license', 'licence', 'copying', 'notice', 'copyright', |
| 53 | 'patents'] |
| 54 | CODE_SUFFIXES = ['.go', '.js', '.mjs', '.cjs', '.ts', '.map'] |
| 55 | |
| 56 | |
| 57 | def run(args, cwd=ROOT, env=ENV): |
| 58 | return subprocess.check_output(args, cwd=cwd, env=env) |
| 59 | |
| 60 | |
| 61 | def digest(path): |
| 62 | return hashlib.sha256(path.read_bytes()).hexdigest() |
| 63 | |
| 64 | |
| 65 | def inputs(): |
| 66 | """What the npm half is read from, each file's digest.""" |
| 67 | files = [EDITOR / name for name in |
| 68 | ['package.json', 'package-lock.json', 'bundles.mjs']] |
| 69 | files.extend(ROOT.glob('internal/mapa/static/editor.*.js')) |
| 70 | return {str(path.relative_to(ROOT)): digest(path) |
| 71 | for path in sorted(files) if path.is_file()} |
| 72 | |
| 73 | |
| 74 | def notice_name(name): |
| 75 | lower = name.lower() |
| 76 | return any(lower == word or lower.startswith(word + separator) |
| 77 | for word in NOTICE_WORDS for separator in '.-_') |
| 78 | |
| 79 | |
| 80 | def notices(directory): |
| 81 | """A package's own licence files, at its top level, unaltered.""" |
| 82 | result = [] |
| 83 | for path in sorted(directory.iterdir()): |
| 84 | if path.suffix.lower() in CODE_SUFFIXES: |
| 85 | continue |
| 86 | if not (path.is_file() and notice_name(path.name)): |
| 87 | continue |
| 88 | if path.is_symlink() or path.stat().st_size > 2 * 1024 * 1024: |
| 89 | raise ValueError('notice must be a bounded regular file') |
| 90 | text = path.read_bytes().decode('utf-8') |
| 91 | if not text.strip(): |
| 92 | raise ValueError('empty notice: ' + str(path)) |
| 93 | result.append({'Name': path.name, 'Text': text}) |
| 94 | return result |
| 95 | |
| 96 | |
| 97 | def go_inventory(): |
| 98 | with tempfile.TemporaryDirectory() as temp: |
| 99 | tool = str(Path(temp) / 'notices') |
| 100 | host = json.loads(run(['go', 'env', '-json', |
| 101 | 'GOHOSTOS', 'GOHOSTARCH'])) |
| 102 | run(['go', 'build', '-o', tool, |
| 103 | 'amadan.net/oficina/estilo.git/cmd/oficina-notices'], |
| 104 | env=ENV | {'GOOS': host['GOHOSTOS'], |
| 105 | 'GOARCH': host['GOHOSTARCH'], 'CGO_ENABLED': '0'}) |
| 106 | return json.loads(run( |
| 107 | [tool, '-package', './cmd/mapa', '-lucide', |
| 108 | '-exclude', ','.join(FIRST_PARTY)], |
| 109 | env=ENV | {'GOOS': 'linux', 'GOARCH': 'arm64', |
| 110 | 'CGO_ENABLED': '0', 'GOWORK': 'off'})) |
| 111 | |
| 112 | |
| 113 | # Prints every input esbuild reads for the shipped bundles, relative to |
| 114 | # editor/, after checking each rebuilt bundle is the committed one. The |
| 115 | # build is in memory: nothing is written. |
| 116 | BUNDLED = r''' |
| 117 | import { build } from 'esbuild' |
| 118 | import { createHash } from 'node:crypto' |
| 119 | import { existsSync, readFileSync } from 'node:fs' |
| 120 | import { join } from 'node:path' |
| 121 | import { bundles, options } from './bundles.mjs' |
| 122 | const here = process.cwd() |
| 123 | const staticDir = join(here, '..', 'internal', 'mapa', 'static') |
| 124 | const inputs = new Set() |
| 125 | for (const { name, entry, format = 'esm' } of bundles) { |
| 126 | const result = await build({ ...options, entryPoints: [join(here, entry)], |
| 127 | format, outfile: join(staticDir, `${name}.js`), write: false, |
| 128 | metafile: true, absWorkingDir: here }) |
| 129 | const bytes = result.outputFiles.find(f => f.path.endsWith('.js')).contents |
| 130 | const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 16) |
| 131 | const committed = join(staticDir, `${name}.${hash}.js`) |
| 132 | if (!existsSync(committed) || |
| 133 | !Buffer.from(bytes).equals(readFileSync(committed))) { |
| 134 | throw new Error(`${name}: the committed bundle is not this build`) |
| 135 | } |
| 136 | for (const path of Object.keys(result.metafile.inputs)) inputs.add(path) |
| 137 | } |
| 138 | console.log(JSON.stringify([...inputs].sort())) |
| 139 | ''' |
| 140 | |
| 141 | |
| 142 | def package_directory(name, node_root): |
| 143 | directory = (EDITOR / name).resolve().parent |
| 144 | while not (directory / 'package.json').is_file(): |
| 145 | if directory == node_root or not directory.is_relative_to(node_root): |
| 146 | raise ValueError('bundled file has no package: ' + name) |
| 147 | directory = directory.parent |
| 148 | return directory |
| 149 | |
| 150 | |
| 151 | def npm_inventory(): |
| 152 | run(['npm', 'ci', '--ignore-scripts', '--no-audit', '--no-fund', |
| 153 | '--loglevel=error'], cwd=EDITOR) |
| 154 | bundled = json.loads(run(['node', '--input-type=module', '-e', BUNDLED], |
| 155 | cwd=EDITOR)) |
| 156 | node_root = (EDITOR / 'node_modules').resolve() |
| 157 | directories = {package_directory(name, node_root) |
| 158 | for name in bundled if 'node_modules/' in name} |
| 159 | components = [] |
| 160 | for directory in sorted(directories): |
| 161 | package = json.loads((directory / 'package.json').read_text()) |
| 162 | texts = notices(directory) |
| 163 | if not texts: |
| 164 | raise ValueError(package['name'] + ' ships no licence file') |
| 165 | components.append({ |
| 166 | 'Name': package['name'], 'Version': package['version'], |
| 167 | 'SourceURL': 'https://www.npmjs.com/package/' + package['name'] |
| 168 | + '/v/' + package['version'], |
| 169 | 'Notices': texts}) |
| 170 | return {'inputs': inputs(), 'components': components} |
| 171 | |
| 172 | |
| 173 | def main(): |
| 174 | if sys.argv[1:] not in [[], ['--check']]: |
| 175 | raise SystemExit('usage: scripts/credits.py [--check]') |
| 176 | checking = sys.argv[1:] == ['--check'] |
| 177 | assets_file = OUT / 'assets.json' |
| 178 | assets = (json.loads(assets_file.read_text()) if checking |
| 179 | else npm_inventory()) |
| 180 | if assets['inputs'] != inputs(): |
| 181 | raise SystemExit('the Colophon\'s JavaScript inventory is stale; ' |
| 182 | 'run make credits') |
| 183 | inventory = go_inventory() |
| 184 | inventory['components'].extend(assets['components']) |
| 185 | inventory['components'].sort(key=lambda item: item['Name']) |
| 186 | target = OUT / 'notices.json' |
| 187 | if checking: |
| 188 | if json.loads(target.read_text()) != inventory: |
| 189 | raise SystemExit('the embedded Colophon is stale; ' |
| 190 | 'run make credits') |
| 191 | else: |
| 192 | OUT.mkdir(parents=True, exist_ok=True) |
| 193 | assets_file.write_text(json.dumps(assets, indent=2) + '\n') |
| 194 | target.write_text(json.dumps(inventory, indent=2) + '\n') |
| 195 | print('credits: ' + ('checked' if checking else 'generated')) |
| 196 | |
| 197 | |
| 198 | if __name__ == '__main__': |
| 199 | main() |
| 200 | |