返回 CodeWhale
install.ps1
根目录 / scripts / release / install.ps1
1 # Archive installation only. Runtime authority remains with Codewhale Core.
2 param([switch]$NoModifyPath)
3 $ErrorActionPreference = 'Stop'
4 $destination = Join-Path $env:USERPROFILE 'bin'
5 $names = @('codewhale.exe', 'codew.exe', 'codewhale.bat')
6 $receiptName = '.codewhale-install.sha256'
7 $optional = $env:CODEWHALE_INSTALL_COMPILED_HOST -eq '1'
8 if ($optional) {
9 $names += @('codewhale-extension-host.exe', 'codewhale-extension-host.LICENSES.txt', 'codewhale-extension-host.relink-source.tar.gz', 'codewhale-extension-host.release.json')
10 }
11 function Path-Key([string]$entry) {
12 return [Environment]::ExpandEnvironmentVariables($entry.Trim()).TrimEnd('\', '/').ToLowerInvariant()
13 }
14 function Ensure-UserPath([string]$directory) {
15 $key = Path-Key $directory
16 $quoted = $directory.Replace("'", "''")
17 $registry = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
18 try {
19 $current = [string]$registry.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
20 if (@($current -split ';' | Where-Object { $_ -and (Path-Key $_) -eq $key }).Count -gt 0) {
21 Write-Host "$directory is already in your user PATH; it was left as is."
22 return
23 }
24 if (@($env:Path -split ';' | Where-Object { $_ -and (Path-Key $_) -eq $key }).Count -gt 0) {
25 Write-Host "$directory is already on PATH; your user PATH was not changed."
26 return
27 }
28 if ($NoModifyPath -or $env:CODEWHALE_NO_MODIFY_PATH -in @('1', 'true', 'yes')) {
29 Write-Host "Not changing your user PATH (-NoModifyPath). To add it yourself, run once:"
30 Write-Host " [Environment]::SetEnvironmentVariable('Path', ([Environment]::GetEnvironmentVariable('Path', 'User') + ';$quoted'), 'User')"
31 return
32 }
33 $updated = if ($current -and !$current.EndsWith(';')) { "$current;$directory" } else { "$current$directory" }
34 $registry.SetValue('Path', $updated, [Microsoft.Win32.RegistryValueKind]::ExpandString)
35 try { [Environment]::SetEnvironmentVariable('CODEWHALE_PATH_NOTIFY', $null, 'User') } catch { }
36 Write-Host "Added $directory to your user PATH so new terminals find codewhale (skip this with -NoModifyPath). Only that one entry was added."
37 Write-Host "To undo, run:"
38 Write-Host " `$p = (Get-Item 'HKCU:\Environment').GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames); Set-ItemProperty -Path 'HKCU:\Environment' -Name Path -Type ExpandString -Value (@(`$p -split ';' | Where-Object { `$_ -and `$_.TrimEnd('\') -ine '$quoted' }) -join ';')"
39 } finally {
40 $registry.Close()
41 }
42 }
43 function File-Hash([string]$file) {
44 if (!(Test-Path -LiteralPath $file)) { return $null }
45 $item = Get-Item -LiteralPath $file -Force
46 if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw "Refusing nonregular installation file $file" }
47 return (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant()
48 }
49 function Host-Entry([string]$receipt) {
50 if ((Get-Item -LiteralPath $receipt).Length -gt 65536) { throw 'Compiled-host receipt exceeds 64 KiB' }
51 $catalog = Get-Content -LiteralPath $receipt -Raw | ConvertFrom-Json
52 $architecture = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant()
53 if ($architecture -eq 'x64') { $target = 'windows-x64' }
54 elseif ($architecture -eq 'arm64') { $target = 'windows-arm64' }
55 else { throw "No qualified compiled host for Windows/$architecture; use Node" }
56 $rows = @($catalog.hosts | Where-Object { $_.target -eq $target })
57 if ($catalog.schema -ne 1 -or $rows.Count -ne 1) { throw 'No unique qualified compiled-host receipt' }
58 $hostEntry = $rows[0]
59 if ($hostEntry.license_closure -ne 'complete' -or $hostEntry.relink_source -ne 'complete' -or $hostEntry.native_platform -ne 'win32' -or $hostEntry.native_arch -ne $architecture -or $hostEntry.passed -ne 5 -or $hostEntry.failed -ne 0 -or $hostEntry.skipped -ne 0 -or $hostEntry.native_passed -lt 9 -or $hostEntry.native_failed -ne 0 -or $hostEntry.native_skipped -ne 0) { throw 'Compiled host has no complete matching-native qualification' }
60 return $hostEntry
61 }
62 $stage = $null
63 $published = @()
64 $retain = $false
65 try {
66 # Check every source before the first destination mutation.
67 foreach ($name in $names) {
68 if (!(File-Hash (Join-Path $PSScriptRoot $name))) { throw "Missing archive payload $name; extract the complete archive" }
69 }
70 if ((File-Hash (Join-Path $PSScriptRoot 'codewhale.exe')) -ne (File-Hash (Join-Path $PSScriptRoot 'codew.exe'))) { throw 'Command alias differs from the canonical Codewhale program' }
71 $sourceLauncherHash = File-Hash (Join-Path $PSScriptRoot 'codewhale.bat')
72 if ($optional) {
73 $entry = Host-Entry (Join-Path $PSScriptRoot 'codewhale-extension-host.release.json')
74 $hashes = @($entry.sha256, $entry.notices_sha256, $entry.source_sha256)
75 for ($i = 0; $i -lt 3; $i++) {
76 if ($hashes[$i] -notmatch '^[a-f0-9]{64}$' -or (File-Hash (Join-Path $PSScriptRoot $names[$i + 3])) -ne $hashes[$i]) { throw 'Compiled host archive payload hash mismatch' }
77 }
78 }
79 if (Test-Path -LiteralPath $destination) {
80 $directory = Get-Item -LiteralPath $destination -Force
81 if (!$directory.PSIsContainer -or ($directory.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Refusing a nonregular or redirected installation directory' }
82 }
83 $receiptTarget = Join-Path $destination $receiptName
84 $claims = @{}
85 if (File-Hash $receiptTarget) {
86 if ((Get-Item -LiteralPath $receiptTarget -Force).Length -gt 65536) { throw "Refusing oversized install receipt $receiptTarget" }
87 $receiptText = [string](Get-Content -LiteralPath $receiptTarget -Raw)
88 foreach ($line in ($receiptText -split "`r?`n")) {
89 if (!$line) { continue }
90 if ($line -match '^([a-f0-9]{64}) (codewhale\.exe|codew\.exe|codewhale\.bat)$') {
91 if ($claims.ContainsKey($Matches[2])) { throw "Refusing duplicate install receipt entry $($Matches[2]) in $receiptTarget" }
92 $claims[$Matches[2]] = $Matches[1].ToLowerInvariant()
93 } else {
94 throw "Refusing unrecognized install receipt entry '$line' in $receiptTarget"
95 }
96 }
97 if ($claims.Count -ne 3) { throw "Refusing incomplete Codewhale install receipt $receiptTarget" }
98 }
99 [IO.Directory]::CreateDirectory($destination) | Out-Null
100 $stage = Join-Path $destination ('.codewhale-install-' + [Guid]::NewGuid().ToString('N'))
101 [IO.Directory]::CreateDirectory($stage) | Out-Null
102 $oldHost = $null
103 if ($optional -and (File-Hash (Join-Path $destination 'codewhale-extension-host.release.json'))) { $oldHost = Host-Entry (Join-Path $destination 'codewhale-extension-host.release.json') }
104 $snapshots = @()
105 foreach ($name in $names) {
106 $target = Join-Path $destination $name
107 $oldHash = File-Hash $target
108 if ($oldHash -and $name -in @('codewhale.exe', 'codew.exe', 'codewhale.bat') -and $claims[$name] -ne $oldHash) {
109 $legacy = $false
110 if ($claims.Count -eq 0) {
111 $primary = File-Hash (Join-Path $destination 'codewhale.exe')
112 $alias = File-Hash (Join-Path $destination 'codew.exe')
113 $launcher = File-Hash (Join-Path $destination 'codewhale.bat')
114 $legacy = $primary -and $primary -eq $alias -and $launcher -eq $sourceLauncherHash
115 }
116 if (!$legacy) { throw "Refusing unclaimed destination $target; the Codewhale install receipt does not own its bytes" }
117 }
118 if ($optional -and $name -like 'codewhale-extension-host*' -and $name -ne 'codewhale-extension-host.release.json' -and $oldHash) {
119 if (!$oldHost) { throw "Refusing unclaimed compiled-host destination $target" }
120 $expected = switch ($name) { 'codewhale-extension-host.exe' { $oldHost.sha256 }; 'codewhale-extension-host.LICENSES.txt' { $oldHost.notices_sha256 }; 'codewhale-extension-host.relink-source.tar.gz' { $oldHost.source_sha256 } }
121 if ($oldHash -ne $expected) { throw "Refusing modified compiled-host destination $target" }
122 }
123 $staged = Join-Path $stage $name
124 Copy-Item -LiteralPath (Join-Path $PSScriptRoot $name) -Destination $staged
125 $newHash = File-Hash $staged
126 if ($newHash -ne (File-Hash (Join-Path $PSScriptRoot $name))) { throw "Source changed during staging: $name" }
127 $backup = Join-Path $stage ($name + '.previous')
128 if ($oldHash) {
129 Copy-Item -LiteralPath $target -Destination $backup
130 if ((File-Hash $backup) -ne $oldHash) { throw "Destination changed during backup: $target" }
131 }
132 $snapshots += [PSCustomObject]@{ Name=$name; Target=$target; Staged=$staged; OldHash=$oldHash; NewHash=$newHash; Backup=$backup }
133 }
134 $receiptStaged = Join-Path $stage $receiptName
135 $receiptText = ($snapshots | Where-Object { $_.Name -in @('codewhale.exe', 'codew.exe', 'codewhale.bat') } | ForEach-Object { "$($_.NewHash) $($_.Name)`n" }) -join ''
136 [IO.File]::WriteAllText($receiptStaged, $receiptText)
137 $receiptOld = File-Hash $receiptTarget
138 $receiptBackup = Join-Path $stage ($receiptName + '.previous')
139 if ($receiptOld) {
140 Copy-Item -LiteralPath $receiptTarget -Destination $receiptBackup
141 if ((File-Hash $receiptBackup) -ne $receiptOld) { throw "Destination changed during backup: $receiptTarget" }
142 }
143 $snapshots += [PSCustomObject]@{ Name=$receiptName; Target=$receiptTarget; Staged=$receiptStaged; OldHash=$receiptOld; NewHash=(File-Hash $receiptStaged); Backup=$receiptBackup }
144 foreach ($row in $snapshots) { if ((File-Hash $row.Target) -ne $row.OldHash) { throw "Destination changed before publication: $($row.Target)" } }
145 foreach ($row in $snapshots) {
146 if ((File-Hash $row.Target) -ne $row.OldHash) { throw "Destination changed during publication: $($row.Target)" }
147 Move-Item -LiteralPath $row.Staged -Destination $row.Target -Force:([bool]$row.OldHash)
148 $published += $row
149 }
150 Write-Host "Installed canonical Codewhale commands to $destination. Node remains the default host. Remove later with: `"$destination\codewhale.exe`" uninstall"
151 $kept = @($published | Where-Object { $_.OldHash -and $_.OldHash -ne $_.NewHash -and (Test-Path -LiteralPath $_.Backup) })
152 if ($kept.Count -gt 0) {
153 $dataRoot = if ($env:CODEWHALE_HOME -and [IO.Path]::IsPathRooted($env:CODEWHALE_HOME)) { $env:CODEWHALE_HOME } else { Join-Path $env:USERPROFILE '.codewhale' }
154 $stamp = [DateTime]::UtcNow.ToString("yyyyMMdd'T'HHmmss'Z'")
155 $recovery = Join-Path (Join-Path $dataRoot 'recovery') $stamp
156 for ($attempt = 1; Test-Path -LiteralPath $recovery; $attempt++) { $recovery = Join-Path (Join-Path $dataRoot 'recovery') "$stamp-$attempt" }
157 [IO.Directory]::CreateDirectory($recovery) | Out-Null
158 $seq = 0
159 foreach ($row in $kept) {
160 $seq++
161 $stored = Join-Path $recovery ('{0:D3}-{1}' -f $seq, $row.Name)
162 Move-Item -LiteralPath $row.Backup -Destination $stored
163 [IO.File]::AppendAllText((Join-Path $recovery 'manifest.tsv'), ("{0}`t{1}`t{2}`t{3}`n" -f $row.Target, $stored, $row.OldHash, (Get-Item -LiteralPath $stored).Length))
164 }
165 Write-Host "Upgraded the earlier Codewhale. Previous files are kept in $recovery for 30 days. Undo: `"$destination\codewhale.exe`" doctor --restore $(Split-Path -Leaf $recovery)"
166 }
167 $priorTelemetry = $env:CODEWHALE_TELEMETRY; $priorUpdateCheck = $env:CODEWHALE_NO_UPDATE_CHECK
168 $env:CODEWHALE_TELEMETRY = '0'; $env:CODEWHALE_NO_UPDATE_CHECK = '1'
169 try { & (Join-Path $destination 'codewhale.exe') doctor --installs --brief 2>$null } catch { } finally { $env:CODEWHALE_TELEMETRY = $priorTelemetry; $env:CODEWHALE_NO_UPDATE_CHECK = $priorUpdateCheck }
170 Write-Host "Usage reporting is on by default (counts only, never your code or conversations). Turn it off: `"$destination\codewhale.exe`" config set telemetry false"
171 $onPath = @($env:Path -split ';' | Where-Object { $_ -and (Path-Key $_) -eq (Path-Key $destination) }).Count -gt 0
172 try { Ensure-UserPath $destination } catch { Write-Warning "Could not update your user PATH: $($_.Exception.Message). Add $destination to it yourself." }
173 Write-Host ''
174 if ($onPath) {
175 Write-Host 'Next: codewhale --version'
176 } else {
177 Write-Host 'Use it in this window now (a PATH change does not reach windows that are already open):'
178 Write-Host " `$env:Path = `"$destination;`$env:Path`""
179 Write-Host 'Then check it:'
180 Write-Host ' codewhale --version'
181 }
182 } catch {
183 $original = $_
184 [array]::Reverse($published)
185 foreach ($row in $published) {
186 try {
187 if ((File-Hash $row.Target) -ne $row.NewHash) { throw "Published file changed; preserved $($row.Target)" }
188 if ($row.OldHash) { Move-Item -LiteralPath $row.Backup -Destination $row.Target -Force }
189 else { Remove-Item -LiteralPath $row.Target }
190 } catch { $retain = $true; Write-Warning $_ }
191 }
192 if ($retain) { Write-Warning "Rollback incomplete; recovery files retained at $stage" }
193 Write-Error $original -ErrorAction Continue
194 exit 1
195 } finally {
196 if ($stage -and !$retain) { Remove-Item -LiteralPath $stage -Recurse -Force }
197 }
198
198 lines Plain Text