Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

260 lines
12KB

  1. # Shared helpers for tools/*.ps1. Generated by the C64/C128 Dev Foundry.
  2. # Everything project-specific comes from project.json ("resolved" section), so these
  3. # scripts do not need editing when sources are added. Requires PowerShell 7+.
  4. Set-StrictMode -Version 1.0
  5. $ErrorActionPreference = 'Stop'
  6. $script:RepoRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path
  7. class MissingToolException : System.Exception {
  8. [string]$ToolId
  9. MissingToolException([string]$toolId, [string]$message) : base($message) { $this.ToolId = $toolId }
  10. }
  11. function Get-RepoRoot { $script:RepoRoot }
  12. function Get-RepoPath([string]$Relative) {
  13. if ([IO.Path]::IsPathRooted($Relative)) { return $Relative }
  14. Join-Path $script:RepoRoot ($Relative -replace '[\\/]', [IO.Path]::DirectorySeparatorChar)
  15. }
  16. function Get-ProjectConfig {
  17. $path = Join-Path $script:RepoRoot 'project.json'
  18. Get-Content -LiteralPath $path -Raw | ConvertFrom-Json -AsHashtable -Depth 64
  19. }
  20. function Get-ProjectTargets([hashtable]$Project, [string]$TargetId) {
  21. $targets = @($Project.resolved.targets)
  22. if ($TargetId) {
  23. $targets = @($targets | Where-Object { $_.id -eq $TargetId })
  24. if ($targets.Count -eq 0) {
  25. $known = ($Project.resolved.targets | ForEach-Object { $_.id }) -join ', '
  26. throw "Unknown target '$TargetId'. Known targets: $known"
  27. }
  28. }
  29. $targets
  30. }
  31. function Get-ToolEntry([hashtable]$Project, [string]$ToolId) {
  32. $entry = $Project.resolved.tools | Where-Object { $_.id -eq $ToolId } | Select-Object -First 1
  33. if (-not $entry) { throw "project.json does not list tool '$ToolId' under resolved.tools." }
  34. $entry
  35. }
  36. function Find-ToolPath([hashtable]$Tool) {
  37. $exe = $Tool.executable
  38. $names = if ($IsWindows) { @("$exe.exe", $exe) } else { @($exe) }
  39. # 1. Explicit environment variable (folder or folder\bin)
  40. if ($Tool.envVar) {
  41. $base = [Environment]::GetEnvironmentVariable($Tool.envVar)
  42. if ($base) {
  43. foreach ($dir in @($base, (Join-Path $base 'bin'))) {
  44. foreach ($n in $names) {
  45. $p = Join-Path $dir $n
  46. if (Test-Path -LiteralPath $p -PathType Leaf) { return $p }
  47. }
  48. }
  49. }
  50. }
  51. # 2. PATH
  52. $cmd = Get-Command $exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
  53. if ($cmd) { return $cmd.Source }
  54. # 3. Well-known install folders (newest first)
  55. foreach ($pattern in @($Tool.searchPaths)) {
  56. if (-not $pattern) { continue }
  57. $expanded = [Environment]::ExpandEnvironmentVariables($pattern)
  58. $dirs = @(Resolve-Path -Path $expanded -ErrorAction SilentlyContinue | ForEach-Object { $_.ProviderPath } | Sort-Object -Descending)
  59. foreach ($dir in $dirs) {
  60. foreach ($n in $names) {
  61. $p = Join-Path $dir $n
  62. if (Test-Path -LiteralPath $p -PathType Leaf) { return $p }
  63. }
  64. }
  65. }
  66. $null
  67. }
  68. function Get-ToolPath([hashtable]$Project, [string]$ToolId) {
  69. $tool = Get-ToolEntry $Project $ToolId
  70. $path = Find-ToolPath $tool
  71. if (-not $path) {
  72. $msg = @"
  73. MISSING TOOL: $($tool.executable) ($($tool.purpose))
  74. First step : $($tool.install.firstCommand)
  75. Source : $($tool.install.source)
  76. Detection : set $($tool.envVar) to the install folder, or put $($tool.executable) on PATH.
  77. Unverified until installed: $(@($tool.requiredFor) -join '; ')
  78. "@
  79. throw [MissingToolException]::new($ToolId, $msg)
  80. }
  81. $path
  82. }
  83. function Get-ToolVersion([hashtable]$Tool, [string]$Path) {
  84. if (-not $Tool.versionArgs -or @($Tool.versionArgs).Count -eq 0) {
  85. # VICE emulators have no quiet version switch; report the install folder name instead.
  86. return "(version from folder) " + (Split-Path (Split-Path $Path -Parent) -Leaf)
  87. }
  88. try {
  89. $out = & $Path @($Tool.versionArgs) 2>&1 | ForEach-Object { "$_" } | Where-Object { $_ -match '\d+\.\d+' } | Select-Object -First 1
  90. if ($out) { return $out.Trim() }
  91. } catch { }
  92. '(version unknown)'
  93. }
  94. function Invoke-Tool([string]$Path, [string[]]$Arguments, [string]$WorkingDirectory = $script:RepoRoot) {
  95. Write-Host (" > {0} {1}" -f (Split-Path $Path -Leaf), (($Arguments | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }) -join ' '))
  96. Push-Location -LiteralPath $WorkingDirectory
  97. try {
  98. $output = & $Path @Arguments 2>&1 | ForEach-Object { "$_" }
  99. $code = $LASTEXITCODE
  100. } finally { Pop-Location }
  101. foreach ($line in $output) { if ($line.Trim()) { Write-Host " $line" } }
  102. if ($code -ne 0) { throw "$(Split-Path $Path -Leaf) failed with exit code $code." }
  103. }
  104. # ---------------------------------------------------------------------------
  105. # Text conversion
  106. # ---------------------------------------------------------------------------
  107. # Plain ASCII text -> PETSCII bytes for the upper/lower-case character set.
  108. # ASCII lower case -> PETSCII $41-$5A, ASCII upper case -> PETSCII $C1-$DA.
  109. # LineEndings: 'cr' converts LF and CRLF to CR ($0D); 'keep' leaves them alone.
  110. function ConvertTo-Petscii([byte[]]$Bytes, [string]$LineEndings = 'cr') {
  111. $out = [System.Collections.Generic.List[byte]]::new()
  112. for ($i = 0; $i -lt $Bytes.Length; $i++) {
  113. $b = $Bytes[$i]
  114. if ($LineEndings -eq 'cr') {
  115. if ($b -eq 0x0D) { $out.Add(0x0D); if ($i + 1 -lt $Bytes.Length -and $Bytes[$i + 1] -eq 0x0A) { $i++ }; continue }
  116. if ($b -eq 0x0A) { $out.Add(0x0D); continue }
  117. }
  118. if ($b -ge 0x61 -and $b -le 0x7A) { $out.Add([byte]($b - 0x20)); continue }
  119. if ($b -ge 0x41 -and $b -le 0x5A) { $out.Add([byte]($b + 0x80)); continue }
  120. $out.Add($b)
  121. }
  122. , $out.ToArray()
  123. }
  124. # Expected text -> VIC-II/VDC screen codes.
  125. # screen-upper: upper-case/graphics set (BASIC and KERNAL default): letters -> 1..26
  126. # screen-mixed: lower/upper-case set (cc65 C programs): a-z -> 1..26, A-Z -> $41..$5A
  127. function ConvertTo-ScreenCodes([string]$Text, [string]$Encoding) {
  128. $codes = foreach ($ch in $Text.ToCharArray()) {
  129. $c = [int]$ch
  130. if ($c -ge 0x61 -and $c -le 0x7A) { $c - 0x60 }
  131. elseif ($c -ge 0x41 -and $c -le 0x5A) { if ($Encoding -eq 'screen-mixed') { $c } else { $c - 0x40 } }
  132. elseif ($c -eq 0x40) { 0 }
  133. elseif ($c -ge 0x5B -and $c -le 0x5F) { $c - 0x40 }
  134. else { $c }
  135. }
  136. , [byte[]]$codes
  137. }
  138. function Format-Hex([byte[]]$Bytes) { ($Bytes | ForEach-Object { '{0:X2}' -f $_ }) -join ' ' }
  139. # ---------------------------------------------------------------------------
  140. # Build
  141. # ---------------------------------------------------------------------------
  142. function Get-SourceFiles([hashtable]$Build) {
  143. $files = foreach ($dir in @($Build.sourceDirs)) {
  144. $full = Get-RepoPath $dir
  145. if (Test-Path -LiteralPath $full) {
  146. Get-ChildItem -LiteralPath $full -File | Where-Object { $_.Extension -in '.c', '.s' } | Sort-Object Name
  147. }
  148. }
  149. @($files | ForEach-Object { $_.FullName })
  150. }
  151. function Invoke-TargetBuild([hashtable]$Project, [hashtable]$Target, [hashtable]$Done) {
  152. $build = $Target.build
  153. $key = "$($build.kind)|$($Target.artifact)"
  154. if ($Done.ContainsKey($key)) {
  155. Write-Host "[$($Target.id)] artifact $($Target.artifact) already built for target $($Done[$key])"
  156. } else {
  157. Write-Host "[$($Target.id)] building $($Target.artifact)"
  158. $artifact = Get-RepoPath $Target.artifact
  159. New-Item -ItemType Directory -Force -Path (Split-Path $artifact -Parent) | Out-Null
  160. switch ($build.kind) {
  161. 'cc65' {
  162. $cl65 = Get-ToolPath $Project 'cl65'
  163. $sources = Get-SourceFiles $build
  164. if ($sources.Count -eq 0) { throw "No .c or .s files found in $(@($build.sourceDirs) -join ', ')." }
  165. $toolArgs = @('-t', $build.cc65Target, '-g')
  166. if ($build.config) { $toolArgs += @('-C', $build.config, '-u', '__EXEHDR__') } else { $toolArgs += '-O' }
  167. foreach ($d in @($build.defines)) { if ($d) { $toolArgs += @('-D', $d) } }
  168. foreach ($d in @($build.asmDefines)) { if ($d) { $toolArgs += @('--asm-define', $d) } } # ca65 symbols (cl65 -D is for C only)
  169. foreach ($dir in @($build.sourceDirs)) { $toolArgs += @('-I', (Get-RepoPath $dir)) }
  170. $toolArgs += @('-o', $artifact, '-Ln', (Get-RepoPath $build.labels), '-m', (Get-RepoPath $build.map))
  171. $toolArgs += $sources
  172. Invoke-Tool $cl65 $toolArgs
  173. # cl65 leaves object files next to sources; keep the source tree clean.
  174. foreach ($s in $sources) { $o = [IO.Path]::ChangeExtension($s, '.o'); if (Test-Path -LiteralPath $o) { Remove-Item -LiteralPath $o } }
  175. }
  176. 'petcat' {
  177. $petcat = Get-ToolPath $Project 'petcat'
  178. Invoke-Tool $petcat @("-w$($build.dialect)", '-f', '-o', $artifact, '--', (Get-RepoPath $build.source))
  179. }
  180. 'none' {
  181. Write-Host " This target is built on the Commodore (see docs/toolchain.md). Nothing to build on the host."
  182. return
  183. }
  184. default { throw "Unknown build kind '$($build.kind)'." }
  185. }
  186. if (-not (Test-Path -LiteralPath $artifact)) { throw "Build reported success but $($Target.artifact) was not created." }
  187. Write-Host (" ok: {0} ({1} bytes)" -f $Target.artifact, (Get-Item -LiteralPath $artifact).Length)
  188. $Done[$key] = $Target.id
  189. }
  190. if ($Target.disk) { New-TargetDisk $Project $Target $Done }
  191. }
  192. function New-TargetDisk([hashtable]$Project, [hashtable]$Target, [hashtable]$Done) {
  193. $disk = $Target.disk
  194. $key = "disk|$($disk.image)"
  195. if ($Done.ContainsKey($key)) { return }
  196. $c1541 = Get-ToolPath $Project 'c1541'
  197. $image = Get-RepoPath $disk.image
  198. $stage = Join-Path (Split-Path $image -Parent) 'disk-files'
  199. New-Item -ItemType Directory -Force -Path $stage | Out-Null
  200. if (Test-Path -LiteralPath $image) { Remove-Item -LiteralPath $image }
  201. $toolArgs = @('-format', $disk.name, $disk.format, $image)
  202. foreach ($f in @($disk.files)) {
  203. $src = Get-RepoPath $f.source
  204. if (-not (Test-Path -LiteralPath $src)) { throw "Disk file source not found: $($f.source)" }
  205. if ($f.convert -eq 'ascii-to-petscii') {
  206. $converted = Join-Path $stage ($f.name + '.petscii')
  207. [IO.File]::WriteAllBytes($converted, (ConvertTo-Petscii ([IO.File]::ReadAllBytes($src)) $f.lineEndings))
  208. $src = $converted
  209. }
  210. $dest = if ($f.type -eq 'seq') { "$($f.name),s" } else { $f.name }
  211. $toolArgs += @('-write', $src, $dest)
  212. }
  213. $toolArgs += '-list'
  214. Write-Host "[$($Target.id)] writing disk image $($disk.image)"
  215. Invoke-Tool $c1541 $toolArgs
  216. $Done[$key] = $Target.id
  217. }
  218. # ---------------------------------------------------------------------------
  219. # Emulator
  220. # ---------------------------------------------------------------------------
  221. # Build variant: add an assembler symbol and give the program, labels and map a suffix
  222. # (<name>-<Suffix>.prg), so the normal build is not touched. cc65 targets only.
  223. function Set-TargetVariant([hashtable]$Target, [string]$Define, [string]$Suffix) {
  224. if ($Target.build.kind -ne 'cc65') { throw "The $Define build needs a cc65 target." }
  225. $Target.build.asmDefines = @(@($Target.build.asmDefines) + $Define | Where-Object { $_ })
  226. foreach ($k in 'labels', 'map') { $Target.build[$k] = $Target.build[$k] -replace '(\.\w+)$', "-$Suffix`$1" }
  227. $Target.artifact = $Target.artifact -replace '(\.\w+)$', "-$Suffix`$1"
  228. $Target.disk = $null
  229. }
  230. function Get-AutostartFile([hashtable]$Target) {
  231. if ($Target.emulator.autostart -eq 'disk') { return Get-RepoPath $Target.disk.image }
  232. Get-RepoPath $Target.artifact
  233. }
  234. function Get-VideoArgs([hashtable]$Target) {
  235. switch ($Target.video) { 'ntsc' { @('-ntsc') } default { @('-pal') } }
  236. }

Powered by TurnKey Linux.