diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0be2462..8a0b6cf 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -29,14 +29,17 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: path: source/modules/antono2/vkmemalloc + - uses: prantlf/setup-v-action@92f20bea50d2c9931a28c96bb4997a3c7357baf0 # v4 + with: + version: 0.5.2 - name: Validate and resolve tested compatibility id: compat shell: bash working-directory: ${{ github.workspace }} run: | - python source/modules/antono2/vkmemalloc/scripts/test_compatibility.py - python source/modules/antono2/vkmemalloc/scripts/test_doctor.py - python source/modules/antono2/vkmemalloc/scripts/compatibility.py --github-output "$GITHUB_OUTPUT" + v run source/modules/antono2/vkmemalloc/scripts/compatibility.vsh --self-test + v run source/modules/antono2/vkmemalloc/scripts/doctor.vsh --self-test + v run source/modules/antono2/vkmemalloc/scripts/compatibility.vsh --github-output "$GITHUB_OUTPUT" - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: repository: antono2/vulkan @@ -48,6 +51,7 @@ jobs: ref: ${{ steps.compat.outputs.module_memory }} path: source/modules/antono2/memory - uses: prantlf/setup-v-action@92f20bea50d2c9931a28c96bb4997a3c7357baf0 # v4 + if: steps.compat.outputs.v_release != '0.5.2' with: version: ${{ steps.compat.outputs.v_release }} - name: Test setup command routing @@ -97,14 +101,17 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: path: source/modules/antono2/vkmemalloc + - uses: prantlf/setup-v-action@92f20bea50d2c9931a28c96bb4997a3c7357baf0 # v4 + with: + version: 0.5.2 - name: Validate and resolve tested compatibility id: compat shell: bash working-directory: ${{ github.workspace }} run: | - python source/modules/antono2/vkmemalloc/scripts/test_compatibility.py - python source/modules/antono2/vkmemalloc/scripts/test_doctor.py - python source/modules/antono2/vkmemalloc/scripts/compatibility.py --github-output "$GITHUB_OUTPUT" + v run source/modules/antono2/vkmemalloc/scripts/compatibility.vsh --self-test + v run source/modules/antono2/vkmemalloc/scripts/doctor.vsh --self-test + v run source/modules/antono2/vkmemalloc/scripts/compatibility.vsh --github-output "$GITHUB_OUTPUT" - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: repository: antono2/vulkan @@ -116,6 +123,7 @@ jobs: ref: ${{ steps.compat.outputs.module_memory }} path: source/modules/antono2/memory - uses: prantlf/setup-v-action@92f20bea50d2c9931a28c96bb4997a3c7357baf0 # v4 + if: steps.compat.outputs.v_release != '0.5.2' with: version: ${{ steps.compat.outputs.v_release }} - name: Test setup command routing @@ -177,14 +185,17 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: path: source/modules/antono2/vkmemalloc + - uses: prantlf/setup-v-action@92f20bea50d2c9931a28c96bb4997a3c7357baf0 # v4 + with: + version: 0.5.2 - name: Validate and resolve tested compatibility id: compat shell: bash working-directory: ${{ github.workspace }} run: | - python source/modules/antono2/vkmemalloc/scripts/test_compatibility.py - python source/modules/antono2/vkmemalloc/scripts/test_doctor.py - python source/modules/antono2/vkmemalloc/scripts/compatibility.py --github-output "$GITHUB_OUTPUT" + v run source/modules/antono2/vkmemalloc/scripts/compatibility.vsh --self-test + v run source/modules/antono2/vkmemalloc/scripts/doctor.vsh --self-test + v run source/modules/antono2/vkmemalloc/scripts/compatibility.vsh --github-output "$GITHUB_OUTPUT" - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: repository: antono2/vulkan @@ -234,14 +245,17 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: path: source/modules/antono2/vkmemalloc + - uses: prantlf/setup-v-action@92f20bea50d2c9931a28c96bb4997a3c7357baf0 # v4 + with: + version: 0.5.2 - name: Validate and resolve tested compatibility id: compat shell: bash working-directory: ${{ github.workspace }} run: | - python source/modules/antono2/vkmemalloc/scripts/test_compatibility.py - python source/modules/antono2/vkmemalloc/scripts/test_doctor.py - python source/modules/antono2/vkmemalloc/scripts/compatibility.py --github-output "$GITHUB_OUTPUT" + v run source/modules/antono2/vkmemalloc/scripts/compatibility.vsh --self-test + v run source/modules/antono2/vkmemalloc/scripts/doctor.vsh --self-test + v run source/modules/antono2/vkmemalloc/scripts/compatibility.vsh --github-output "$GITHUB_OUTPUT" - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: repository: antono2/vulkan @@ -253,6 +267,7 @@ jobs: ref: ${{ steps.compat.outputs.module_memory }} path: source/modules/antono2/memory - uses: prantlf/setup-v-action@92f20bea50d2c9931a28c96bb4997a3c7357baf0 # v4 + if: steps.compat.outputs.v_release != '0.5.2' with: version: ${{ steps.compat.outputs.v_release }} - name: Verify the declared dependency graph diff --git a/docs/compatibility.md b/docs/compatibility.md index eaab86a..17efddf 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -8,11 +8,11 @@ generated API contents; upstream update workflows deliberately select candidates separately from the tested compiler profiles. Upgrade the manifest and affected VPM declarations together. Run -`python scripts/test_compatibility.py` and the full project CI. Consumer application +`v run scripts/compatibility.vsh --self-test` and the full project CI. Consumer application compilation/runtime checks are also required before publishing a dependency upgrade. The resolver's `--modules PATH` option verifies installed Git tags without fetching. -Run `python scripts/doctor.py --v PATH_TO_V --modules PATH_TO_MODULES` for read-only +Run `v run scripts/doctor.vsh --v PATH_TO_V --modules PATH_TO_MODULES` for read-only compiler/tool/dependency diagnostics. Add `--json` for a support report and `--runtime` for Vulkan device enumeration when Vulkan tools are available. Missing or mismatched prerequisites include a recovery action; diagnostics never repair diff --git a/scripts/compatibility.py b/scripts/compatibility.py deleted file mode 100644 index 4e33944..0000000 --- a/scripts/compatibility.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python3 -"""Resolve tested compiler/native/module profiles and validate VPM declarations.""" -import argparse -import json -from pathlib import Path -import re -import subprocess - - -def resolve(root, profile='stable'): - pins = json.loads((root / 'compatibility.json').read_text()) - if pins.get('schema_version') != 1: - raise ValueError('Unsupported compatibility schema_version') - if 'v_release' in pins and not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', pins['v_release']): - raise ValueError('v_release must be a released compiler version') - upstream = root / 'third_party/upstream.json' - if upstream.is_file() and pins.get('glfw') != json.loads(upstream.read_text())['version']: - raise ValueError('Native GLFW version and compatibility.json disagree') - for key, value in pins.items(): - if key in ['v', 'vc', 'tcc', 'volk', 'generator'] or key.endswith(('_v', '_vc', '_tcc')): - if not re.fullmatch('[0-9a-f]{40}', value): - raise ValueError(f'{key} must be an immutable Git commit') - declared = dict(re.findall(r"'antono2\.([a-z0-9_]+)@([^']+)'", (root / 'v.mod').read_text())) - for name, tag in declared.items(): - if pins.get('modules', {}).get(name) != tag: - raise ValueError(f'v.mod and compatibility.json disagree for {name}') - outputs = {key: value for key, value in pins.items() if isinstance(value, str)} - for name, tag in pins.get('modules', {}).items(): - if not re.fullmatch('[a-z0-9_]+', name) or not re.fullmatch(r'v[0-9]+\.[0-9]+\.[0-9]+(?:-standard)?', tag): - raise ValueError(f'Invalid module pin: {name}={tag}') - outputs['module_' + name] = tag - outputs['selected_v'] = 'master' if profile == 'master' else (pins['v3_v'] if profile == 'v3' else pins.get('v', pins.get('v_release', ''))) - for key, value in outputs.items(): - if not re.fullmatch('[a-z0-9_]+', key) or '\n' in value or '\r' in value: - raise ValueError(f'Unsafe compatibility output: {key}') - return outputs - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1]) - parser.add_argument('--profile', choices=['stable', 'v3', 'master'], default='stable') - parser.add_argument('--github-output', type=Path) - parser.add_argument('--get') - parser.add_argument('--modules', type=Path) - args = parser.parse_args() - outputs = resolve(args.root, args.profile) - if args.modules: - for key, tag in outputs.items(): - if not key.startswith('module_'): - continue - checkout = args.modules / 'antono2' / key[len('module_'):] - def revision(ref): - return subprocess.check_output(['git', '-C', str(checkout), 'rev-parse', '--verify', ref], text=True).strip() - if revision('HEAD') != revision(f'refs/tags/{tag}^{{commit}}'): - raise ValueError(f'Installed module does not match {tag}: {checkout}') - if args.github_output: - with args.github_output.open('a', encoding='utf-8') as output: - for key, value in outputs.items(): - output.write(f'{key}={value}\n') - print(outputs[args.get] if args.get else json.dumps(outputs, indent=2)) - - -if __name__ == '__main__': - main() diff --git a/scripts/compatibility.vsh b/scripts/compatibility.vsh new file mode 100644 index 0000000..01a3558 --- /dev/null +++ b/scripts/compatibility.vsh @@ -0,0 +1,188 @@ +// Resolve tested compiler and module pins and validate the VPM declarations. +import flag +import os +import rand +import x.json2 + +fn name_is_safe(name string) bool { + return name.len > 0 && name.bytes().all((it >= `a` && it <= `z`) || it.is_digit() || it == `_`) +} + +fn release_is_valid(version string) bool { + parts := version.split('.') + return parts.len == 3 && parts.all(it.len > 0 && it.bytes().all(it.is_digit())) +} + +fn manifest(path string) !map[string]json2.Any { + return json2.decode[map[string]json2.Any](os.read_file(path)!) +} + +fn pin_value(pins map[string]json2.Any, key string) string { + value := pins[key] or { return '' } + return value.str() +} + +fn resolve(root string, profile string) !map[string]string { + pins := manifest(os.join_path(root, 'compatibility.json'))! + if (pins['schema_version'] or { json2.Any(0) }).int() != 1 { + return error('Unsupported compatibility schema_version') + } + if 'v_release' in pins && !release_is_valid(pin_value(pins, 'v_release')) { + return error('v_release must be a released compiler version') + } + upstream := os.join_path(root, 'third_party', 'upstream.json') + if os.is_file(upstream) { + native := manifest(upstream)! + if pin_value(pins, 'glfw') != pin_value(native, 'version') { + return error('Native GLFW version and compatibility.json disagree') + } + } + + mut outputs := map[string]string{} + for key, value in pins { + if key in ['v', 'vc', 'tcc', 'volk', 'generator'] || key.ends_with('_v') + || key.ends_with('_vc') || key.ends_with('_tcc') { + commit := value.str() + if commit.len != 40 || !commit.bytes().all(it.is_digit() || (it >= `a` && it <= `f`)) { + return error('${key} must be an immutable Git commit') + } + } + if value is string { + outputs[key] = value + } + } + modules := (pins['modules'] or { json2.Any(map[string]json2.Any{}) }).as_map() + declarations := os.read_file(os.join_path(root, 'v.mod'))!.split("'") + for i := 1; i < declarations.len; i += 2 { + declaration := declarations[i] + if declaration.starts_with('antono2.') && declaration.contains('@') { + name := declaration.all_after('antono2.').all_before('@') + if name_is_safe(name) && pin_value(modules, name) != declaration.all_after('@') { + return error('v.mod and compatibility.json disagree for ${name}') + } + } + } + for name, value in modules { + tag := value.str() + version := if tag.ends_with('-standard') { tag[..tag.len - '-standard'.len] } else { tag } + if !name_is_safe(name) || !version.starts_with('v') || !release_is_valid(version[1..]) { + return error('Invalid module pin: ${name}=${tag}') + } + outputs['module_' + name] = tag + } + outputs['selected_v'] = match profile { + 'stable' { + if 'v' in outputs { outputs['v'] } else { outputs['v_release'] } + } + 'master' { + 'master' + } + 'v3' { + outputs['v3_v'] or { return error('v3 profile requires v3_v') } + } + else { + return error('unknown compatibility profile: ${profile}') + } + } + + for key, value in outputs { + if !name_is_safe(key) || value.contains_any('\r\n') { + return error('Unsafe compatibility output: ${key}') + } + } + return outputs +} + +fn revision(checkout string, ref string) !string { + return os.execute_opt('git -C ${os.quoted_path(checkout)} rev-parse --verify ${os.quoted_path(ref)}')!.output.trim_space() +} + +fn verify_modules(outputs map[string]string, modules string) ! { + for key, tag in outputs { + if !key.starts_with('module_') { + continue + } + checkout := os.join_path(modules, 'antono2', key['module_'.len..]) + if revision(checkout, 'HEAD')! != revision(checkout, 'refs/tags/${tag}^{commit}')! { + return error('Installed module does not match ${tag}: ${checkout}') + } + } +} + +fn expect_invalid(root string, expected string) ! { + resolve(root, 'stable') or { + if !err.msg().contains(expected) { + return error('expected ${expected}, got ${err}') + } + return + } + return error('accepted a fixture that should fail with ${expected}') +} + +fn self_test(root string) ! { + pins := manifest(os.join_path(root, 'compatibility.json'))! + expected := if 'v' in pins { pin_value(pins, 'v') } else { pin_value(pins, 'v_release') } + assert resolve(root, 'stable')!['selected_v'] == expected + assert resolve(root, 'master')!['selected_v'] == 'master' + if 'v3_v' in pins { + assert resolve(root, 'v3')!['selected_v'] == pin_value(pins, 'v3_v') + } + work := os.join_path(os.temp_dir(), 'compatibility ${rand.uuid_v4()}') + os.mkdir(work)! + defer { os.rmdir_all(work) or {} } + os.write_file(os.join_path(work, 'v.mod'), + "Module { dependencies: ['antono2.memory@v99.0.0'] }")! + path := os.join_path(work, 'compatibility.json') + os.write_file(path, '{"schema_version":1,"v":"master"}')! + expect_invalid(work, 'immutable')! + os.write_file(path, '{"schema_version":1,"modules":{"memory":"v1.4.0"}}')! + expect_invalid(work, 'disagree')! + os.write_file(os.join_path(work, 'v.mod'), 'Module {}')! + os.write_file(path, '{"schema_version":1,"v_release":"0.5.2","ci_sdk":"x\\nother=pin"}')! + expect_invalid(work, 'Unsafe compatibility output')! + println('Compatibility profiles and refusal checks passed.') +} + +fn run_cli() ! { + mut parser := flag.new_flag_parser(os.args[1..]) + parser.application('compatibility') + parser.description('Validate and resolve tested build profiles.') + root := parser.string('root', 0, os.dir(@DIR), 'project root') + profile := parser.string('profile', 0, 'stable', 'stable, v3, or master') + output_path := parser.string('github-output', 0, '', 'append pins to this GitHub output file') + key := parser.string('get', 0, '', 'print a single pin') + modules := parser.string('modules', 0, '', 'verify module checkouts in this directory') + test := parser.bool('self-test', 0, false, 'run the profile and refusal fixtures') + if parser.bool('help', `h`, false, 'show help') { + println(parser.usage()) + return + } + if parser.finalize()!.len != 0 { + return error('unexpected positional arguments') + } + if test { + self_test(root)! + return + } + outputs := resolve(root, profile)! + if modules != '' { + verify_modules(outputs, modules)! + } + if output_path != '' { + mut output := os.open_append(output_path)! + defer { output.close() } + for name, value in outputs { + output.writeln('${name}=${value}')! + } + } + if key != '' { + println(outputs[key] or { return error('unknown compatibility output: ${key}') }) + } else { + println(json2.encode(outputs, prettify: true)) + } +} + +run_cli() or { + eprintln(err) + exit(1) +} diff --git a/scripts/doctor.py b/scripts/doctor.py deleted file mode 100644 index cd4c666..0000000 --- a/scripts/doctor.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python3 -"""Read-only build/runtime diagnostics; use --json for a support report.""" -import argparse -import json -import os -from pathlib import Path -import re -import shutil -import subprocess - - -def probe(command, timeout=15): - try: - result = subprocess.run(command, capture_output=True, text=True, errors='replace', timeout=timeout) - return result.returncode == 0, (result.stdout + result.stderr).strip() - except (OSError, subprocess.TimeoutExpired) as error: - return False, str(error) - - -def diagnose(root, compiler=None, modules=None, sdk=None, runtime=False, profile='stable'): - checks = [] - def check(name, passed, detail, action, optional=False): - checks.append({'name': name, 'status': 'pass' if passed else ('warn' if optional else 'fail'), - 'detail': detail, 'action': '' if passed else action}) - try: - pins = json.loads((root / 'compatibility.json').read_text()) - if pins.get('schema_version') != 1: - raise ValueError('Unsupported schema_version') - except (OSError, ValueError) as error: - check('Compatibility manifest', False, str(error), 'Restore compatibility.json from this project revision.') - return {'checks': checks} - declared = dict(re.findall(r"'antono2\.([a-z0-9_]+)@([^']+)'", (root / 'v.mod').read_text())) - disagreement = [name for name, tag in declared.items() if pins.get('modules', {}).get(name) != tag] - check('Declared dependencies', not disagreement, ', '.join(disagreement) or 'Manifest agrees with v.mod', - 'Update compatibility.json and v.mod together; use the tested dependency versions.') - for tool in pins.get('build_tools', ['git', 'cmake']): - location = shutil.which(tool) - check(tool, bool(location), location or 'Not found on PATH', f'Install {tool}, reopen your shell and rerun diagnostics.') - compiler = str(compiler) if compiler else (os.environ.get('VEXE') or shutil.which('v')) - if compiler: - passed, detail = probe([compiler, '-version']) - selected = pins.get('v_release', '') if profile == 'release' else ( - pins.get('v3_v', pins.get('v', '')) if profile == 'v3' else pins.get('v', '')) - expected = selected[:7] if selected else (pins.get('v_release', '') if profile == 'stable' else '') - matches = passed and bool(expected) and expected in detail - check('V compiler', matches, detail, 'Select the tested V compiler from compatibility.json or rerun the setup helper.') - else: - check('V compiler', False, 'No V compiler found', 'Run the project setup helper, or pass --v with the tested compiler path.') - modules = modules or os.environ.get('VMODULES') - if modules: - for name, tag in pins.get('modules', {}).items(): - checkout = Path(modules) / 'antono2' / name - head_ok, head = probe(['git', '-C', str(checkout), 'rev-parse', '--verify', 'HEAD']) - tag_ok, wanted = probe(['git', '-C', str(checkout), 'rev-parse', '--verify', f'refs/tags/{tag}^{{commit}}']) - check('Module ' + name, head_ok and tag_ok and head == wanted, f'{checkout}: expected {tag}', - 'Preserve local changes and use a fresh module/cache directory with the declared releases.') - else: - check('Installed modules', False, 'VMODULES is not set', 'Pass --modules with the module directory used by setup.', optional=True) - sdk = sdk or os.environ.get('VULKAN_SDK') - needs_vulkan = 'ci_sdk' in pins or 'vulkan' in pins.get('modules', {}) - if needs_vulkan and os.name == 'nt': - available = bool(sdk) and (Path(sdk) / 'Lib/vulkan-1.lib').is_file() - check('Vulkan SDK', available, str(sdk or 'Not configured'), 'Install the Vulkan SDK or pass --sdk with its directory.') - if runtime and needs_vulkan: - executable = shutil.which('vulkaninfo') - if not executable and sdk: - candidate = Path(sdk) / ('Bin/vulkaninfo.exe' if os.name == 'nt' else 'bin/vulkaninfo') - if candidate.is_file(): - executable = str(candidate) - passed, detail = probe([executable, '--summary'], timeout=30) if executable else (False, 'vulkaninfo is unavailable') - check('Vulkan devices', passed, detail, 'Install Vulkan runtime tools and a compatible graphics driver; rerun --runtime.', optional=True) - return {'project': root.name, 'platform': os.name, 'profile': profile, 'compatibility': pins, 'checks': checks, - 'hardware_note': 'Device enumeration does not validate hardware video decoding or OpenCL interoperability.'} - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--v', type=Path, help='Tested V compiler executable') - parser.add_argument('--modules', type=Path) - parser.add_argument('--sdk', type=Path) - parser.add_argument('--runtime', action='store_true', help='Also enumerate Vulkan devices, when tools are available') - parser.add_argument('--profile', choices=['stable', 'v3', 'release'], default='stable', help='Compiler profile to diagnose') - parser.add_argument('--json', action='store_true', help='Emit JSON without modifying the environment or caches') - args = parser.parse_args() - report = diagnose(Path(__file__).resolve().parents[1], args.v, args.modules, args.sdk, args.runtime, args.profile) - if args.json: - print(json.dumps(report, indent=2)) - else: - for item in report['checks']: - print(f"{item['status'].upper()}: {item['name']}: {item['detail']}") - if item['action']: - print(' Next: ' + item['action']) - raise SystemExit(1 if any(item['status'] == 'fail' for item in report['checks']) else 0) - - -if __name__ == '__main__': - main() diff --git a/scripts/doctor.vsh b/scripts/doctor.vsh new file mode 100644 index 0000000..dff799d --- /dev/null +++ b/scripts/doctor.vsh @@ -0,0 +1,419 @@ +// Read-only build and runtime diagnostics. Use --json for a support report. +import flag +import os +import rand +import strings +import time +import x.json2 + +const command_timeout = 15 * time.second +const runtime_timeout = 30 * time.second +const probe_interval = 10 * time.millisecond +const require_explicit_v3_pin = false + +struct Options { + compiler string + modules string + sdk string + runtime bool + profile string = 'stable' +} + +struct Check { + name string + status string + detail string + action string +} + +struct Report { + project string + platform string + profile string + compatibility map[string]json2.Any + checks []Check + hardware_note string +} + +struct ProbeResult { + ok bool + detail string +} + +struct Probes { + find fn (string) string = find_executable + run fn (string, []string, time.Duration) ProbeResult = run_probe +} + +fn find_executable(name string) string { + if os.is_abs_path(name) && os.is_file(name) && os.is_executable(name) { + return name + } + path := os.find_abs_path_of_executable(name) or { return '' } + return if os.is_file(path) && os.is_executable(path) { path } else { '' } +} + +fn run_probe(executable string, args []string, timeout time.Duration) ProbeResult { + path := find_executable(executable) + if path == '' { + return ProbeResult{ + detail: 'Executable unavailable: ${executable}' + } + } + mut child := os.new_process(path) + child.set_args(args) + child.set_redirect_stdio() + child.run() + defer { child.close() } + mut stdout := strings.new_builder(256) + mut stderr := strings.new_builder(256) + timer := time.new_stopwatch() + for { + live := child.is_alive() + out := child.stdout_read() + err := child.stderr_read() + stdout.write_string(out) + stderr.write_string(err) + if !live && out == '' && err == '' { + child.wait() + break + } + if timer.elapsed() >= timeout { + if live { + child.signal_kill() + // wait() reaps a killed POSIX child only from a running status. + child.status = .running + child.wait() + } + return ProbeResult{ + detail: 'Timed out after ${timeout}: ${executable}' + } + } + if out == '' && err == '' { + time.sleep(probe_interval) + } + } + detail := (stdout.str() + stderr.str()).replace('\r\n', '\n').trim_space() + return ProbeResult{ + ok: child.code == 0 + detail: if detail == '' { child.err } else { detail } + } +} + +fn make_check(name string, passed bool, detail string, action string, optional bool) Check { + return Check{ + name: name + status: if passed { + 'pass' + } else if optional { + 'warn' + } else { + 'fail' + } + detail: detail + action: if passed { '' } else { action } + } +} + +fn load_pins(root string) !map[string]json2.Any { + pins := + json2.decode[map[string]json2.Any](os.read_file(os.join_path(root, 'compatibility.json'))!)! + version := pins['schema_version'] or { return error('Missing schema_version') } + if version.int() != 1 { + return error('Unsupported schema_version') + } + return pins +} + +fn pin(pins map[string]json2.Any, name string) string { + value := pins[name] or { return '' } + return value.str() +} + +fn expected_compiler(pins map[string]json2.Any, profile string) string { + selected := match profile { + 'release' { + pin(pins, 'v_release') + } + 'v3' { + if 'v3_v' in pins || require_explicit_v3_pin { + pin(pins, 'v3_v') + } else { + pin(pins, 'v') + } + } + else { + pin(pins, 'v') + } + } + + if selected == '' && profile == 'stable' { + return pin(pins, 'v_release') + } + return selected[..if selected.len < 7 { + selected.len + } else { + 7 + }] +} + +fn mismatched_modules(root string, pins map[string]json2.Any) ![]string { + declarations := os.read_file(os.join_path(root, 'v.mod'))!.split("'") + mut declared := map[string]string{} + for i := 1; i < declarations.len; i += 2 { + value := declarations[i] + if value.starts_with('antono2.') && value.contains('@') { + name := value.all_after('antono2.').all_before('@') + tag := value.all_after('@') + if name != '' && tag != '' && name.bytes().all((it >= `a` && it <= `z`) + || it.is_digit() || it == `_`) { + declared[name] = tag + } + } + } + return declared.keys().filter(declared[it] != pin(pins, it)) +} + +fn diagnose(root string, options Options, probes Probes) Report { + pins := load_pins(root) or { + return Report{ + checks: [ + make_check('Compatibility manifest', false, err.msg(), + 'Restore compatibility.json from this project revision.', false), + ] + } + } + module_pins := (pins['modules'] or { json2.Any(map[string]json2.Any{}) }).as_map() + mut checks := []Check{} + disagreement := mismatched_modules(root, module_pins) or { + checks << make_check('Declared dependencies', false, err.msg(), + 'Restore v.mod from this project revision.', false) + []string{} + } + if checks.len == 0 { + checks << make_check('Declared dependencies', disagreement.len == 0, if disagreement.len == 0 { + 'Manifest agrees with v.mod' + } else { + disagreement.join(', ') + }, 'Update compatibility.json and v.mod together; use the tested dependency versions.', + false) + } + tools := + (pins['build_tools'] or { json2.Any([json2.Any('git'), json2.Any('cmake')]) }).as_array() + for tool in tools { + name := tool.str() + location := probes.find(name) + checks << make_check(name, location != '', if location == '' { + 'Not found on PATH' + } else { + location + }, 'Install ${name}, reopen your shell and rerun diagnostics.', false) + } + + if options.compiler == '' { + checks << make_check('V compiler', false, 'No V compiler found', + 'Run the project setup helper, or pass --v with the tested compiler path.', false) + } else { + version := probes.run(options.compiler, ['-version'], command_timeout) + expected := expected_compiler(pins, options.profile) + action := if require_explicit_v3_pin && expected == '' { + 'Configure the requested compiler profile in compatibility.json.' + } else { + 'Select the tested V compiler from compatibility.json; pass --v with its executable path.' + } + checks << make_check('V compiler', version.ok && expected != '' + && version.detail.contains(expected), version.detail, action, false) + } + + if options.modules == '' { + checks << make_check('Installed modules', false, 'VMODULES is not set', + 'Pass --modules with the module directory used by setup.', true) + } else { + for name, value in module_pins { + checkout := os.join_path(options.modules, 'antono2', name) + tag := value.str() + git_args := ['-C', checkout, 'rev-parse', '--verify'] + head := probes.run('git', array_with_arg(git_args, 'HEAD'), command_timeout) + wanted := probes.run('git', array_with_arg(git_args, 'refs/tags/${tag}^{commit}'), + command_timeout) + checks << make_check('Module ' + name, head.ok && wanted.ok + && head.detail == wanted.detail, '${checkout}: expected ${tag}', + 'Preserve local changes and use a fresh module/cache directory with the declared releases.', + false) + } + } + + needs_vulkan := 'ci_sdk' in pins || 'vulkan' in module_pins + $if windows { + if needs_vulkan { + available := options.sdk != '' + && os.is_file(os.join_path(options.sdk, 'Lib', 'vulkan-1.lib')) + checks << make_check('Vulkan SDK', available, if options.sdk == '' { + 'Not configured' + } else { + options.sdk + }, 'Install the Vulkan SDK or pass --sdk with its directory.', false) + } + } + if options.runtime && needs_vulkan { + mut executable := probes.find('vulkaninfo') + if executable == '' && options.sdk != '' { + $if windows { + executable = probes.find(os.join_path(options.sdk, 'Bin', 'vulkaninfo.exe')) + } $else { + executable = probes.find(os.join_path(options.sdk, 'bin', 'vulkaninfo')) + } + } + result := if executable == '' { + ProbeResult{ + detail: 'vulkaninfo is unavailable' + } + } else { + probes.run(executable, ['--summary'], runtime_timeout) + } + checks << make_check('Vulkan devices', result.ok, result.detail, + 'Install Vulkan runtime tools and a compatible graphics driver; rerun --runtime.', true) + } + return Report{ + project: os.file_name(root) + platform: if os.user_os() == 'windows' { 'nt' } else { 'posix' } + profile: options.profile + compatibility: pins + checks: checks + hardware_note: 'Device enumeration does not validate hardware video decoding or OpenCL interoperability.' + } +} + +fn array_with_arg(args []string, trailing string) []string { + mut complete := args.clone() + complete << trailing + return complete +} + +fn self_test() ! { + root := os.join_path(os.temp_dir(), 'doctor ' + rand.uuid_v4()) + os.mkdir(root)! + defer { os.rmdir_all(root) or {} } + manifest := os.join_path(root, 'compatibility.json') + declarations := os.join_path(root, 'v.mod') + pins := '{"schema_version":1,"v":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","modules":{"memory":"v1.4.0"},"build_tools":["git"]}' + contents := "Module { dependencies: ['antono2.memory@v1.4.0'] }" + os.write_file(manifest, pins)! + os.write_file(declarations, contents)! + missing := diagnose(root, Options{}, Probes{ + find: fn (_ string) string { + return '' + } + }) + failed := missing.checks.filter(it.status == 'fail') + assert failed.map(it.name) == ['git', 'V compiler'] + assert failed.all(it.action != '') + assert os.read_file(manifest)! == pins + assert os.read_file(declarations)! == contents + assert os.ls(root)!.len == 2 + + os.write_file(declarations, contents.replace('v1.4.0', 'v99.0.0'))! + known := Probes{ + find: fn (name string) string { + return name + } + run: fn (_ string, _ []string, _ time.Duration) ProbeResult { + return ProbeResult{ + ok: true + detail: 'V bbbbbbb' + } + } + } + wrong := diagnose(root, Options{ compiler: 'fixture-v' }, known) + assert wrong.checks.filter(it.status == 'fail').map(it.name) == [ + 'Declared dependencies', + 'V compiler', + ] + os.write_file(declarations, contents)! + os.write_file(manifest, pins.replace('"modules"', + '"v3_v":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","modules"'))! + assert diagnose(root, Options{ compiler: 'fixture-v', profile: 'v3' }, known).checks.filter(it.status == 'fail').len == 0 + assert diagnose(root, Options{ compiler: 'fixture-v', profile: 'release' }, known).checks.filter(it.status == 'fail').map(it.name) == [ + 'V compiler', + ] + assert expected_compiler(json2.decode[map[string]json2.Any](pins)!, 'v3') == if require_explicit_v3_pin { + '' + } else { + 'aaaaaaa' + } + + // Exercise the real process plumbing with the current executable. + child := run_probe(os.executable(), ['--probe-fixture'], command_timeout) + assert child.ok && child.detail == 'stdout\nstderr' + timed := run_probe(os.executable(), ['--probe-fixture', 'wait'], 100 * time.millisecond) + assert !timed.ok && timed.detail.starts_with('Timed out') + println('Build and runtime diagnostic checks passed.') +} + +fn environment_or(option string, name string) string { + return if option == '' { os.getenv(name) } else { option } +} + +fn run_cli() ! { + mut parser := flag.new_flag_parser(os.args[1..]) + parser.application('doctor') + parser.description('Check compiler, native tools and runtime availability.') + explicit_compiler := parser.string('v', 0, '', 'tested V compiler executable') + modules := parser.string('modules', 0, '', 'module directory') + sdk := parser.string('sdk', 0, '', 'Vulkan SDK directory') + profile := parser.string('profile', 0, 'stable', 'stable, v3, or release') + runtime := parser.bool('runtime', 0, false, 'enumerate Vulkan devices when tools are available') + json_output := parser.bool('json', 0, false, 'write a JSON support report') + self_test_only := parser.bool('self-test', 0, false, 'run the diagnostic fixtures') + if parser.bool('help', `h`, false, 'show help') { + println(parser.usage()) + return + } + if parser.finalize()!.len != 0 || profile !in ['stable', 'v3', 'release'] { + return error_with_code('Expected --profile stable, v3, or release. See --help.', 2) + } + if self_test_only { + self_test()! + return + } + compiler := environment_or(explicit_compiler, 'VEXE') + report := diagnose(os.dir(@DIR), Options{ + compiler: if compiler == '' { find_executable('v') } else { compiler } + modules: environment_or(modules, 'VMODULES') + sdk: environment_or(sdk, 'VULKAN_SDK') + profile: profile + runtime: runtime + }, Probes{}) + if json_output { + if report.project == '' { + println(json2.encode({ + 'checks': report.checks + }, prettify: true)) + } else { + println(json2.encode(report, prettify: true)) + } + } else { + for check in report.checks { + println('${check.status.to_upper()}: ${check.name}: ${check.detail}') + if check.action != '' { + println(' Next: ${check.action}') + } + } + } + if report.checks.any(it.status == 'fail') { + exit(1) + } +} + +if os.args.len >= 2 && os.args[1] == '--probe-fixture' { + if os.args.len == 3 { + time.sleep(3 * time.second) + } + println('stdout') + eprintln('stderr') + exit(0) +} +run_cli() or { + eprintln(err) + exit(if err.code() == 2 { 2 } else { 1 }) +} diff --git a/scripts/test_compatibility.py b/scripts/test_compatibility.py deleted file mode 100644 index 2829ea6..0000000 --- a/scripts/test_compatibility.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Upgrades must keep declarations and immutable compiler pins in agreement.""" -import json -from pathlib import Path -import shutil -import tempfile -import unittest -from compatibility import resolve - - -class CompatibilityChecks(unittest.TestCase): - def test_project_profile(self): - root = Path(__file__).resolve().parents[1] - pins = json.loads((root / 'compatibility.json').read_text()) - values = resolve(root) - self.assertEqual(values['selected_v'], pins.get('v', pins.get('v_release', ''))) - if 'v3_v' in pins: - self.assertEqual(resolve(root, 'v3')['selected_v'], pins['v3_v']) - self.assertEqual(resolve(root, 'master')['selected_v'], 'master') - - def test_mutable_compiler_and_disagreement_rejected(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - source = Path(__file__).resolve().parents[1] - shutil.copyfile(source / 'v.mod', root / 'v.mod') - pins = json.loads((source / 'compatibility.json').read_text()) - pins['v'] = 'master' - (root / 'compatibility.json').write_text(json.dumps(pins)) - with self.assertRaisesRegex(ValueError, 'immutable'): - resolve(root) - del pins['v'] - (root / 'v.mod').write_text("Module { dependencies: ['antono2.memory@v99.0.0'] }") - pins['modules']['memory'] = 'v1.4.0' - (root / 'compatibility.json').write_text(json.dumps(pins)) - with self.assertRaisesRegex(ValueError, 'disagree'): - resolve(root) - - -if __name__ == '__main__': - unittest.main() diff --git a/scripts/test_doctor.py b/scripts/test_doctor.py deleted file mode 100644 index ba63017..0000000 --- a/scripts/test_doctor.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Diagnostics must identify mismatches without repairing or changing caches.""" -import json -from pathlib import Path -import tempfile -import unittest -from unittest.mock import patch -from doctor import diagnose - - -class DoctorChecks(unittest.TestCase): - def fixture(self, root): - (root / 'compatibility.json').write_text(json.dumps({'schema_version': 1, - 'v': 'a' * 40, 'modules': {'memory': 'v1.4.0'}, 'build_tools': ['git']})) - (root / 'v.mod').write_text("Module { dependencies: ['antono2.memory@v1.4.0'] }") - - def test_missing_tools_are_actionable_and_read_only(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - self.fixture(root) - before = {p.name: p.read_bytes() for p in root.iterdir()} - with patch('doctor.shutil.which', return_value=None), patch.dict('os.environ', {}, clear=True): - report = diagnose(root) - failed = [item for item in report['checks'] if item['status'] == 'fail'] - self.assertEqual({item['name'] for item in failed}, {'git', 'V compiler'}) - self.assertTrue(all(item['action'] for item in failed)) - self.assertEqual(before, {p.name: p.read_bytes() for p in root.iterdir()}) - - def test_wrong_compiler_and_dependency_are_reported(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - self.fixture(root) - (root / 'v.mod').write_text("Module { dependencies: ['antono2.memory@v99.0.0'] }") - with patch('doctor.shutil.which', return_value='git'), patch('doctor.probe', return_value=(True, 'V wrong-revision')): - report = diagnose(root, compiler='fixture-v') - failed = {item['name'] for item in report['checks'] if item['status'] == 'fail'} - self.assertIn('V compiler', failed) - self.assertIn('Declared dependencies', failed) - - def test_v3_compiler_is_checked_against_its_own_profile(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - self.fixture(root) - pins = json.loads((root / 'compatibility.json').read_text()) - pins['v3_v'] = 'b' * 40 - (root / 'compatibility.json').write_text(json.dumps(pins)) - with patch('doctor.shutil.which', return_value='git'), patch('doctor.probe', return_value=(True, 'V bbbbbbb')): - release = diagnose(root, compiler='fixture-v') - v3 = diagnose(root, compiler='fixture-v', profile='v3') - unsupported = diagnose(root, compiler='fixture-v', profile='release') - self.assertEqual(next(item for item in release['checks'] if item['name'] == 'V compiler')['status'], 'fail') - self.assertEqual(next(item for item in v3['checks'] if item['name'] == 'V compiler')['status'], 'pass') - self.assertEqual(next(item for item in unsupported['checks'] if item['name'] == 'V compiler')['status'], 'fail') - - -if __name__ == '__main__': - unittest.main()