Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

install.ps1

223 lines10.4 KB

1# Installs the T3 Code CLI from a GitHub Release archive on Windows. Needs
2# only PowerShell 5.1+; no Node, npm, or compiler.
3#
4# irm https://t3.codes/install.ps1 | iex
5#
6# Environment:
7# T3CODE_CHANNEL release train to follow: stable, nightly, or preview
8# (default: stable; preview is a maintainers' test train)
9# T3CODE_VERSION exact version to install (overrides T3CODE_CHANNEL)
10# T3CODE_HOME T3 home directory (default: ~\.t3)
11# T3CODE_INSTALL_BIN_DIR where t3.exe is linked (default: ~\.local\bin)
12# T3CODE_RELEASE_BASE_URL mirror for releases/download (default: GitHub)
14# The archive is unpacked into $T3CODE_HOME\runtime\versions\<version>, the
15# same layout `t3 service install` uses, so the service reuses this download.
16$ErrorActionPreference = "Stop"
17[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
18​
19$repo = "pingdotgg/t3code"
20$baseUrl = if ($env:T3CODE_RELEASE_BASE_URL) { $env:T3CODE_RELEASE_BASE_URL.TrimEnd("/") } else { "https://github.com/$repo/releases/download" }
21$t3Home = if ($env:T3CODE_HOME) { $env:T3CODE_HOME } else { Join-Path $HOME ".t3" }
22$binDir = if ($env:T3CODE_INSTALL_BIN_DIR) { $env:T3CODE_INSTALL_BIN_DIR } else { Join-Path $HOME ".local\bin" }
23​
24function Fail([string] $message) {
25 Write-Error "t3 install: $message"
26 exit 1
28​
29$terminal = -not [Console]::IsErrorRedirected -and $env:TERM -ne "dumb"
30$interactive = $terminal -and $Host.UI.SupportsVirtualTerminal
31if ($interactive) {
32 # Legacy code pages may support ANSI escapes but not the logo or bar glyphs.
33 $glyphs = -join [char[]](0x2588, 0x2580, 0x2584, 0x25A0, 0x00B7)
34 $encoding = [Console]::Error.Encoding
35 $interactive = $encoding.GetString($encoding.GetBytes($glyphs)) -eq $glyphs
37$esc = [char]27
38$reset = $bold = $muted = $accent = $green = ""
39if ($interactive -and -not $env:NO_COLOR) {
40 $reset = "$esc[0m"; $bold = "$esc[1m"; $muted = "$esc[2m"
41 $accent = "$esc[94m"; $green = "$esc[32m"
43function Step([string] $message) {
44 if ($interactive) { [Console]::Error.Write("`r$esc[2K $muted$message$reset") }
45 else { [Console]::Error.WriteLine(" $message") }
47function Draw-Download([long] $bytes, [long] $total) {
48 if (-not $interactive) { return }
49 $columns = [Console]::WindowWidth
50 if ($columns -le 0) { $columns = 80 }
51 if ($total -gt 0 -and $columns -ge 9) {
52 $percent = [Math]::Min(100, [Math]::Floor($bytes * 100.0 / $total))
53 $width = [Math]::Min(32, $columns - 8)
54 $filled = [int][Math]::Floor($percent * $width / 100)
55 $bar = ([string][char]0x25A0) * $filled
56 $rest = ([string][char]0x00B7) * ($width - $filled)
57 $sizes = (" {0:F1} / {1:F1} MB" -f ($bytes / 1MB), ($total / 1MB))
58 if ($width + 7 + $sizes.Length -ge $columns) { $sizes = "" }
59 [Console]::Error.Write(("`r$esc[2K $accent$bar$reset$muted$rest$reset {0,3}%" -f $percent) + "$muted$sizes$reset")
60 } else {
61 $line = if ($columns -ge 32) { " Downloading {0:F1} MB" -f ($bytes / 1MB) } else { " {0:F1} MB" -f ($bytes / 1MB) }
62 [Console]::Error.Write("`r$esc[2K" + $line.Substring(0, [Math]::Min($line.Length, $columns - 1)))
63 }
65function Fetch([string] $uri, [string] $destination, [switch] $progress) {
66 if (-not $progress -or -not $interactive) {
67 $ProgressPreference = if ($progress -and $terminal) { "Continue" } else { "SilentlyContinue" }
68 Invoke-WebRequest -Uri $uri -OutFile $destination -UseBasicParsing
69 return
70 }
71 Add-Type -AssemblyName System.Net.Http
72 $client = New-Object System.Net.Http.HttpClient
73 $response = $source = $file = $null
74 try {
75 $response = $client.GetAsync($uri, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult()
76 $response.EnsureSuccessStatusCode() | Out-Null
77 $source = $response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()
78 $file = [IO.File]::Create($destination)
79 $buffer = New-Object byte[] 65536
80 $bytes = 0L
81 $clock = [Diagnostics.Stopwatch]::StartNew()
82 Draw-Download 0 $response.Content.Headers.ContentLength
83 while (($count = $source.Read($buffer, 0, $buffer.Length)) -gt 0) {
84 $file.Write($buffer, 0, $count)
85 $bytes += $count
86 if ($clock.ElapsedMilliseconds -ge 100) {
87 Draw-Download $bytes $response.Content.Headers.ContentLength
88 $clock.Restart()
89 }
90 }
91 Draw-Download $bytes $bytes
92 [Console]::Error.WriteLine()
93 } finally {
94 if ($file) { $file.Dispose() }
95 if ($source) { $source.Dispose() }
96 if ($response) { $response.Dispose() }
97 $client.Dispose()
98 }
100if ($interactive) {
101 # Block characters are constructed so this file also loads correctly in PowerShell 5.1.
102 $mark = @(
103 "########## ######## ",
104 " ### _##^ ",
105 " ### ####_ ",
106 " ### _ ###",
107 " ### #######^ "
108 )
109 [Console]::Error.WriteLine()
110 for ($i = 0; $i -lt $mark.Length; $i++) {
111 $row = $mark[$i].Replace('#', [char]0x2588).Replace('^', [char]0x2580).Replace('_', [char]0x2584)
112 $label = if ($i -eq 1) { " ${bold}T3 Code$reset" } elseif ($i -eq 2) { " ${muted}CLI installer$reset" } else { "" }
113 [Console]::Error.WriteLine(" $bold$row$reset$label")
114 }
115 [Console]::Error.WriteLine()
117Step "Finding your release..."
118​
119# PROCESSOR_ARCHITEW6432 bypasses WOW64 emulation; 5.1 hosts can lack RuntimeInformation's required .NET version.
120$rawArch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
121$arch = switch ($rawArch) {
122 "AMD64" { "x64" }
123 "ARM64" { "arm64" }
124 default { Fail "unsupported architecture $rawArch" }
126​
127$channel = if ($env:T3CODE_CHANNEL) { $env:T3CODE_CHANNEL } else { "stable" }
128$version = $env:T3CODE_VERSION
129if (-not $version) {
130 $tagPattern = switch ($channel) {
131 "stable" { '^v\d+\.\d+\.\d+$' }
132 "nightly" { '^v\d+\.\d+\.\d+-nightly\.\d+\.\d+$' }
133 "preview" { '^v\d+\.\d+\.\d+-preview\.\d+\.\d+$' }
134 default { Fail "T3CODE_CHANNEL must be stable, nightly, or preview" }
135 }
136 $releases = Invoke-RestMethod -Uri "https://api.github.com/repos/$repo/releases?per_page=100" -Headers @{ "User-Agent" = "t3-install" }
137 $tag = ($releases | Where-Object { -not $_.draft -and $_.tag_name -match $tagPattern } | Select-Object -First 1).tag_name
138 if (-not $tag) { Fail "could not find a $channel release; set T3CODE_VERSION" }
139 $version = $tag.Substring(1)
141if ($version -match '-preview\.') {
142 Write-Warning "t3 $version is a preview build. Preview builds are cut by maintainers from unreleased branches to exercise the release pipeline. They can be broken, receive no fixes, and are never offered as updates. Set T3CODE_CHANNEL=stable (the default) for a supported build."
143 if ($channel -ne "preview" -and -not $env:T3CODE_VERSION) {
144 Fail "refusing a preview build that was not explicitly requested"
145 }
147​
148$stem = "t3-$version-win32-$arch"
149$archive = "$stem.zip"
150$versionsDir = Join-Path $t3Home "runtime\versions"
151$targetDir = Join-Path $versionsDir $version
152$marker = Join-Path $targetDir ".install-complete"
153​
154if ((Test-Path $marker) -and ((Get-Content $marker -Raw).Trim() -eq $version)) {
155 Step "Version $version is already downloaded."
156} else {
157 New-Item -ItemType Directory -Force -Path $versionsDir | Out-Null
158 $staging = Join-Path $versionsDir (".staging-" + [System.IO.Path]::GetRandomFileName())
159 New-Item -ItemType Directory -Path $staging | Out-Null
160 try {
161 if ($interactive) { [Console]::Error.Write("`r$esc[2K") }
162 [Console]::Error.WriteLine(" ${muted}Installing$reset T3 Code $bold$version$reset`n")
163 Step "Downloading..."
164 try {
165 Fetch "$baseUrl/v$version/SHA256SUMS" (Join-Path $staging "SHA256SUMS")
166 } catch {
167 $status = $_.Exception.Response.StatusCode.value__
168 if ($status -eq 404) {
169 Fail "t3 $version has no release archive for win32-$arch; releases before the self-contained CLI can only be installed with 'npm install -g t3@$version'"
170 }
171 throw
172 }
173 Fetch "$baseUrl/v$version/$archive" (Join-Path $staging $archive) -progress
174​
175 Step "Verifying the download..."
176​
177 $expected = (Get-Content (Join-Path $staging "SHA256SUMS") | Where-Object { $_ -match "\s\*?$([regex]::Escape($archive))$" } | Select-Object -First 1)
178 if (-not $expected) { Fail "$archive is not listed in SHA256SUMS" }
179 $expected = ($expected -split "\s+")[0].ToLowerInvariant()
180 $actual = (Get-FileHash -Algorithm SHA256 (Join-Path $staging $archive)).Hash.ToLowerInvariant()
181 if ($actual -ne $expected) { Fail "checksum mismatch for $archive" }
182​
183 Step "Extracting T3 Code..."
184 # The archive module reads the global preference, not the caller's local scope.
185 $savedProgress = $global:ProgressPreference
186 try {
187 $global:ProgressPreference = "SilentlyContinue"
188 Expand-Archive -Path (Join-Path $staging $archive) -DestinationPath $staging -Force
189 } finally { $global:ProgressPreference = $savedProgress }
190 Get-ChildItem (Join-Path $staging $stem) | Move-Item -Destination $staging
191 Remove-Item (Join-Path $staging $stem), (Join-Path $staging $archive), (Join-Path $staging "SHA256SUMS") -Recurse -Force
192​
193 & (Join-Path $staging "t3.exe") --version | Out-Null
194 if ($LASTEXITCODE -ne 0) { Fail "the downloaded executable does not run" }
195 Set-Content -Path (Join-Path $staging ".install-complete") -Value $version -NoNewline
196​
197 if (Test-Path $targetDir) { Remove-Item $targetDir -Recurse -Force }
198 Move-Item $staging $targetDir
199 } catch {
200 if (Test-Path $staging) { Remove-Item $staging -Recurse -Force }
201 throw
202 }
204​
205Step "Setting up the t3 command..."
206New-Item -ItemType Directory -Force -Path $binDir | Out-Null
207$shim = Join-Path $binDir "t3.cmd"
208# UTF-8 without a BOM: cmd.exe reads the shim as-is, and ASCII would corrupt
209# non-ASCII characters in the user's home path.
210[System.IO.File]::WriteAllText($shim, "@echo off`r`n`"$(Join-Path $targetDir 't3.exe')`" %*", (New-Object System.Text.UTF8Encoding $false))
211# Pruning keeps what this shim points at; a background service cannot see $binDir otherwise.
212$launchers = Join-Path $t3Home "runtime\launchers"
213$shimPath = (Resolve-Path $shim).Path
214if (-not ((Test-Path $launchers) -and ((Get-Content $launchers) -contains $shimPath))) {
215 [System.IO.File]::AppendAllText($launchers, "$shimPath`r`n", (New-Object System.Text.UTF8Encoding $false))
217if ($interactive) { [Console]::Error.Write("`r$esc[2K") }
218[Console]::Error.WriteLine(" ${green}Installed T3 Code $version$reset`n")
219if (($env:PATH -split ";") -notcontains $binDir) {
220 Write-Host " Add $binDir to your PATH, then run ${bold}t3$reset.`n"
221} else {
222 Write-Host " Run ${bold}t3$reset to get started.`n"