Open History to see the last commit
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)
13#
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# Absolute, so PATH never gets a folder that changes with the working directory.
24$binDir = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($binDir)
25
26function Fail([string] $message) {
27 Write-Error "t3 install: $message"
28 exit 1
29}
30
31$terminal = -not [Console]::IsErrorRedirected -and $env:TERM -ne "dumb"
32$interactive = $terminal -and $Host.UI.SupportsVirtualTerminal
33if ($interactive) {
34 # Legacy code pages may support ANSI escapes but not the logo or bar glyphs.
35 $glyphs = -join [char[]](0x2588, 0x2580, 0x2584, 0x25A0, 0x00B7)
36 $encoding = [Console]::Error.Encoding
37 $interactive = $encoding.GetString($encoding.GetBytes($glyphs)) -eq $glyphs
38}
39$esc = [char]27
40$reset = $bold = $muted = $accent = $green = ""
41if ($interactive -and -not $env:NO_COLOR) {
42 $reset = "$esc[0m"; $bold = "$esc[1m"; $muted = "$esc[2m"
43 $accent = "$esc[94m"; $green = "$esc[32m"
44}
45function Step([string] $message) {
46 if ($interactive) { [Console]::Error.Write("`r$esc[2K $muted$message$reset") }
47 else { [Console]::Error.WriteLine(" $message") }
48}
49function Draw-Download([long] $bytes, [long] $total) {
50 if (-not $interactive) { return }
51 $columns = [Console]::WindowWidth
52 if ($columns -le 0) { $columns = 80 }
53 if ($total -gt 0 -and $columns -ge 9) {
54 $percent = [Math]::Min(100, [Math]::Floor($bytes * 100.0 / $total))
55 $width = [Math]::Min(32, $columns - 8)
56 $filled = [int][Math]::Floor($percent * $width / 100)
57 $bar = ([string][char]0x25A0) * $filled
58 $rest = ([string][char]0x00B7) * ($width - $filled)
59 $sizes = (" {0:F1} / {1:F1} MB" -f ($bytes / 1MB), ($total / 1MB))
60 if ($width + 7 + $sizes.Length -ge $columns) { $sizes = "" }
61 [Console]::Error.Write(("`r$esc[2K $accent$bar$reset$muted$rest$reset {0,3}%" -f $percent) + "$muted$sizes$reset")
62 } else {
63 $line = if ($columns -ge 32) { " Downloading {0:F1} MB" -f ($bytes / 1MB) } else { " {0:F1} MB" -f ($bytes / 1MB) }
64 [Console]::Error.Write("`r$esc[2K" + $line.Substring(0, [Math]::Min($line.Length, $columns - 1)))
65 }
66}
67function Fetch([string] $uri, [string] $destination, [switch] $progress) {
68 if (-not $progress -or -not $interactive) {
69 $ProgressPreference = if ($progress -and $terminal) { "Continue" } else { "SilentlyContinue" }
70 Invoke-WebRequest -Uri $uri -OutFile $destination -UseBasicParsing
71 return
72 }
73 Add-Type -AssemblyName System.Net.Http
74 $client = New-Object System.Net.Http.HttpClient
75 $response = $source = $file = $null
76 try {
77 $response = $client.GetAsync($uri, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult()
78 $response.EnsureSuccessStatusCode() | Out-Null
79 $source = $response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()
80 $file = [IO.File]::Create($destination)
81 $buffer = New-Object byte[] 65536
82 $bytes = 0L
83 $clock = [Diagnostics.Stopwatch]::StartNew()
84 Draw-Download 0 $response.Content.Headers.ContentLength
85 while (($count = $source.Read($buffer, 0, $buffer.Length)) -gt 0) {
86 $file.Write($buffer, 0, $count)
87 $bytes += $count
88 if ($clock.ElapsedMilliseconds -ge 100) {
89 Draw-Download $bytes $response.Content.Headers.ContentLength
90 $clock.Restart()
91 }
92 }
93 Draw-Download $bytes $bytes
94 [Console]::Error.WriteLine()
95 } finally {
96 if ($file) { $file.Dispose() }
97 if ($source) { $source.Dispose() }
98 if ($response) { $response.Dispose() }
99 $client.Dispose()
100 }
101}
102if ($interactive) {
103 # Block characters are constructed so this file also loads correctly in PowerShell 5.1.
104 $mark = @(
105 "########## ######## ",
106 " ### _##^ ",
107 " ### ####_ ",
108 " ### _ ###",
109 " ### #######^ "
110 )
111 [Console]::Error.WriteLine()
112 for ($i = 0; $i -lt $mark.Length; $i++) {
113 $row = $mark[$i].Replace('#', [char]0x2588).Replace('^', [char]0x2580).Replace('_', [char]0x2584)
114 $label = if ($i -eq 1) { " ${bold}T3 Code$reset" } elseif ($i -eq 2) { " ${muted}CLI installer$reset" } else { "" }
115 [Console]::Error.WriteLine(" $bold$row$reset$label")
116 }
117 [Console]::Error.WriteLine()
118}
119Step "Finding your release..."
120
121# PROCESSOR_ARCHITEW6432 bypasses WOW64 emulation; 5.1 hosts can lack RuntimeInformation's required .NET version.
122$rawArch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
123$arch = switch ($rawArch) {
124 "AMD64" { "x64" }
125 "ARM64" { "arm64" }
126 default { Fail "unsupported architecture $rawArch" }
127}
128
129$channel = if ($env:T3CODE_CHANNEL) { $env:T3CODE_CHANNEL } else { "stable" }
130$version = $env:T3CODE_VERSION
131if (-not $version) {
132 $tagPattern = switch ($channel) {
133 "stable" { '^v\d+\.\d+\.\d+$' }
134 "nightly" { '^v\d+\.\d+\.\d+-nightly\.\d+\.\d+$' }
135 "preview" { '^v\d+\.\d+\.\d+-preview\.\d+\.\d+$' }
136 default { Fail "T3CODE_CHANNEL must be stable, nightly, or preview" }
137 }
138 if ($channel -eq "stable") {
139 # release.yml marks only plain stable releases latest. This is a github.com
140 # page, so it is not cut off by a page of newer nightlies or the API quota.
141 $release = Invoke-RestMethod -Uri "https://github.com/$repo/releases/latest" -Headers @{ "User-Agent" = "t3-install"; "Accept" = "application/json" }
142 $tag = ($release | Where-Object { $_.tag_name -match $tagPattern }).tag_name
143 } else {
144 $tag = $null
145 for ($page = 1; -not $tag -and $page -le 10; $page++) {
146 $releases = Invoke-RestMethod -Uri "https://api.github.com/repos/$repo/releases?per_page=100&page=$page" -Headers @{ "User-Agent" = "t3-install" }
147 $tag = ($releases | Where-Object { -not $_.draft -and $_.tag_name -match $tagPattern } | Select-Object -First 1).tag_name
148 if (-not $releases) { break }
149 }
150 }
151 if (-not $tag) { Fail "could not find a $channel release; set T3CODE_VERSION" }
152 $version = $tag.Substring(1)
153}
154if ($version -match '-preview\.') {
155 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."
156 if ($channel -ne "preview" -and -not $env:T3CODE_VERSION) {
157 Fail "refusing a preview build that was not explicitly requested"
158 }
159}
160
161$stem = "t3-$version-win32-$arch"
162$archive = "$stem.zip"
163$versionsDir = Join-Path $t3Home "runtime\versions"
164$targetDir = Join-Path $versionsDir $version
165$marker = Join-Path $targetDir ".install-complete"
166
167if ((Test-Path $marker) -and ((Get-Content $marker -Raw).Trim() -eq $version)) {
168 Step "Version $version is already downloaded."
169} else {
170 New-Item -ItemType Directory -Force -Path $versionsDir | Out-Null
171 $staging = Join-Path $versionsDir (".staging-" + [System.IO.Path]::GetRandomFileName())
172 New-Item -ItemType Directory -Path $staging | Out-Null
173 try {
174 if ($interactive) { [Console]::Error.Write("`r$esc[2K") }
175 [Console]::Error.WriteLine(" ${muted}Installing$reset T3 Code $bold$version$reset`n")
176 Step "Downloading..."
177 try {
178 Fetch "$baseUrl/v$version/SHA256SUMS" (Join-Path $staging "SHA256SUMS")
179 } catch {
180 $status = $_.Exception.Response.StatusCode.value__
181 if ($status -eq 404) {
182 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'"
183 }
184 throw
185 }
186 Fetch "$baseUrl/v$version/$archive" (Join-Path $staging $archive) -progress
187
188 Step "Verifying the download..."
189
190 $expected = (Get-Content (Join-Path $staging "SHA256SUMS") | Where-Object { $_ -match "\s\*?$([regex]::Escape($archive))$" } | Select-Object -First 1)
191 if (-not $expected) { Fail "$archive is not listed in SHA256SUMS" }
192 $expected = ($expected -split "\s+")[0].ToLowerInvariant()
193 $actual = (Get-FileHash -Algorithm SHA256 (Join-Path $staging $archive)).Hash.ToLowerInvariant()
194 if ($actual -ne $expected) { Fail "checksum mismatch for $archive" }
195
196 Step "Extracting T3 Code..."
197 # The archive module reads the global preference, not the caller's local scope.
198 $savedProgress = $global:ProgressPreference
199 try {
200 $global:ProgressPreference = "SilentlyContinue"
201 Expand-Archive -Path (Join-Path $staging $archive) -DestinationPath $staging -Force
202 } finally { $global:ProgressPreference = $savedProgress }
203 Get-ChildItem (Join-Path $staging $stem) | Move-Item -Destination $staging
204 Remove-Item (Join-Path $staging $stem), (Join-Path $staging $archive), (Join-Path $staging "SHA256SUMS") -Recurse -Force
205
206 & (Join-Path $staging "t3.exe") --version | Out-Null
207 if ($LASTEXITCODE -ne 0) { Fail "the downloaded executable does not run" }
208 Set-Content -Path (Join-Path $staging ".install-complete") -Value $version -NoNewline
209
210 if (Test-Path $targetDir) { Remove-Item $targetDir -Recurse -Force }
211 Move-Item $staging $targetDir
212 } catch {
213 if (Test-Path $staging) { Remove-Item $staging -Recurse -Force }
214 throw
215 }
216}
217
218Step "Setting up the t3 command..."
219New-Item -ItemType Directory -Force -Path $binDir | Out-Null
220$shim = Join-Path $binDir "t3.cmd"
221# Replace only a shim that runs a version in this home; never the desktop app's or another t3.
222if (Test-Path -LiteralPath $shim) {
223 $existingTarget = ""
224 # The shim is UTF-8 without a BOM; Windows PowerShell 5.1 reads files as ANSI by default.
225 # Only a shim exactly as written here counts; a user's wrapper that also runs t3.exe does not.
226 $existing = [System.IO.File]::ReadAllText($shim, [System.Text.Encoding]::UTF8)
227 if ($existing -match '^@echo off\r?\n"([^"]+)" %\*\s*$') { $existingTarget = $Matches[1] }
228 # Full paths, so a target like versions\..\other cannot pass as ours.
229 $ownedPrefix = [System.IO.Path]::GetFullPath($versionsDir).TrimEnd('\', '/') + [System.IO.Path]::DirectorySeparatorChar
230 if ($existingTarget) { $existingTarget = [System.IO.Path]::GetFullPath($existingTarget) }
231 # Exactly <version>\t3.exe, never another program inside a version.
232 $owned = $existingTarget.StartsWith($ownedPrefix, [System.StringComparison]::OrdinalIgnoreCase) -and
233 ($existingTarget.Substring($ownedPrefix.Length) -match '^[^\\/]+\\t3\.exe$')
234 if (-not $owned) {
235 Fail "another t3 is already at $shim. Remove it and run this again, or run $(Join-Path $targetDir 't3.exe') directly."
236 }
237}
238# UTF-8 without a BOM: cmd.exe reads the shim as-is, and ASCII would corrupt
239# non-ASCII characters in the user's home path.
240[System.IO.File]::WriteAllText($shim, "@echo off`r`n`"$(Join-Path $targetDir 't3.exe')`" %*", (New-Object System.Text.UTF8Encoding $false))
241# Pruning keeps what this shim points at; a background service cannot see $binDir otherwise.
242$launchers = Join-Path $t3Home "runtime\launchers"
243$shimPath = (Resolve-Path -LiteralPath $shim).Path
244if (-not ((Test-Path $launchers) -and ((Get-Content $launchers) -contains $shimPath))) {
245 [System.IO.File]::AppendAllText($launchers, "$shimPath`r`n", (New-Object System.Text.UTF8Encoding $false))
246}
247if ($interactive) { [Console]::Error.Write("`r$esc[2K") }
248[Console]::Error.WriteLine(" ${green}Installed T3 Code $version$reset`n")
249if ($binDir.Contains(";")) {
250 # PATH would split the folder at the `;`, so name the command in full instead.
251 Write-Host " Run ${bold}& '$($shim.Replace("'", "''"))'$reset to get started.`n"
252} else {
253 # Either side may end in a separator. Trim only here: a drive root keeps its `\` for Join-Path.
254 $added = ($env:PATH -split ";" | ForEach-Object { $_.TrimEnd('\', '/') }) -notcontains $binDir.TrimEnd('\', '/')
255 # `irm | iex` runs in the user's own session, so t3 works in this window right away.
256 # Last, so it never shadows another t3.
257 if ($added) { $env:Path = "$env:Path;$binDir" }
258 # A t3 earlier on PATH runs instead, so name this one in full.
259 $first = Get-Command t3 -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
260 if ($first -and [System.IO.Path]::GetFullPath($first.Source) -ne [System.IO.Path]::GetFullPath($shimPath)) {
261 Write-Host " Another t3 at $($first.Source) runs first, so run ${bold}& '$($shim.Replace("'", "''"))'$reset to use this one.`n"
262 } elseif ($added) {
263 Write-Host " Run ${bold}t3$reset to get started. For new windows, add $binDir to your PATH.`n"
264 } else {
265 Write-Host " Run ${bold}t3$reset to use T3 Code here, or ${bold}t3 up$reset to use it from your other devices.`n"
266 }
267}