# Shared helpers for tools/*.ps1. Generated by the C64/C128 Dev Foundry. # Everything project-specific comes from project.json ("resolved" section), so these # scripts do not need editing when sources are added. Requires PowerShell 7+. Set-StrictMode -Version 1.0 $ErrorActionPreference = 'Stop' $script:RepoRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path class MissingToolException : System.Exception { [string]$ToolId MissingToolException([string]$toolId, [string]$message) : base($message) { $this.ToolId = $toolId } } function Get-RepoRoot { $script:RepoRoot } function Get-RepoPath([string]$Relative) { if ([IO.Path]::IsPathRooted($Relative)) { return $Relative } Join-Path $script:RepoRoot ($Relative -replace '[\\/]', [IO.Path]::DirectorySeparatorChar) } function Get-ProjectConfig { $path = Join-Path $script:RepoRoot 'project.json' Get-Content -LiteralPath $path -Raw | ConvertFrom-Json -AsHashtable -Depth 64 } function Get-ProjectTargets([hashtable]$Project, [string]$TargetId) { $targets = @($Project.resolved.targets) if ($TargetId) { $targets = @($targets | Where-Object { $_.id -eq $TargetId }) if ($targets.Count -eq 0) { $known = ($Project.resolved.targets | ForEach-Object { $_.id }) -join ', ' throw "Unknown target '$TargetId'. Known targets: $known" } } $targets } function Get-ToolEntry([hashtable]$Project, [string]$ToolId) { $entry = $Project.resolved.tools | Where-Object { $_.id -eq $ToolId } | Select-Object -First 1 if (-not $entry) { throw "project.json does not list tool '$ToolId' under resolved.tools." } $entry } function Find-ToolPath([hashtable]$Tool) { $exe = $Tool.executable $names = if ($IsWindows) { @("$exe.exe", $exe) } else { @($exe) } # 1. Explicit environment variable (folder or folder\bin) if ($Tool.envVar) { $base = [Environment]::GetEnvironmentVariable($Tool.envVar) if ($base) { foreach ($dir in @($base, (Join-Path $base 'bin'))) { foreach ($n in $names) { $p = Join-Path $dir $n if (Test-Path -LiteralPath $p -PathType Leaf) { return $p } } } } } # 2. PATH $cmd = Get-Command $exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if ($cmd) { return $cmd.Source } # 3. Well-known install folders (newest first) foreach ($pattern in @($Tool.searchPaths)) { if (-not $pattern) { continue } $expanded = [Environment]::ExpandEnvironmentVariables($pattern) $dirs = @(Resolve-Path -Path $expanded -ErrorAction SilentlyContinue | ForEach-Object { $_.ProviderPath } | Sort-Object -Descending) foreach ($dir in $dirs) { foreach ($n in $names) { $p = Join-Path $dir $n if (Test-Path -LiteralPath $p -PathType Leaf) { return $p } } } } $null } function Get-ToolPath([hashtable]$Project, [string]$ToolId) { $tool = Get-ToolEntry $Project $ToolId $path = Find-ToolPath $tool if (-not $path) { $msg = @" MISSING TOOL: $($tool.executable) ($($tool.purpose)) First step : $($tool.install.firstCommand) Source : $($tool.install.source) Detection : set $($tool.envVar) to the install folder, or put $($tool.executable) on PATH. Unverified until installed: $(@($tool.requiredFor) -join '; ') "@ throw [MissingToolException]::new($ToolId, $msg) } $path } function Get-ToolVersion([hashtable]$Tool, [string]$Path) { if (-not $Tool.versionArgs -or @($Tool.versionArgs).Count -eq 0) { # VICE emulators have no quiet version switch; report the install folder name instead. return "(version from folder) " + (Split-Path (Split-Path $Path -Parent) -Leaf) } try { $out = & $Path @($Tool.versionArgs) 2>&1 | ForEach-Object { "$_" } | Where-Object { $_ -match '\d+\.\d+' } | Select-Object -First 1 if ($out) { return $out.Trim() } } catch { } '(version unknown)' } function Invoke-Tool([string]$Path, [string[]]$Arguments, [string]$WorkingDirectory = $script:RepoRoot) { Write-Host (" > {0} {1}" -f (Split-Path $Path -Leaf), (($Arguments | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }) -join ' ')) Push-Location -LiteralPath $WorkingDirectory try { $output = & $Path @Arguments 2>&1 | ForEach-Object { "$_" } $code = $LASTEXITCODE } finally { Pop-Location } foreach ($line in $output) { if ($line.Trim()) { Write-Host " $line" } } if ($code -ne 0) { throw "$(Split-Path $Path -Leaf) failed with exit code $code." } } # --------------------------------------------------------------------------- # Text conversion # --------------------------------------------------------------------------- # Plain ASCII text -> PETSCII bytes for the upper/lower-case character set. # ASCII lower case -> PETSCII $41-$5A, ASCII upper case -> PETSCII $C1-$DA. # LineEndings: 'cr' converts LF and CRLF to CR ($0D); 'keep' leaves them alone. function ConvertTo-Petscii([byte[]]$Bytes, [string]$LineEndings = 'cr') { $out = [System.Collections.Generic.List[byte]]::new() for ($i = 0; $i -lt $Bytes.Length; $i++) { $b = $Bytes[$i] if ($LineEndings -eq 'cr') { if ($b -eq 0x0D) { $out.Add(0x0D); if ($i + 1 -lt $Bytes.Length -and $Bytes[$i + 1] -eq 0x0A) { $i++ }; continue } if ($b -eq 0x0A) { $out.Add(0x0D); continue } } if ($b -ge 0x61 -and $b -le 0x7A) { $out.Add([byte]($b - 0x20)); continue } if ($b -ge 0x41 -and $b -le 0x5A) { $out.Add([byte]($b + 0x80)); continue } $out.Add($b) } , $out.ToArray() } # Expected text -> VIC-II/VDC screen codes. # screen-upper: upper-case/graphics set (BASIC and KERNAL default): letters -> 1..26 # screen-mixed: lower/upper-case set (cc65 C programs): a-z -> 1..26, A-Z -> $41..$5A function ConvertTo-ScreenCodes([string]$Text, [string]$Encoding) { $codes = foreach ($ch in $Text.ToCharArray()) { $c = [int]$ch if ($c -ge 0x61 -and $c -le 0x7A) { $c - 0x60 } elseif ($c -ge 0x41 -and $c -le 0x5A) { if ($Encoding -eq 'screen-mixed') { $c } else { $c - 0x40 } } elseif ($c -eq 0x40) { 0 } elseif ($c -ge 0x5B -and $c -le 0x5F) { $c - 0x40 } else { $c } } , [byte[]]$codes } function Format-Hex([byte[]]$Bytes) { ($Bytes | ForEach-Object { '{0:X2}' -f $_ }) -join ' ' } # --------------------------------------------------------------------------- # Build # --------------------------------------------------------------------------- function Get-SourceFiles([hashtable]$Build) { $files = foreach ($dir in @($Build.sourceDirs)) { $full = Get-RepoPath $dir if (Test-Path -LiteralPath $full) { Get-ChildItem -LiteralPath $full -File | Where-Object { $_.Extension -in '.c', '.s' } | Sort-Object Name } } @($files | ForEach-Object { $_.FullName }) } function Invoke-TargetBuild([hashtable]$Project, [hashtable]$Target, [hashtable]$Done) { $build = $Target.build $key = "$($build.kind)|$($Target.artifact)" if ($Done.ContainsKey($key)) { Write-Host "[$($Target.id)] artifact $($Target.artifact) already built for target $($Done[$key])" } else { Write-Host "[$($Target.id)] building $($Target.artifact)" $artifact = Get-RepoPath $Target.artifact New-Item -ItemType Directory -Force -Path (Split-Path $artifact -Parent) | Out-Null switch ($build.kind) { 'cc65' { $cl65 = Get-ToolPath $Project 'cl65' $sources = Get-SourceFiles $build if ($sources.Count -eq 0) { throw "No .c or .s files found in $(@($build.sourceDirs) -join ', ')." } $toolArgs = @('-t', $build.cc65Target, '-g') if ($build.config) { $toolArgs += @('-C', $build.config, '-u', '__EXEHDR__') } else { $toolArgs += '-O' } foreach ($d in @($build.defines)) { if ($d) { $toolArgs += @('-D', $d) } } foreach ($d in @($build.asmDefines)) { if ($d) { $toolArgs += @('--asm-define', $d) } } # ca65 symbols (cl65 -D is for C only) foreach ($dir in @($build.sourceDirs)) { $toolArgs += @('-I', (Get-RepoPath $dir)) } $toolArgs += @('-o', $artifact, '-Ln', (Get-RepoPath $build.labels), '-m', (Get-RepoPath $build.map)) $toolArgs += $sources Invoke-Tool $cl65 $toolArgs # cl65 leaves object files next to sources; keep the source tree clean. foreach ($s in $sources) { $o = [IO.Path]::ChangeExtension($s, '.o'); if (Test-Path -LiteralPath $o) { Remove-Item -LiteralPath $o } } } 'petcat' { $petcat = Get-ToolPath $Project 'petcat' Invoke-Tool $petcat @("-w$($build.dialect)", '-f', '-o', $artifact, '--', (Get-RepoPath $build.source)) } 'none' { Write-Host " This target is built on the Commodore (see docs/toolchain.md). Nothing to build on the host." return } default { throw "Unknown build kind '$($build.kind)'." } } if (-not (Test-Path -LiteralPath $artifact)) { throw "Build reported success but $($Target.artifact) was not created." } Write-Host (" ok: {0} ({1} bytes)" -f $Target.artifact, (Get-Item -LiteralPath $artifact).Length) $Done[$key] = $Target.id } if ($Target.disk) { New-TargetDisk $Project $Target $Done } } function New-TargetDisk([hashtable]$Project, [hashtable]$Target, [hashtable]$Done) { $disk = $Target.disk $key = "disk|$($disk.image)" if ($Done.ContainsKey($key)) { return } $c1541 = Get-ToolPath $Project 'c1541' $image = Get-RepoPath $disk.image $stage = Join-Path (Split-Path $image -Parent) 'disk-files' New-Item -ItemType Directory -Force -Path $stage | Out-Null if (Test-Path -LiteralPath $image) { Remove-Item -LiteralPath $image } $toolArgs = @('-format', $disk.name, $disk.format, $image) foreach ($f in @($disk.files)) { $src = Get-RepoPath $f.source if (-not (Test-Path -LiteralPath $src)) { throw "Disk file source not found: $($f.source)" } if ($f.convert -eq 'ascii-to-petscii') { $converted = Join-Path $stage ($f.name + '.petscii') [IO.File]::WriteAllBytes($converted, (ConvertTo-Petscii ([IO.File]::ReadAllBytes($src)) $f.lineEndings)) $src = $converted } $dest = if ($f.type -eq 'seq') { "$($f.name),s" } else { $f.name } $toolArgs += @('-write', $src, $dest) } $toolArgs += '-list' Write-Host "[$($Target.id)] writing disk image $($disk.image)" Invoke-Tool $c1541 $toolArgs $Done[$key] = $Target.id } # --------------------------------------------------------------------------- # Emulator # --------------------------------------------------------------------------- function Get-AutostartFile([hashtable]$Target) { if ($Target.emulator.autostart -eq 'disk') { return Get-RepoPath $Target.disk.image } Get-RepoPath $Target.artifact } function Get-VideoArgs([hashtable]$Target) { switch ($Target.video) { 'ntsc' { @('-ntsc') } default { @('-pal') } } }