#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """Explicit app build-content selection and schema-only resource staging. Normal is the existing maintainer/developer build. Source builds deliberately omit prepared libraries; they never need to probe a maintainer input location. """ from contextlib import closing import hashlib import os from pathlib import Path import sqlite3 import tempfile PROFILES = ('normal', 'source') PROFILE_ENV = 'VCC_BUILD_CONTENT_PROFILE' def content_profile(value=None, environ=None): """CLI values override the environment; an unset profile preserves defaults.""" selected = value if value is not None else (os.environ if environ is None else environ).get(PROFILE_ENV, 'normal') if selected not in PROFILES: raise ValueError('Build content profile must be normal or source') return selected def add_content_profile_argument(parser): parser.add_argument('--content-profile', choices=PROFILES, help='App content: normal (default) or source (empty libraries); overrides ' + PROFILE_ENV) def _check_output(output, expected_name, expected_parent): # Preserve macOS's public /tmp and /var spellings without resolving arbitrary # links supplied inside a build directory. No other ancestor link is allowed. aliases = {Path('/tmp'): Path('/private/tmp'), Path('/var'): Path('/private/var')} absolute = output if output.is_absolute() else Path.cwd() / output for parent in absolute.parents: if parent.is_symlink() and not (parent in aliases and parent.resolve() == aliases[parent]): raise ValueError('Build resource destination must not have a linked ancestor directory') if output.name != expected_name or output.parent.name != expected_parent: raise ValueError('Expected a ' + expected_parent + '/' + expected_name + ' build resource destination') if output.is_symlink() or (output.exists() and (not output.is_file() or output.stat().st_nlink != 1)): raise ValueError('Build resource destination must be a regular, unlinked file') if any(Path(str(output) + suffix).exists() or Path(str(output) + suffix).is_symlink() for suffix in ('-wal', '-shm', '-journal')): raise ValueError('Remove SQLite transaction sidecars from this build resource before regenerating it') def atomic_empty_database(output, schema, metadata, content_tables, *, expected_name, expected_parent, application_id=None, user_version, fts_integrity=False): """Validate a new schema-only database before replacing a disposable resource. No source database is accepted. Existing identical resource bytes retain their timestamp. Failed schema/integrity checks leave the previous resource intact. """ output = Path(output) _check_output(output, expected_name, expected_parent) output.parent.mkdir(parents=True, exist_ok=True) descriptor, name = tempfile.mkstemp(prefix='.empty-library-', suffix='.sqlite', dir=output.parent) os.close(descriptor) temporary = Path(name) try: with closing(sqlite3.connect(temporary)) as db: db.execute('PRAGMA page_size=4096') db.execute('PRAGMA foreign_keys=ON') db.executescript(Path(schema).read_text(encoding='utf-8')) db.executemany('INSERT INTO metadata VALUES(?,?)', metadata) if fts_integrity: db.execute("INSERT INTO page_terms(page_terms) VALUES('integrity-check')") db.commit() db.execute('VACUUM') if db.execute('PRAGMA integrity_check').fetchall() != [('ok',)]: raise ValueError('Empty library integrity check failed') if db.execute('PRAGMA foreign_key_check').fetchall(): raise ValueError('Empty library has broken relationships') if db.execute('PRAGMA user_version').fetchone() != (user_version,): raise ValueError('Unsupported empty library schema version') if application_id is not None and db.execute('PRAGMA application_id').fetchone() != (application_id,): raise ValueError('Unsupported empty library application identity') for table in content_tables: # Table names are authored constants, never command-line values. if db.execute('SELECT count(*) FROM "' + table + '"').fetchone() != (0,): raise ValueError('Library schema unexpectedly inserts content') data = temporary.read_bytes() result = dict(bytes=len(data), sha256=hashlib.sha256(data).hexdigest()) os.chmod(temporary, 0o444) _check_output(output, expected_name, expected_parent) if output.is_file() and output.read_bytes() == data: # chmod only a verified regular file; never follow a linked output. os.chmod(output, 0o444) else: os.replace(temporary, output) return result finally: temporary.unlink(missing_ok=True)