"""Read public GitHub repository facts at a fixed commit; execute no downloaded code.""" import argparse from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import re import signal import time from urllib.parse import quote from urllib.request import Request, urlopen def read_json(url): req = Request(url, headers={'User-Agent': 'game-reference-research', 'Accept': 'application/vnd.github+json'}) with urlopen(req, timeout=12) as response: return json.loads(response.read()) def inspect_repository(repository, cache): result = {'repository': repository, 'runtime_tested': False, 'checked_at_utc': datetime.now(timezone.utc).isoformat()} try: base = 'https://api.github.com/repos/' + repository metadata = read_json(base) branch = metadata['default_branch'] commit = read_json(base + '/commits/' + quote(branch, safe='')) sha = commit['sha'] result.update(default_branch=branch, commit=sha, commit_date=commit['commit']['committer']['date'], description=metadata.get('description'), license_metadata=(metadata.get('license') or {}).get('spdx_id', 'NOASSERTION'), archived=metadata['archived'], fork=metadata['fork'], html_url=metadata['html_url'], status='metadata_verified') if cache: tree = read_json(base + '/git/trees/' + sha + '?recursive=1') tree_file = cache / (repository.replace('/', '__') + '.tree.json') content = json.dumps(tree, ensure_ascii=False, indent=2).encode('utf-8') with tree_file.open('xb') as handle: handle.write(content) result.update(tree_truncated=tree.get('truncated', False), tree_entries=len(tree.get('tree', [])), tree_sha256=hashlib.sha256(content).hexdigest()) except Exception as error: result['error'] = type(error).__name__ + ': ' + str(error) result['status'] = 'incomplete' if result.get('commit') else 'unavailable_this_check' return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--repo', action='append', required=True) parser.add_argument('--output', type=Path, required=True, help='New result path; existing evidence is never overwritten') parser.add_argument('--cache', type=Path, help='New tree files outside the delivered library') parser.add_argument('--hard-timeout', type=int, default=120) args = parser.parse_args() if args.output.exists(): parser.error('output already exists') if not 1 <= args.hard_timeout <= 180: parser.error('hard timeout must be between 1 and 180 seconds') if not all(re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', r) for r in args.repo): parser.error('repo must be owner/name') repositories = list(dict.fromkeys(args.repo)) if args.cache: args.cache.mkdir(parents=True, exist_ok=True) if any((args.cache / (r.replace('/', '__') + '.tree.json')).exists() for r in repositories): parser.error('cache would overwrite an existing tree receipt') # No child processes are started. On macOS/Linux this also bounds executor # shutdown, even when an individual network call is slow. if not hasattr(signal, 'SIGALRM'): parser.error('this helper needs Unix SIGALRM for its hard deadline') start = time.monotonic() process = {'pid': os.getpid(), 'pgid': os.getpgid(0), 'children_started': 0, 'start_utc': datetime.now(timezone.utc).isoformat(), 'hard_timeout_seconds': args.hard_timeout} print(json.dumps({'process_started': process}), flush=True) signal.alarm(args.hard_timeout) results = [] with ThreadPoolExecutor(max_workers=4) as executor: jobs = [executor.submit(inspect_repository, r, args.cache) for r in repositories] for job in as_completed(jobs): result = job.result() results.append(result) print(json.dumps({'repository': result['repository'], 'status': result['status']}), flush=True) signal.alarm(0) process['elapsed_seconds'] = round(time.monotonic() - start, 3) report = {'schema_version': 1, 'scope': 'Public metadata and tree only; no install or runtime claim', 'process': process, 'repositories': sorted(results, key=lambda r: r['repository'])} args.output.parent.mkdir(parents=True, exist_ok=True) with args.output.open('x', encoding='utf-8') as handle: json.dump(report, handle, ensure_ascii=False, indent=2) handle.write('\n') return 0 if all(r['status'] == 'metadata_verified' for r in results) else 1 if __name__ == '__main__': raise SystemExit(main())