oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1#!/usr/bin/env python3
2"""Generate or check the notices embedded in the Slides release."""
3import hashlib
4import json
5import os
6from pathlib import Path
7import subprocess
8import sys
9import tempfile
10from html.parser import HTMLParser
11
12ROOT = Path(__file__).resolve().parent.parent
13OUT = ROOT / 'internal/slides/credits'
14ENV = os.environ | {'GOPRIVATE': 'amadan.net/oficina/estilo.git'}
15EXCLUDE = ','.join(['amadan.net/oficina/agent-access.git', 'amadan.net/oficina/home/dashboard', 'amadan.net/oficina/estilo.git', 'amadan.net/oficina/home/handoff', 'amadan.net/oficina/home/connect', 'amadan.net/oficina/home/roster', 'amadan.net/oficina/home/teammode'])
16
17
18def run(args, cwd=ROOT, env=ENV):
19 return subprocess.check_output(args, cwd=cwd, env=env)
20
21
22def digest(path):
23 return hashlib.sha256(path.read_bytes()).hexdigest()
24
25
26def inputs():
27 files = [ROOT / p for p in ['core/Cargo.toml', 'core/Cargo.lock', 'core/pdf/Cargo.toml', 'core/pdf/Cargo.lock', 'rust-toolchain.toml', 'fixtures/package.json', 'fixtures/package-lock.json', 'internal/slides/core/testdata/slides_core.wasm', 'internal/slides/pdfcore/testdata/slides_pdf.wasm']]
28 for pattern in ['internal/slides/static/*.js', 'internal/slides/fonts/files/*', 'internal/slides/static/fonts/*', 'internal/slides/credits/upstream/*', 'core/vendor/fastrand-2.5.0/**/*']:
29 files.extend(ROOT.glob(pattern))
30 return {str(p.relative_to(ROOT)): digest(p) for p in sorted(files) if p.is_file()}
31
32
33def notices(directory):
34 result = []
35 for path in sorted(directory.rglob("*")):
36 lower = path.name.lower()
37 if path.suffix.lower() in [".go", ".rs", ".js", ".ts", ".c", ".h", ".py"]:
38 continue
39 if path.is_file() and any(lower == word or lower.startswith(word + '.') or lower.startswith(word + '-') or lower.startswith(word + '_') for word in ['license', 'licence', 'copying', 'notice', 'copyright', 'patents']):
40 if path.is_symlink() or path.stat().st_size > 2 * 1024 * 1024:
41 raise ValueError('notice must be a bounded regular file')
42 text = path.read_bytes().decode('utf-8')
43 if not text.strip():
44 raise ValueError('empty notice')
45 result.append({'Name': str(path.relative_to(directory)), 'Text': text})
46 return result
47
48
49def go_inventory():
50 with tempfile.TemporaryDirectory() as temp:
51 tool = str(Path(temp) / 'notices')
52 host = json.loads(run(['go', 'env', '-json', 'GOHOSTOS', 'GOHOSTARCH']))
53 run(['go', 'build', '-o', tool, 'amadan.net/oficina/estilo.git/cmd/oficina-notices'], env=ENV | {'GOOS': host['GOHOSTOS'], 'GOARCH': host['GOHOSTARCH'], 'CGO_ENABLED': '0'})
54 return json.loads(run([tool, '-package', './cmd/slides', '-lucide', '-onest', '-exclude', EXCLUDE], env=ENV | {'GOOS': 'linux', 'GOARCH': 'arm64', 'CGO_ENABLED': '0', 'GOWORK': 'off'}))
55
56
57class NoticeText(HTMLParser):
58 def __init__(self):
59 super().__init__(convert_charrefs=True)
60 self.parts = []
61
62 def handle_data(self, data):
63 self.parts.append(data)
64
65 def handle_starttag(self, tag, attrs):
66 if tag in ['p', 'h1', 'h2', 'h3', 'li', 'pre', 'br']:
67 self.parts.append('\n')
68
69
70def verified_vendor(package):
71 record = json.loads((OUT / 'upstream/fastrand-vendor.json').read_text())
72 directory = ROOT / 'core/vendor/fastrand-2.5.0'
73 manifest = Path(package['manifest_path'])
74 if (package['source'] is not None or package['name'] != 'fastrand'
75 or package['version'] != '2.5.0'
76 or manifest != directory / 'Cargo.toml'
77 or manifest.resolve() != directory / 'Cargo.toml'):
78 raise ValueError('unverified Cargo source replacement')
79 files = {}
80 for path in directory.rglob('*'):
81 if path.is_symlink():
82 raise ValueError('vendored source must not contain symlinks')
83 if path.is_file():
84 files[str(path.relative_to(directory))] = digest(path)
85 # This reviewed manifest is anchored to the recorded upstream crate archive.
86 # Its only source difference is the documented Cargo feature patch.
87 if files != record['files']:
88 raise ValueError('vendored source differs from verified upstream patch')
89
90
91def asset_inventory():
92 fixtures = ROOT / 'fixtures'
93 run(['npm', 'ci', '--ignore-scripts', '--no-audit', '--no-fund'], cwd=fixtures)
94 js = r'''
95import { build } from 'esbuild';
96import { readFileSync, readdirSync } from 'node:fs';
97const inputs = new Set();
98for (const [name, entry, format] of [['editor', 'editor-entry.js', 'esm'], ['fontsgate', 'fonts-gate.mjs', 'esm'], ['fontshold', 'fonts-hold.js', 'iife']]) {
99 const result = await build({entryPoints:[entry],bundle:true,format,minify:true,target:'es2020',outfile:`../internal/slides/static/${name}.js`,write:false,metafile:true});
100 const original = readdirSync('../internal/slides/static').filter(p => p.startsWith(name+'.') && p.endsWith('.js'));
101 if (original.length !== 1 || !Buffer.from(result.outputFiles.find(p => p.path.endsWith('.js')).contents).equals(readFileSync('../internal/slides/static/'+original[0]))) throw new Error('committed bundle differs from locked source');
102 for (const path of Object.keys(result.metafile.inputs)) if (path.includes('node_modules/')) inputs.add(path);
103}
104console.log(JSON.stringify([...inputs]));
105'''
106 bundled = json.loads(run(['node', '--input-type=module', '-e', js], cwd=fixtures))
107 directories = set()
108 for name in bundled:
109 directory = (fixtures / name).resolve().parent
110 node_root = (fixtures / 'node_modules').resolve()
111 while not (directory / 'package.json').is_file():
112 if directory == node_root or not directory.is_relative_to(node_root):
113 raise ValueError('bundled package provenance is missing')
114 directory = directory.parent
115 if not directory.is_relative_to(node_root):
116 raise ValueError('bundled package escapes node_modules')
117 directories.add(directory)
118 components = []
119 for directory in sorted(directories):
120 package = json.loads((directory / 'package.json').read_text())
121 components.append({'Name': package['name'], 'Version': package['version'], 'SourceURL': 'https://www.npmjs.com/package/' + package['name'] + '/v/' + package['version'], 'Notices': notices(directory)})
122 selected = {}
123 for crate, script, built, embedded in [
124 ('core', 'scripts/build-wasm.sh', 'core/target/wasm32-unknown-unknown/release/slides_core.wasm', 'internal/slides/core/testdata/slides_core.wasm'),
125 ('core/pdf', 'scripts/build-pdf-wasm.sh', 'core/pdf/target/wasm32-unknown-unknown/release/slides_pdf.wasm', 'internal/slides/pdfcore/testdata/slides_pdf.wasm')]:
126 run(['bash', script])
127 if (ROOT / built).read_bytes() != (ROOT / embedded).read_bytes():
128 raise ValueError('committed Wasm differs from locked source')
129 metadata = json.loads(run(['cargo', 'metadata', '--locked', '--filter-platform', 'wasm32-unknown-unknown', '--format-version', '1'], cwd=ROOT / crate))
130 packages = {p['id']: p for p in metadata['packages']}
131 nodes = {p['id']: p for p in metadata['resolve']['nodes']}
132 pending, seen = [metadata['resolve']['root']], set()
133 while pending:
134 current = pending.pop()
135 if current in seen:
136 continue
137 seen.add(current)
138 pending.extend(d['pkg'] for d in nodes[current]['deps'] if any(k['kind'] != 'dev' for k in d['dep_kinds']))
139 for identity in seen:
140 package = packages[identity]
141 if identity != metadata['resolve']['root']:
142 if package['source'] != 'registry+https://github.com/rust-lang/crates.io-index':
143 verified_vendor(package)
144 selected[(package['name'], package['version'])] = package
145 for key in sorted(selected):
146 package = selected[key]
147 directory = Path(package['manifest_path']).parent
148 texts = notices(directory)
149 if package['name'] in ['yrs', 'krilla', 'krilla-svg']:
150 expected = '3996e91df00acdb67334695944bc43f60627103f' if package['name'] == 'yrs' else '3ffdf0588cf98050aad6edba51ca70162e1fb5b5'
151 vcs = json.loads((directory / '.cargo_vcs_info.json').read_text())
152 if vcs['git']['sha1'] != expected:
153 raise ValueError('upstream source revision changed')
154 for record in json.loads((OUT / 'upstream/provenance.json').read_text()):
155 prefix = 'yrs-' if package['name'] == 'yrs' else 'krilla-'
156 if not record['file'].startswith(prefix):
157 continue
158 path = OUT / 'upstream' / record['file']
159 if digest(path) != record['sha256']:
160 raise ValueError('original notice checksum changed')
161 texts.append({'Name': record['file'], 'Text': path.read_bytes().decode('utf-8')})
162 components.append({'Name': package['name'], 'Version': package['version'], 'SourceURL': 'https://crates.io/crates/' + package['name'] + '/' + package['version'], 'Notices': texts})
163 sysroot = Path(run(['rustc', '--print', 'sysroot']).decode().strip())
164 rust_version = run(['rustc', '--version']).decode().split()[1]
165 text = NoticeText()
166 text.feed((sysroot / 'share/doc/rust/COPYRIGHT-library.html').read_text())
167 components.append({'Name': 'Rust standard library', 'Version': rust_version, 'SourceURL': 'https://doc.rust-lang.org/' + rust_version + '/COPYRIGHT-library.html', 'Notices': [{'Name': 'Copyright notices', 'Text': ''.join(text.parts)}]})
168 components.append({'Name': 'Liberation Fonts', 'SourceURL': 'https://github.com/liberationfonts/liberation-fonts', 'Notices': notices(ROOT / 'internal/slides/fonts/files')})
169 if any(not item['Notices'] for item in components):
170 raise ValueError('an asset dependency lacks its original notice')
171 return {'inputs': inputs(), 'components': components}
172
173
174def main():
175 if sys.argv[1:] not in [[], ['--check']]:
176 raise SystemExit('usage: scripts/credits.py [--check]')
177 checking = sys.argv[1:] == ['--check']
178 assets_file = OUT / 'assets.json'
179 assets = json.loads(assets_file.read_text()) if checking else asset_inventory()
180 if assets['inputs'] != inputs():
181 raise SystemExit('credit asset inventory is stale; run scripts/credits.py')
182 inventory = go_inventory()
183 inventory['components'].extend(assets['components'])
184 inventory['components'].sort(key=lambda item: item['Name'])
185 target = OUT / 'notices.json'
186 if checking:
187 if json.loads(target.read_text()) != inventory:
188 raise SystemExit('embedded credits are stale; run scripts/credits.py')
189 else:
190 assets_file.write_text(json.dumps(assets, indent=2) + '\n')
191 target.write_text(json.dumps(inventory, indent=2) + '\n')
192 print('credits: ' + ('checked' if checking else 'generated'))
193
194
195if __name__ == '__main__':
196 main()
197