diff --git a/.github/workflows/windows-setup.yml b/.github/workflows/windows-setup.yml index f50b9bf..edc63e3 100644 --- a/.github/workflows/windows-setup.yml +++ b/.github/workflows/windows-setup.yml @@ -22,30 +22,13 @@ jobs: version: 0.5.2 - name: Validate and resolve tested compatibility id: compat - shell: bash - working-directory: ${{ github.workspace }} - run: | - v run "checkout with spaces/scripts/compatibility.vsh" --self-test - v run "checkout with spaces/scripts/doctor.vsh" --self-test - v run "checkout with spaces/scripts/compatibility.vsh" --github-output "$GITHUB_OUTPUT" + working-directory: checkout with spaces + run: v run scripts/check_demo_release.vsh compatibility - name: Install CI Vulkan runtime uses: antono2/vulkan/.github/actions/setup-vulkan-ci@04620525bab9fd843ad3b9046171aaff4dfe3d3c with: sdk-version: ${{ steps.compat.outputs.ci_sdk }} artifact-tag: ${{ steps.compat.outputs.ci_runtime }} - - name: Exercise the documented PowerShell bootstrap - shell: powershell + - name: Exercise the Windows bootstrap and V demo setup working-directory: checkout with spaces - run: | - ./scripts/test_windows_setup.ps1 - $Cache = Join-Path $env:RUNNER_TEMP 'ImGui compiler with spaces' - ./scripts/setup_windows.ps1 -Check -CacheDirectory $Cache - if (Test-Path $Cache) { throw 'Read-only check created the compiler cache' } - ./scripts/setup_windows.ps1 -CacheDirectory $Cache - ./scripts/setup_windows.ps1 -CacheDirectory $Cache - ./scripts/setup_windows.ps1 -CacheDirectory $Cache -PrepareOnly - foreach ($File in @('v_imgui_demo.exe', 'vimgui.dll', 'glfw3.dll')) { - $Artifact = Join-Path 'build\windows-demo' $File - if (-not (Test-Path $Artifact)) { throw "Missing demo artifact: $File" } - } - ./scripts/smoke_windows_demo.ps1 + run: v run scripts/check_windows_setup.vsh "$env:RUNNER_TEMP\ImGui compiler with spaces" diff --git a/QUICKSTART.md b/QUICKSTART.md index ae47df8..cce2dbb 100644 --- a/QUICKSTART.md +++ b/QUICKSTART.md @@ -66,12 +66,19 @@ From ordinary 64-bit PowerShell in the checkout, run: powershell -ExecutionPolicy Bypass -File scripts\setup_windows.ps1 ``` -The helper discovers Visual Studio x64 tools and builds the tested upstream V -compiler in a versioned cache, so a separately installed V compiler is optional. -It prepares isolated V modules, downloads GLFW 3.4 through CMake, checks out the -tested demo and builds it. Use `-Run` to launch after building, `-Check` for -read-only prerequisite checks, or `-PrepareOnly` to prepare only the compiler. -`-CacheDirectory` chooses another compiler-cache location. Existing checkouts +The PowerShell bootstrap discovers Visual Studio x64 tools and builds the +tested upstream V compiler in a versioned cache. V then installs isolated +modules, downloads GLFW 3.4 through CMake, checks out the tested demo and +builds it. + +| Option | Effect | +| --- | --- | +| `-Run` | Launch the demo after building. | +| `-Check` | Check native prerequisites without creating a compiler cache. | +| `-PrepareOnly` | Prepare the compiler without building the demo. | +| `-CacheDirectory PATH` | Select a compiler-cache location. | + +Existing checkouts with local changes or wrong revisions are rejected rather than reset. Native GPU rendering still requires a Vulkan-capable driver and desktop session. @@ -81,6 +88,10 @@ After building, check rendering and clean shutdown with a bounded 60-frame run: powershell -ExecutionPolicy Bypass -File scripts\smoke_windows_demo.ps1 ``` +If your shell already has V, use `v run scripts/smoke_windows_demo.vsh` +directly. Run it with `--help` for the demo directory, frame count, and +timeout options. The smoke check saves stdout and stderr beside the demo. + Windows CI uses a software Vulkan driver for this smoke test; it does not establish support for every physical GPU. diff --git a/scripts/check_windows_setup.vsh b/scripts/check_windows_setup.vsh new file mode 100644 index 0000000..33655f5 --- /dev/null +++ b/scripts/check_windows_setup.vsh @@ -0,0 +1,38 @@ +// Exercise the documented bootstrap and repeat installs in a checkout with spaces. +import os +import tooling + +fn bootstrap_script(script string, args []string) ! { + mut invocation := ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script] + invocation << args + tooling.command('powershell.exe', invocation)! +} + +fn run(args []string) ! { + if args.len != 1 || args[0] == '' { + return error('Usage: v run scripts/check_windows_setup.vsh COMPILER_CACHE') + } + cache := os.abs_path(args[0]) + os.chdir(os.dir(@DIR))! + bootstrap_script('scripts/test_windows_setup.ps1', [])! + bootstrap_script('scripts/setup_windows.ps1', ['-CacheDirectory', cache, '-Check'])! + if os.exists(cache) { + return error('Read-only check created the compiler cache: ${cache}') + } + bootstrap_script('scripts/setup_windows.ps1', ['-CacheDirectory', cache])! + bootstrap_script('scripts/setup_windows.ps1', ['-CacheDirectory', cache])! + bootstrap_script('scripts/setup_windows.ps1', ['-CacheDirectory', cache, '-PrepareOnly'])! + for name in ['v_imgui_demo.exe', 'vimgui.dll', 'glfw3.dll'] { + artifact := os.join_path('build', 'windows-demo', name) + if !os.is_file(artifact) { + return error('Missing demo artifact: ${artifact}') + } + } + // Keep testing the original entry point as well as its new V implementation. + bootstrap_script('scripts/smoke_windows_demo.ps1', [])! +} + +run(os.args[1..]) or { + eprintln(err) + exit(1) +} diff --git a/scripts/setup_windows.ps1 b/scripts/setup_windows.ps1 index 809aca8..4388075 100644 --- a/scripts/setup_windows.ps1 +++ b/scripts/setup_windows.ps1 @@ -59,47 +59,25 @@ Get-WindowsSetupCheckout 'https://github.com/vlang/v.git' $Pins.v $VDirectory Get-WindowsSetupCheckout 'https://github.com/vlang/vc.git' $Pins.vc (Join-Path $VDirectory 'vc') Get-WindowsSetupCheckout 'https://github.com/vlang/tccbin.git' $Pins.tcc (Join-Path $VDirectory 'thirdparty\tcc') $VExecutable = Join-Path $VDirectory 'v.exe' -if (-not (Test-Path -LiteralPath $VExecutable)) { - Push-Location $VDirectory - # Use the pinned bootstrap compiler, regardless of unrelated Clang/GCC - # installations on PATH. The demo itself is compiled with MSVC below. - try { Invoke-WindowsSetupCommand (Join-Path $VDirectory 'makev.bat') @('-tcc', '--local') } finally { Pop-Location } -} -$env:V_BIN = $VExecutable -$env:Path = "$VDirectory;$(Join-Path $env:VULKAN_SDK 'Bin');$env:Path" -if ($PrepareOnly) { - Write-Host "Prepared upstream V compiler: $VExecutable" - return -} -# Keep VPM staging and module installs on the checkout's drive, even when the -# compiler cache or Windows TEMP is elsewhere. The user's VPM directory is retained. -$BuildDirectory = Join-Path $ProjectDirectory 'build' -$env:VMODULES = Join-Path $BuildDirectory 'windows-modules' -$env:VTMP = Join-Path (Join-Path $BuildDirectory '.vtmp') ([Guid]::NewGuid().ToString('N').Substring(0, 8)) -New-Item -ItemType Directory -Force -Path $env:VMODULES, $env:VTMP | Out-Null -$ExistingCount = $env:GIT_CONFIG_COUNT -$Count = 0 -if ($ExistingCount -and (-not [int]::TryParse($ExistingCount, [ref]$Count) -or $Count -lt 0)) { - throw 'GIT_CONFIG_COUNT must be a nonnegative integer.' -} -$SavedGitEnvironment = @{} -foreach ($Name in @('GIT_CONFIG_COUNT', "GIT_CONFIG_KEY_$Count", "GIT_CONFIG_VALUE_$Count")) { - $SavedGitEnvironment[$Name] = [Environment]::GetEnvironmentVariable($Name, 'Process') -} -Push-Location $ProjectDirectory +$PreviousVexe = $env:VEXE try { - [Environment]::SetEnvironmentVariable("GIT_CONFIG_KEY_$Count", 'core.longpaths', 'Process') - [Environment]::SetEnvironmentVariable("GIT_CONFIG_VALUE_$Count", 'true', 'Process') - $env:GIT_CONFIG_COUNT = ($Count + 1).ToString() - Install-WindowsSetupModules $ProjectDirectory $env:VMODULES @{} - Invoke-WindowsSetupCommand $VExecutable @('-cc', 'msvc', 'run', 'scripts/check_installed_deps.vsh') - Invoke-WindowsSetupCommand $VExecutable @('-old-compiler', '-check-syntax', 'imgui.v') - $Options = @('-cc', 'msvc', 'run', 'scripts/run_demo.vsh') - if (-not $Run) { $Options += '--build-only' } + # A parent V script can export VEXE pointing at a different compiler and vlib. + $env:VEXE = $null + if (-not (Test-Path -LiteralPath $VExecutable)) { + Push-Location $VDirectory + # Use the pinned TCC checkout to bootstrap V before the MSVC demo build. + try { Invoke-WindowsSetupCommand (Join-Path $VDirectory 'makev.bat') @('-tcc', '--local') } finally { Pop-Location } + } + $env:VEXE = $VExecutable + $env:V_BIN = $VExecutable + $env:Path = "$VDirectory;$(Join-Path $env:VULKAN_SDK 'Bin');$env:Path" + if ($PrepareOnly) { + Write-Host "Prepared upstream V compiler: $VExecutable" + return + } + $Options = @('-cc', 'msvc', 'run', (Join-Path $PSScriptRoot 'setup_windows_demo.vsh')) + if ($Run) { $Options += '--run' } Invoke-WindowsSetupCommand $VExecutable $Options } finally { - Pop-Location - foreach ($Name in $SavedGitEnvironment.Keys) { - [Environment]::SetEnvironmentVariable($Name, $SavedGitEnvironment[$Name], 'Process') - } + $env:VEXE = $PreviousVexe } diff --git a/scripts/setup_windows_demo.vsh b/scripts/setup_windows_demo.vsh new file mode 100644 index 0000000..c5a4794 --- /dev/null +++ b/scripts/setup_windows_demo.vsh @@ -0,0 +1,66 @@ +// Once Git, the Vulkan SDK, MSVC and V are ready, build the pinned Windows demo. +import os +import rand +import strconv +import tooling + +const usage = 'Usage: v run scripts/setup_windows_demo.vsh [--run]' +// Keep the scratch component short for the Windows C compiler and linker. +const scratch_id_length = 8 + +fn allow_git_long_paths() ! { + configured := os.getenv('GIT_CONFIG_COUNT') + count := if configured == '' { + 0 + } else { + strconv.atoi(configured) or { return error('GIT_CONFIG_COUNT must be a nonnegative integer.') } + } + if count < 0 || count == max_int { + return error('GIT_CONFIG_COUNT must be a nonnegative integer.') + } + os.setenv('GIT_CONFIG_KEY_${count}', 'core.longpaths', true) + os.setenv('GIT_CONFIG_VALUE_${count}', 'true', true) + os.setenv('GIT_CONFIG_COUNT', (count + 1).str(), true) +} + +fn run(args []string) ! { + if args in [['-h'], ['--help']] { + println(usage) + return + } + if args.len > 0 && args != ['--run'] { + return error(usage) + } + if os.user_os() != 'windows' { + return error('Windows demo setup requires Windows and the MSVC x64 toolchain.') + } + allow_git_long_paths()! + root := os.dir(@DIR) + build := os.join_path(root, 'build') + modules := os.join_path(build, 'windows-modules') + scratch_parent := os.join_path(build, '.vtmp') + os.mkdir_all(scratch_parent)! + scratch := os.join_path(scratch_parent, rand.uuid_v4()[..scratch_id_length]) + os.mkdir(scratch)! + defer { + os.rmdir_all(scratch) or { eprintln('Could not remove the build scratch directory: ${err}') } + } + // Keep generated files on the checkout drive and leave the user's VPM cache alone. + os.setenv('VMODULES', modules, true) + os.setenv('VTMP', scratch, true) + os.chdir(root)! + tooling.prepare_pinned_modules(root, modules)! + compiler := tooling.compiler() + tooling.command(compiler, ['-cc', 'msvc', 'run', 'scripts/check_installed_deps.vsh'])! + tooling.command(compiler, ['-old-compiler', '-check-syntax', 'imgui.v'])! + mut options := ['-cc', 'msvc', 'run', 'scripts/run_demo.vsh'] + if args.len == 0 { + options << '--build-only' + } + tooling.command(compiler, options)! +} + +run(os.args[1..]) or { + eprintln(err) + exit(1) +} diff --git a/scripts/smoke_windows_demo.ps1 b/scripts/smoke_windows_demo.ps1 index 2cf9a09..0b2d036 100644 --- a/scripts/smoke_windows_demo.ps1 +++ b/scripts/smoke_windows_demo.ps1 @@ -1,34 +1,30 @@ -# Renders a bounded GLFW/Vulkan demo and checks its exit status and diagnostics. +# Compatibility entry point for the V smoke check. [CmdletBinding()] param( [string]$DemoDirectory = '', - [ValidateRange(1, 10000)][int]$Frames = 60, - [ValidateRange(1, 300)][int]$TimeoutSeconds = 60 + [int]$Frames, + [int]$TimeoutSeconds, + [string]$CacheDirectory = '' ) $ErrorActionPreference = 'Stop' -if (-not $DemoDirectory) { $DemoDirectory = Join-Path (Split-Path -Parent $PSScriptRoot) 'build\windows-demo' } -$DemoDirectory = [IO.Path]::GetFullPath($DemoDirectory) -$Executable = Join-Path $DemoDirectory 'v_imgui_demo.exe' -if (-not (Test-Path -LiteralPath $Executable)) { throw "Build the demo first with scripts\setup_windows.ps1: $Executable" } -$OutputLog = Join-Path $DemoDirectory 'smoke-stdout.log' -$ErrorLog = Join-Path $DemoDirectory 'smoke-stderr.log' -$PreviousFrames = $env:VIMGUI_SMOKE_FRAMES +$Compiler = $env:V_BIN +if (-not $Compiler) { + $Installed = Get-Command v.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($Installed) { $Compiler = $Installed.Source } +} +if (-not $Compiler) { + & (Join-Path $PSScriptRoot 'setup_windows.ps1') -PrepareOnly -CacheDirectory $CacheDirectory + $Compiler = $env:V_BIN +} +$Arguments = @('run', (Join-Path $PSScriptRoot 'smoke_windows_demo.vsh')) +if ($DemoDirectory) { $Arguments += @('--demo-directory', $DemoDirectory) } +if ($PSBoundParameters.ContainsKey('Frames')) { $Arguments += @('--frames', $Frames.ToString()) } +if ($PSBoundParameters.ContainsKey('TimeoutSeconds')) { $Arguments += @('--timeout-seconds', $TimeoutSeconds.ToString()) } +$PreviousVexe = $env:VEXE try { - $env:VIMGUI_SMOKE_FRAMES = $Frames.ToString() - $DemoProcess = Start-Process -FilePath $Executable -WorkingDirectory $DemoDirectory -WindowStyle Hidden -PassThru -RedirectStandardOutput $OutputLog -RedirectStandardError $ErrorLog - # Retain the process handle before exit; Windows PowerShell 5 otherwise - # sometimes loses ExitCode when Start-Process redirects output. - $null = $DemoProcess.Handle - if (-not $DemoProcess.WaitForExit($TimeoutSeconds * 1000)) { - Stop-Process -Id $DemoProcess.Id -Force - throw "Windows demo rendering timed out; inspect $OutputLog and $ErrorLog." - } - $Diagnostics = (Get-Content -LiteralPath $OutputLog, $ErrorLog -Raw) -join "`n" - if ($Diagnostics) { Write-Host $Diagnostics } - if ($DemoProcess.ExitCode -ne 0 -or $Diagnostics -match '(?i)VUID-|validation error|segmentation|assert|fatal') { - throw "Windows demo rendering failed (exit $($DemoProcess.ExitCode)); inspect the smoke logs." - } - Write-Host "Windows GLFW/Vulkan demo rendered and shut down after $Frames frames." + $env:VEXE = $Compiler + & $Compiler @Arguments + if ($LASTEXITCODE -ne 0) { throw "Demo smoke check failed with exit code $LASTEXITCODE." } } finally { - $env:VIMGUI_SMOKE_FRAMES = $PreviousFrames + $env:VEXE = $PreviousVexe } diff --git a/scripts/smoke_windows_demo.vsh b/scripts/smoke_windows_demo.vsh new file mode 100644 index 0000000..93130a5 --- /dev/null +++ b/scripts/smoke_windows_demo.vsh @@ -0,0 +1,100 @@ +// Render a bounded number of frames and preserve the demo's diagnostics. +import flag +import os +import time + +const default_frames = 60 +const max_frames = 10_000 +const default_timeout_seconds = 60 +const max_timeout_seconds = 300 +const output_poll_interval = 20 * time.millisecond +const render_failures = ['vuid-', 'validation error', 'segmentation', 'assert', 'fatal'] + +fn smoke(directory string, frames int, timeout time.Duration) ! { + player := os.join_path(directory, 'v_imgui_demo.exe') + if !os.is_file(player) { + return error('Build the demo first with scripts\\setup_windows.ps1: ${player}') + } + stdout_path := os.join_path(directory, 'smoke-stdout.log') + stderr_path := os.join_path(directory, 'smoke-stderr.log') + mut stdout_file := os.create(stdout_path)! + defer { stdout_file.close() } + mut stderr_file := os.create(stderr_path)! + defer { stderr_file.close() } + + mut environment := os.environ() + environment['VIMGUI_SMOKE_FRAMES'] = frames.str() + mut child := os.new_process(player) + child.set_work_folder(directory) + child.set_environment(environment) + child.set_redirect_stdio() + child.run() + defer { + if child.is_alive() { + child.signal_kill() + // wait() reaps the killed process only while its status is running. + child.status = .running + } + child.wait() + child.close() + } + timer := time.new_stopwatch() + for { + live := child.is_alive() + out := child.stdout_read() + diagnostics := child.stderr_read() + stdout_file.write_string(out)! + stderr_file.write_string(diagnostics)! + if !live && out == '' && diagnostics == '' { + break + } + if timer.elapsed() >= timeout { + return error('Windows demo rendering timed out after ${timeout}; inspect ${stdout_path} and ${stderr_path}.') + } + if out == '' && diagnostics == '' { time.sleep(output_poll_interval) } + } + child.wait() + // Inspect complete streams so diagnostics split across pipe reads are detected. + stdout_file.flush() + stderr_file.flush() + out := os.read_file(stdout_path)! + diagnostics := os.read_file(stderr_path)! + print(out) + eprint(diagnostics) + output_lower := out.to_lower() + diagnostics_lower := diagnostics.to_lower() + if child.code != 0 || render_failures.any(output_lower.contains(it) + || diagnostics_lower.contains(it)) { + return error('Windows demo rendering failed (exit ${child.code}); inspect ${stdout_path} and ${stderr_path}.') + } + println('Windows GLFW/Vulkan demo rendered and shut down after ${frames} frames.') +} + +fn run(args []string) ! { + mut parser := flag.new_flag_parser(args) + parser.application('smoke_windows_demo') + parser.description('Render the built GLFW/Vulkan demo and check for a clean shutdown.') + directory := parser.string('demo-directory', 0, os.join_path(os.dir(@DIR), 'build', + 'windows-demo'), 'directory containing v_imgui_demo.exe') + frames := parser.int('frames', 0, default_frames, 'number of frames to render') + seconds := parser.int('timeout-seconds', 0, default_timeout_seconds, 'render time limit in seconds') + if parser.bool('help', `h`, false, 'show this help') { + println(parser.usage()) + return + } + if parser.finalize()!.len != 0 { + return error(parser.usage()) + } + if frames < 1 || frames > max_frames { + return error('--frames must be between 1 and ${max_frames}.') + } + if seconds < 1 || seconds > max_timeout_seconds { + return error('--timeout-seconds must be between 1 and ${max_timeout_seconds}.') + } + smoke(os.abs_path(directory), frames, seconds * time.second)! +} + +run(os.args[1..]) or { + eprintln(err) + exit(1) +} diff --git a/scripts/test_windows_setup.ps1 b/scripts/test_windows_setup.ps1 index d8c4c5f..437fba0 100644 --- a/scripts/test_windows_setup.ps1 +++ b/scripts/test_windows_setup.ps1 @@ -1,7 +1,7 @@ -# Uses local Git and ZIP fixtures to verify cache reuse, data preservation and hash checks. +# Uses local Git fixtures to verify compiler-cache reuse and data preservation. $ErrorActionPreference = 'Stop' . (Join-Path $PSScriptRoot 'windows_setup_tools.ps1') -$TestRoot = Join-Path ([IO.Path]::GetTempPath()) ('torus setup tests ' + [Guid]::NewGuid().ToString('N')) +$TestRoot = Join-Path ([IO.Path]::GetTempPath()) ('imgui setup tests ' + [Guid]::NewGuid().ToString('N')) function Assert-TT([bool]$Condition, [string]$Message) { if (-not $Condition) { throw $Message } } @@ -33,65 +33,6 @@ try { Assert-TT (-not (Test-Path -LiteralPath $RetryCheckout)) 'Failed clone committed an incomplete cache.' Get-WindowsSetupCheckout $Origin $Revision $RetryCheckout - $ArchiveFile = Join-Path $TestRoot 'fixture.zip' - $Payload = Join-Path $TestRoot 'tool.exe' - 'fixture executable' | Set-Content $Payload - Compress-Archive -LiteralPath $Payload -DestinationPath $ArchiveFile - $Extracted = Join-Path $TestRoot 'extracted' - $Caught = '' - try { Expand-WindowsSetupVerifiedArchive $ArchiveFile ('0' * 64) $Extracted } catch { $Caught = $_.Exception.Message } - Assert-TT ($Caught.StartsWith('Download checksum mismatch')) 'Setup accepted a bad checksum.' - Assert-TT (-not (Test-Path -LiteralPath $Extracted)) 'Bad download was extracted.' - $Hash = (Get-FileHash -LiteralPath $ArchiveFile -Algorithm SHA256).Hash - Get-WindowsSetupArchive 'https://example.invalid/not-downloaded' $Hash $ArchiveFile $Extracted 'tool.exe' - Get-WindowsSetupArchive 'https://example.invalid/not-downloaded' $Hash $ArchiveFile $Extracted 'tool.exe' - Assert-TT (Test-Path -LiteralPath (Join-Path $Extracted 'tool.exe')) 'Verified archive was not prepared.' - - $Unverified = Join-Path $TestRoot 'unverified extraction' - New-Item -ItemType Directory $Unverified | Out-Null - 'keep me' | Set-Content (Join-Path $Unverified 'personal.txt') - $Caught = '' - try { Get-WindowsSetupArchive 'unused' $Hash $ArchiveFile $Unverified 'tool.exe' } catch { $Caught = $_.Exception.Message } - Assert-TT ($Caught.StartsWith('Unverified tool directory')) 'Setup accepted an unverified directory.' - Assert-TT ((Get-Content (Join-Path $Unverified 'personal.txt') -Raw).Trim() -eq 'keep me') 'Setup overwrote user files.' - - $MissingTool = Join-Path $TestRoot 'missing executable' - $Caught = '' - try { Get-WindowsSetupArchive 'unused' $Hash $ArchiveFile $MissingTool 'missing.exe' } catch { $Caught = $_.Exception.Message } - Assert-TT ($Caught.StartsWith('Downloaded tool is missing')) 'Missing executable was accepted.' - Assert-TT (-not (Test-Path -LiteralPath $MissingTool)) 'Failed extraction committed an incomplete cache.' - Get-WindowsSetupArchive 'unused' $Hash $ArchiveFile $MissingTool 'tool.exe' - - Remove-Item -LiteralPath (Join-Path $Extracted 'tool.exe') - $Caught = '' - try { Get-WindowsSetupArchive 'unused' $Hash $ArchiveFile $Extracted 'tool.exe' } catch { $Caught = $_.Exception.Message } - Assert-TT ($Caught.StartsWith('Incomplete or mismatched tool cache')) 'Damaged verified cache was reused.' - Assert-TT (Test-Path -LiteralPath (Join-Path $MissingTool 'tool.exe')) 'Damaged-cache recovery changed a working cache.' - - $RetryArchive = Join-Path $TestRoot 'retry.zip' - $RetryTool = Join-Path $TestRoot 'retry tool' - function curl.exe { - param([Parameter(ValueFromRemainingArguments = $true)] [string[]]$DownloadArguments) - $OutputIndex = [Array]::IndexOf($DownloadArguments, '--output') - [IO.File]::WriteAllText($DownloadArguments[$OutputIndex + 1], 'interrupted download') - $global:LASTEXITCODE = 7 - } - try { - $Caught = '' - try { Get-WindowsSetupArchive 'fixture' $Hash $RetryArchive $RetryTool 'tool.exe' } catch { $Caught = $_.Exception.Message } - Assert-TT ($Caught -like '*failed with exit code 7*') 'Download failure was ignored.' - Assert-TT (-not (Test-Path -LiteralPath $RetryArchive)) 'Partial download became a cached archive.' - Assert-TT (-not (Test-Path -LiteralPath $RetryTool)) 'Partial download created an installed tool.' - function curl.exe { - param([Parameter(ValueFromRemainingArguments = $true)] [string[]]$DownloadArguments) - $OutputIndex = [Array]::IndexOf($DownloadArguments, '--output') - Copy-Item -LiteralPath $ArchiveFile -Destination $DownloadArguments[$OutputIndex + 1] -Force - $global:LASTEXITCODE = 0 - } - Get-WindowsSetupArchive 'fixture' $Hash $RetryArchive $RetryTool 'tool.exe' - Assert-TT (Test-Path -LiteralPath (Join-Path $RetryTool 'tool.exe')) 'Retry did not recover an interrupted download.' - } finally { Remove-Item -LiteralPath Function:curl.exe } - $SavedPath = $env:PATH try { $env:PATH = '' @@ -99,12 +40,12 @@ try { try { & (Join-Path $PSScriptRoot 'setup_windows.ps1') -Check } catch { $Caught = $_.Exception.Message } Assert-TT ($Caught -like 'Install git*rerun setup*') 'Missing Git did not explain recovery.' } finally { $env:PATH = $SavedPath } - Write-Host 'Windows setup cache and checksum tests passed.' + Write-Host 'Windows compiler-cache tests passed.' } finally { $ResolvedTestRoot = [IO.Path]::GetFullPath($TestRoot) $TemporaryPrefix = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\' if (-not $ResolvedTestRoot.StartsWith($TemporaryPrefix, [StringComparison]::OrdinalIgnoreCase) -or - [IO.Path]::GetFileName($ResolvedTestRoot) -notlike 'torus setup tests *') { + [IO.Path]::GetFileName($ResolvedTestRoot) -notlike 'imgui setup tests *') { throw "Refusing cleanup outside the test fixture: $ResolvedTestRoot" } if (Test-Path -LiteralPath $ResolvedTestRoot) { Remove-Item -LiteralPath $ResolvedTestRoot -Recurse -Force } diff --git a/scripts/tooling/pinned_checkout.v b/scripts/tooling/pinned_checkout.v new file mode 100644 index 0000000..bb756fe --- /dev/null +++ b/scripts/tooling/pinned_checkout.v @@ -0,0 +1,75 @@ +// Installs tagged dependency checkouts without resetting existing work. +module tooling + +import os +import rand +import v.vmod + +fn verify_pinned_checkout(directory string, tag string) ! { + if !os.exists(os.join_path(directory, '.git')) { + return error('Existing directory is not a managed Git checkout: ${directory}') + } + head := output('git', ['-C', directory, 'rev-parse', 'HEAD'])! + expected := output('git', ['-C', directory, 'rev-parse', '--verify', 'refs/tags/${tag}^{commit}'])! + if head != expected { + return error('Checkout is not at the tested tag ${tag}: ${directory}') + } + if output('git', ['-C', directory, 'status', '--porcelain'])! != '' { + return error('Preserve local changes in ${directory}, or choose another VMODULES directory.') + } +} + +fn prepare_pinned_checkout(repository string, tag string, directory string) ! { + if os.exists(directory) || os.is_link(directory) { + verify_pinned_checkout(directory, tag)! + return + } + os.mkdir_all(os.dir(directory))! + stage := os.join_path(os.dir(directory), '.module-' + rand.uuid_v4()) + defer { os.rmdir_all(stage) or {} } + command('git', ['clone', '--filter=blob:none', '--depth', '1', '--branch', tag, '--', repository, + stage])! + verify_pinned_checkout(stage, tag)! + // Publish only the complete checkout. Do not replace a concurrent install. + os.rename_dir(stage, directory) or { + if !os.is_dir(directory) { + return err + } + verify_pinned_checkout(directory, tag)! + } +} + +fn prepare_dependencies(root string, modules string, mut checked map[string]string) ! { + manifest := vmod.from_file(os.join_path(root, 'v.mod'))! + for dependency in manifest.dependencies { + name, tag := dependency.rsplit_once('@') or { + return error('Dependency is not pinned in ${root}: ${dependency}') + } + module_name := name.all_after_last('.') + if name != 'antono2.${module_name}' || module_name == '' || tag == '' + || !module_name.bytes().all((it >= `a` && it <= `z`) || (it >= `0` && it <= `9`) || it == `_`) { + return error('Expected an antono2 module with a release tag: ${dependency}') + } + if previous := checked[name] { + if previous != tag { + return error('Conflicting dependency pins for ${name}: ${previous} and ${tag}') + } + continue + } + repository := if module_name == 'vkmemalloc' { + 'vulkan_memory_allocator' + } else { + module_name + } + directory := os.join_path(modules, 'antono2', module_name) + prepare_pinned_checkout('https://github.com/antono2/${repository}.git', tag, directory)! + checked[name] = tag + prepare_dependencies(directory, modules, mut checked)! + } +} + +// Older VPM versions cannot reliably reuse pinned modules in paths with spaces. +pub fn prepare_pinned_modules(root string, modules string) ! { + mut checked := map[string]string{} + prepare_dependencies(root, modules, mut checked)! +} diff --git a/scripts/tooling/pinned_checkout_test.v b/scripts/tooling/pinned_checkout_test.v new file mode 100644 index 0000000..c6c863d --- /dev/null +++ b/scripts/tooling/pinned_checkout_test.v @@ -0,0 +1,38 @@ +// Verify staged tagged checkouts preserve personal work and allow a failed clone to be retried. +module tooling + +import os +import rand + +fn test_pinned_checkout_reuse_and_recovery() { + workspace := os.join_path(os.temp_dir(), 'imgui pinned modules ' + rand.uuid_v4()) + origin := os.join_path(workspace, 'local origin') + namespace := os.join_path(workspace, 'modules with spaces', 'antono2') + checkout := os.join_path(namespace, 'fixture') + pin := 'v1.0.0' + os.mkdir_all(origin) or { panic(err) } + defer { os.rmdir_all(workspace) or {} } + command('git', ['init', origin]) or { panic(err) } + os.write_file(os.join_path(origin, 'fixture.txt'), 'original') or { panic(err) } + command('git', ['-C', origin, 'add', '.']) or { panic(err) } + command('git', ['-C', origin, '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', + 'commit', '-m', 'fixture']) or { panic(err) } + command('git', ['-C', origin, 'tag', pin]) or { panic(err) } + mut rejected_missing := false + prepare_pinned_checkout(os.join_path(workspace, 'missing origin'), pin, checkout) or { + rejected_missing = true + } + assert rejected_missing + assert os.ls(namespace) or { panic(err) } == [] + prepare_pinned_checkout(origin, pin, checkout) or { panic(err) } + prepare_pinned_checkout(origin, pin, checkout) or { panic(err) } + file := os.join_path(checkout, 'fixture.txt') + os.write_file(file, 'personal changes') or { panic(err) } + mut rejected_dirty := false + prepare_pinned_checkout(origin, pin, checkout) or { + rejected_dirty = err.msg().contains('Preserve local changes') + } + assert rejected_dirty + assert os.read_file(file) or { panic(err) } == 'personal changes' + assert os.ls(namespace) or { panic(err) } == ['fixture'] +} diff --git a/scripts/windows_setup_tools.ps1 b/scripts/windows_setup_tools.ps1 index 23332ac..8d74c55 100644 --- a/scripts/windows_setup_tools.ps1 +++ b/scripts/windows_setup_tools.ps1 @@ -1,4 +1,4 @@ -# Checked downloads and Git checkouts used by the isolated Windows bootstrap. +# Checked Git checkouts used by the isolated Windows bootstrap. function Invoke-WindowsSetupCommand([string]$Command, [string[]]$Arguments) { & $Command @Arguments if ($LASTEXITCODE -ne 0) { throw "$Command failed with exit code ${LASTEXITCODE}: $($Arguments -join ' ')" } @@ -43,72 +43,3 @@ function Remove-WindowsSetupStagingDirectory([string]$Staging, [string]$Destinat } if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force } } - -function Expand-WindowsSetupVerifiedArchive([string]$Archive, [string]$Hash, [string]$Directory) { - if ((Get-FileHash -LiteralPath $Archive -Algorithm SHA256).Hash -ne $Hash) { - throw "Download checksum mismatch: $Archive. Remove this cached archive and retry." - } - Expand-Archive -LiteralPath $Archive -DestinationPath $Directory -Force -} - -function Get-WindowsSetupArchive([string]$Url, [string]$Hash, [string]$Archive, [string]$Directory, [string]$Executable) { - $ProgressPreference = 'SilentlyContinue' - $Marker = Join-Path $Directory '.archive-sha256' - if (Test-Path -LiteralPath $Marker) { - if ((Get-Content -LiteralPath $Marker -Raw).Trim() -ne $Hash -or - -not (Test-Path -LiteralPath (Join-Path $Directory $Executable))) { - throw "Incomplete or mismatched tool cache: $Directory. Choose another -CacheDirectory." - } - return - } - if (Test-Path -LiteralPath $Directory) { - throw "Unverified tool directory: $Directory. Preserve its contents and choose another -CacheDirectory." - } - if (-not (Test-Path -LiteralPath $Archive)) { - Write-Host "Downloading $Url" - $Download = "$Archive.download.zip" - try { - if (Get-Command curl.exe -ErrorAction SilentlyContinue) { - Invoke-WindowsSetupCommand curl.exe @('--fail', '--location', '--retry', '3', '--connect-timeout', '30', '--max-time', '900', '--silent', '--show-error', '--output', $Download, $Url) - } else { - Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $Download -TimeoutSec 120 - } - } catch { - throw "Download failed for ${Url}. Retry setup; existing installed tools are preserved. $($_.Exception.Message)" - } - if ((Get-FileHash -LiteralPath $Download -Algorithm SHA256).Hash -ne $Hash) { - throw "Download checksum mismatch: $Url. Retry setup to download again." - } - Move-Item -LiteralPath $Download -Destination $Archive -Force - } - $Staging = "$Directory.setup-$([Guid]::NewGuid().ToString('N'))" - try { - Expand-WindowsSetupVerifiedArchive $Archive $Hash $Staging - if (-not (Test-Path -LiteralPath (Join-Path $Staging $Executable))) { - throw "Downloaded tool is missing ${Executable}: $Archive. Check the archive/pin before retrying." - } - $Hash | Set-Content -LiteralPath (Join-Path $Staging '.archive-sha256') -Encoding ascii - [IO.Directory]::Move([IO.Path]::GetFullPath($Staging), [IO.Path]::GetFullPath($Directory)) - } finally { - Remove-WindowsSetupStagingDirectory $Staging $Directory - } -} - -# Install manifest-pinned repositories directly: old VPM versions refuse repeat -# installs into a VMODULES directory containing spaces, even at the right pin. -function Install-WindowsSetupModules([string]$ManifestDirectory, [string]$ModulesDirectory, [hashtable]$Checked) { - $Manifest = Get-Content -LiteralPath (Join-Path $ManifestDirectory 'v.mod') -Raw - foreach ($Match in [regex]::Matches($Manifest, "'antono2\.([a-z0-9_]+)@([^']+)'")) { - $Name = $Match.Groups[1].Value - $Tag = $Match.Groups[2].Value - if ($Checked.ContainsKey($Name)) { - if ($Checked[$Name] -ne $Tag) { throw "Conflicting dependency pins for $Name" } - continue - } - $Checked[$Name] = $Tag - $Repository = if ($Name -eq 'vkmemalloc') { 'vulkan_memory_allocator' } else { $Name } - $Directory = Join-Path $ModulesDirectory "antono2\$Name" - Get-WindowsSetupCheckout "https://github.com/antono2/$Repository.git" $Tag $Directory - Install-WindowsSetupModules $Directory $ModulesDirectory $Checked - } -}