#!/usr/bin/env python3 """Reuse an immutable CI checkout's stamp only after a completed, unchanged lease.""" import hashlib import json import os import re from pathlib import Path import stat import sys def workspace_state_input(data): """Retain pnpm project information across clock changes and relocation.""" try: document = json.loads(data) projects = document['projects'] if not isinstance(projects, dict) or not projects: return data if not all(isinstance(key, str) and Path(key).is_absolute() for key in projects): return data origin = Path(os.path.commonpath(projects)) # A normal workspace includes its root project. Unknown layouts stay # byte-sensitive rather than guessing which prefix is the checkout. if not origin.is_absolute() or str(origin) not in projects: return data document['projects'] = {Path(key).relative_to(origin).as_posix(): value for key, value in projects.items()} document.pop('lastValidatedTimestamp', None) return json.dumps(document, sort_keys=True, separators=(',', ':')).encode() except (ValueError, TypeError, KeyError): return data def snapshot(root): digest = hashlib.sha256() times = [] for directory, dirs, files in os.walk(root, followlinks=False): if Path(directory) == root: dirs[:] = [name for name in dirs if name != '.git'] files = [name for name in files if name != '.git'] dirs.sort() for name in sorted(dirs + files): path = Path(directory) / name info = path.lstat() digest.update(str(path.relative_to(root)).encode() + b'\0') digest.update(str(info.st_mode).encode() + b'\0') times.append(info.st_mtime_ns) if stat.S_ISLNK(info.st_mode): link = os.fsencode(os.readlink(path)) digest.update(str(len(link)).encode() + b'\0' + link) elif stat.S_ISREG(info.st_mode): contents = hashlib.sha256() if path.relative_to(root).as_posix() == 'node_modules/.modules.yaml': # pnpm writes a fresh pruning clock in every CI checkout. # It is bookkeeping, not a source or dependency-layout # input. Retain every other byte, mode and link in the key. contents.update(re.sub(rb'(?m)^prunedAt:[^\n]*(?:\n|$)', b'', path.read_bytes())) elif path.relative_to(root).as_posix() == 'node_modules/.pnpm-workspace-state.json': # The checkout lives at SRC regardless of its CI job's # original path. Preserve every relative project and field. contents.update(workspace_state_input(path.read_bytes())) else: with path.open('rb') as source: for block in iter(lambda: source.read(1024 * 1024), b''): contents.update(block) digest.update(contents.digest()) elif not stat.S_ISDIR(info.st_mode): raise OSError('non-file checkout input') digest.update(b'\0') return digest.hexdigest(), times def main(): mode, root_arg, state_arg = sys.argv[1:4] root, state = Path(root_arg), Path(state_arg) pending = state.with_suffix('.pending') if mode == 'prepare': lease = int(sys.argv[4]) sha = os.environ.get('GITHUB_SHA') or os.environ.get('FORGEJO_SHA') try: old = json.loads(state.read_text()) except (OSError, ValueError): old = {} if not isinstance(old, dict): old = {} # A killed or source-mutating command must leave no reusable record. state.unlink(missing_ok=True) pending.unlink(missing_ok=True) if not sha: print(lease, 0) return try: digest, _ = snapshot(root) except OSError: print(lease, 0) return reuse = (old.get('sha') == sha and old.get('digest') == digest and type(old.get('stamp')) is int and 0 < old['stamp'] < lease) stamp = old['stamp'] if reuse else lease pending.write_text(json.dumps({'sha': sha, 'digest': digest, 'stamp': stamp})) print(stamp, int(reuse)) elif mode == 'finish': if len(sys.argv) > 4 and sys.argv[4] != '0': pending.unlink(missing_ok=True) return try: record = json.loads(pending.read_text()) if not isinstance(record, dict): return digest, times = snapshot(root) if digest == record['digest'] and all(t == record['stamp'] * 10**9 for t in times): pending.replace(state) except (OSError, ValueError, KeyError): pass # No cache record means a full fresh stamp on the next lease. finally: pending.unlink(missing_ok=True) else: raise ValueError('expected prepare or finish') if __name__ == '__main__': main()