Repository navigation
Expand file tree
/
Copy pathinstall.ps1
More file actions
1126 lines (1020 loc) · 46.2 KB
/
Copy pathinstall.ps1
File metadata and controls
1126 lines (1020 loc) · 46.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# autter installer for Windows (Windows PowerShell 5.1 and PowerShell 7+).
#
# Usage (works from PowerShell, cmd.exe, and Git Bash):
# powershell -NoProfile -ExecutionPolicy Bypass -Command "iex (irm https://api.autter.dev/install.ps1)"
# or, already inside PowerShell (autter is then usable in that window at once):
# irm https://api.autter.dev/install.ps1 | iex
#
# Dry run (prints what would be downloaded, written and started, and changes
# nothing). iex cannot pass arguments, so it is an environment variable:
# $env:AUTTER_INSTALL_DRY_RUN = '1'
# irm https://api.autter.dev/install.ps1 | iex
# Remove-Item Env:\AUTTER_INSTALL_DRY_RUN
#
# Rules for editing this file, because it usually runs through `irm | iex`:
# - Keep it pure ASCII. irm decodes with whatever charset the server sends,
# and a mis-decoded em-dash or smart quote can become a quote character
# that PowerShell parses as a string delimiter. CI enforces this.
# - iex runs the text in the CALLER's scope (the user's own shell), so the
# whole body lives in the scriptblock below: preferences, StrictMode, and
# helper functions stay inside it instead of leaking into the session.
# - Never call `exit`: under iex it closes the user's terminal. Fail with
# Write-ErrorAndExit, which throws; -File/-Command runs still exit 1.
# - No param() block, $PSScriptRoot, or $MyInvocation paths (none exist
# under iex); take input from environment variables.
# - Windows PowerShell 5.1 syntax only: no ??, ?., ternaries, && / ||.
# CI parses this file with both powershell.exe and pwsh.
#
# The body below is intentionally not indented, to keep diffs readable.
& {
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
# Dry run: print the plan and return before anything is downloaded, written
# or started (see the block after the release tag is determined).
$dryRun = ($env:AUTTER_INSTALL_DRY_RUN -eq '1')
# What to try when a download from GitHub fails (a 502, a proxy, a blocked
# host): the npm package installs the same binary and is a second route.
# The two commands are on separate lines because Windows PowerShell 5.1 has
# no operator that chains them.
$NpmFallbackHint = "This is usually temporary: wait a minute and run the installer again.`nIf it keeps failing on this network, install with npm instead (needs Node.js 18+):`n npm install -g @autter/cli`n autter onboard"
# Set when the background service was running and was stopped to replace
# its binary: it is started again at the end, on whatever binary is then in
# place (also when the install fails and the previous binary stays).
$serviceWasRunning = $false
function Start-DaemonIfRequested {
if ($env:AUTTER_RESTART_DAEMON_AFTER_INSTALL -ne '1' -and -not $serviceWasRunning) {
return
}
# A dry run starts nothing, also when it stops on an error.
if ($dryRun) { return }
$daemonExe = Join-Path $HOME '.autter\bin\autter.exe'
if (-not (Test-Path $daemonExe)) {
Write-Warning 'Warning: Failed to locate autter.exe for daemon restart after install.'
return
}
try {
& $daemonExe bg start *> $null
} catch {
Write-Warning 'Warning: Failed to restart autter background service automatically.'
}
}
function Write-ErrorAndExit {
param(
[Parameter(Mandatory = $true)][string]$Message
)
Write-Host "Error: $Message" -ForegroundColor Red
Start-DaemonIfRequested
# Throw, never `exit`: under `irm | iex` exit would close the user's
# terminal. An uncaught throw still makes `powershell -File` and
# `powershell -Command` exit 1. Do not call this inside a try block whose
# catch would intercept the throw and report the failure a second time.
throw "autter install failed: $Message"
}
function Write-Success {
param(
[Parameter(Mandatory = $true)][string]$Message
)
Write-Host $Message -ForegroundColor Green
}
function Write-Warning {
param(
[Parameter(Mandatory = $true)][string]$Message
)
Write-Host $Message -ForegroundColor Yellow
}
function Normalize-PathString {
param(
[Parameter(Mandatory = $true)][string]$Path
)
try {
return ([IO.Path]::GetFullPath($Path.Trim())).TrimEnd('\').ToLowerInvariant()
} catch {
return ($Path.Trim()).TrimEnd('\').ToLowerInvariant()
}
}
function Test-FileAvailable {
param(
[Parameter(Mandatory = $true)][string]$Path
)
try {
$stream = [System.IO.File]::Open($Path, 'Open', 'Write', 'None')
$stream.Close()
return $true
} catch {
return $false
}
}
function Stop-AutterBackgroundService {
param(
[Parameter(Mandatory = $true)][string]$AutterExe,
[Parameter(Mandatory = $false)][switch]$Hard
)
if (-not (Test-Path -LiteralPath $AutterExe)) {
return $false
}
# Not $args: that is an automatic variable.
$bgArgs = @('bg', 'shutdown')
if ($Hard) {
$bgArgs += '--hard'
}
try {
& $AutterExe @bgArgs *> $null
return $LASTEXITCODE -eq 0
} catch {
return $false
}
}
function Wait-ForFileAvailable {
param(
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $false)][int]$MaxWaitSeconds = 10
)
$deadline = (Get-Date).AddSeconds($MaxWaitSeconds)
while ((Get-Date) -lt $deadline) {
if (Test-FileAvailable -Path $Path) {
return $true
}
Start-Sleep -Milliseconds 250
}
return (Test-FileAvailable -Path $Path)
}
# Stop the background service before its binary is replaced, the way
# `autter bg shutdown` does, and wait for it to let go of the file. Returns
# whether a service was running, so it is started again afterwards. A file
# that stays held is not fatal: Install-ExecutableFile renames it aside.
function Stop-ServiceForReplace {
param(
[Parameter(Mandatory = $true)][string]$AutterExe
)
if (-not (Test-Path -LiteralPath $AutterExe)) {
return $false
}
$wasRunning = Stop-AutterBackgroundService -AutterExe $AutterExe
if ($wasRunning) {
Write-Host 'Stopped the autter background service to replace its binary.'
if (-not (Wait-ForFileAvailable -Path $AutterExe -MaxWaitSeconds 15)) {
[void](Stop-AutterBackgroundService -AutterExe $AutterExe -Hard)
[void](Wait-ForFileAvailable -Path $AutterExe -MaxWaitSeconds 5)
}
}
return $wasRunning
}
# Put $Source at $Destination. Windows does not replace or delete an .exe that
# a running process has open (the background service, a git command run
# through autter, `autter upgrade` itself), but it does rename one. So the
# file in place is renamed aside to <name>.old (or <name>.<pid>.old) and the
# new one moved in; if that fails, the old one is moved back. The aside file
# is deleted by Remove-LeftoverExecutables once nothing runs it.
# Returns @{ Error = $null or why it failed; Aside = $null or the aside path }.
function Install-ExecutableFile {
param(
[Parameter(Mandatory = $true)][string]$Source,
[Parameter(Mandatory = $true)][string]$Destination
)
$aside = $null
if (Test-Path -LiteralPath $Destination) {
$aside = "$Destination.old"
if (Test-Path -LiteralPath $aside) {
try {
Remove-Item -LiteralPath $aside -Force -ErrorAction Stop
} catch {
$aside = "$Destination.$PID.old"
}
}
try {
[IO.File]::Move($Destination, $aside)
} catch {
return [PSCustomObject]@{ Error = $_.Exception.Message; Aside = $null }
}
}
try {
[IO.File]::Move($Source, $Destination)
} catch {
$reason = $_.Exception.Message
if ($aside) {
try {
[IO.File]::Move($aside, $Destination)
} catch {
$reason += " The previous file could not be put back either: rename $aside to $Destination."
}
}
return [PSCustomObject]@{ Error = $reason; Aside = $null }
}
return [PSCustomObject]@{ Error = $null; Aside = $aside }
}
# Put the previous binary back after the new one failed its check.
function Restore-PreviousExecutable {
param(
[Parameter(Mandatory = $false)][string]$Aside,
[Parameter(Mandatory = $true)][string]$Destination
)
if (-not $Aside -or -not (Test-Path -LiteralPath $Aside)) {
return $false
}
try {
Remove-Item -LiteralPath $Destination -Force -ErrorAction SilentlyContinue
[IO.File]::Move($Aside, $Destination)
return $true
} catch {
return $false
}
}
# Delete binaries renamed aside by earlier installs that nothing runs any
# more. One still running stays until the next install (the background
# service also deletes them when it starts).
function Remove-LeftoverExecutables {
param(
[Parameter(Mandatory = $true)][string]$InstallDir
)
foreach ($pattern in @('autter.exe.*old', 'git.exe.*old')) {
foreach ($leftover in @(Get-ChildItem -LiteralPath $InstallDir -Filter $pattern -File -ErrorAction SilentlyContinue)) {
try { Remove-Item -LiteralPath $leftover.FullName -Force -ErrorAction Stop } catch { }
}
}
}
function Verify-Checksum {
param(
[Parameter(Mandatory = $true)][string]$File,
[Parameter(Mandatory = $true)][string]$BinaryName
)
# Local developer installs do not download a release artifact.
if (-not [string]::IsNullOrWhiteSpace($env:AUTTER_LOCAL_BINARY)) {
return
}
if ($EmbeddedChecksums -eq $ChecksumsSentinel) {
Write-ErrorAndExit "Release checksums were not loaded; refusing to install $BinaryName"
}
# Extract expected checksum for this binary
$expected = $null
$entries = $EmbeddedChecksums -split '\|'
foreach ($entry in $entries) {
if ($entry -match "^([0-9a-fA-F]{64})\s+$([regex]::Escape($BinaryName))$") {
$expected = $Matches[1].ToLowerInvariant()
break
}
}
if (-not $expected) {
Write-ErrorAndExit "No checksum found for $BinaryName"
}
# Calculate actual checksum
$hashCommand = Get-Command Get-FileHash -ErrorAction SilentlyContinue
if ($null -ne $hashCommand) {
$actual = (Get-FileHash -Path $File -Algorithm SHA256).Hash.ToLower()
} else {
$sha256 = $null
$stream = [System.IO.File]::OpenRead($File)
try {
$sha256 = [System.Security.Cryptography.SHA256]::Create()
$hashBytes = $sha256.ComputeHash($stream)
$actual = ([System.BitConverter]::ToString($hashBytes)).Replace('-', '').ToLower()
} finally {
$stream.Dispose()
if ($sha256) {
$sha256.Dispose()
}
}
}
if ($expected -ne $actual) {
Remove-Item -Force -ErrorAction SilentlyContinue $File
Write-ErrorAndExit "Checksum verification failed for $BinaryName`nExpected: $expected`nActual: $actual"
}
Write-Success "Checksum verified for $BinaryName"
}
# Release-fill placeholders. The release workflow blindly string-replaces each
# placeholder token EVERYWHERE in this file, so the guards below compare
# against *Sentinel values built by concatenation - those survive the fill.
# Comparing against the literal token would self-destruct on fill: the pinned
# copy would ignore its version pin and skip checksum verification.
# Repository ("owner/repo"); the sentinel defaults to the canonical repo.
$Repo = '__REPO_PLACEHOLDER__'
$RepoSentinel = '__REPO_' + 'PLACEHOLDER__'
if ($Repo -eq $RepoSentinel) {
$Repo = 'autter-dev/autter-cli'
}
# Version pin (e.g. "v1.6.8") in release copies; the sentinel means "latest".
$PinnedVersion = '__VERSION_PLACEHOLDER__'
$VersionSentinel = '__VERSION_' + 'PLACEHOLDER__'
# Pipe-separated "sha256 filename" entries in release copies. Public installer
# copies replace the sentinel by downloading the release's checksums.txt.
$EmbeddedChecksums = '__CHECKSUMS_PLACEHOLDER__'
$ChecksumsSentinel = '__CHECKSUMS_' + 'PLACEHOLDER__'
# Ensure TLS 1.2 for GitHub downloads on Windows PowerShell 5.1, whose .NET
# Framework may default to SSL3/TLS 1.0 only. This setting is process-wide, so
# under iex it is the user's own session: leave SystemDefault (0, the OS picks,
# including TLS 1.3) alone and otherwise only add TLS 1.2 with -bor instead of
# overwriting the list. (PowerShell 7's web cmdlets ignore this setting.)
# A dry run makes no request, so it leaves the setting alone.
if (-not $dryRun) {
try {
$securityProtocol = [Net.ServicePointManager]::SecurityProtocol
if ([int]$securityProtocol -ne 0 -and -not ($securityProtocol -band [Net.SecurityProtocolType]::Tls12)) {
[Net.ServicePointManager]::SecurityProtocol = $securityProtocol -bor [Net.SecurityProtocolType]::Tls12
}
} catch { }
}
function Get-Architecture {
# Environment variables first: they exist on every PowerShell version.
# PROCESSOR_ARCHITEW6432 is set when a 32-bit shell runs on a 64-bit OS
# (WOW64), where PROCESSOR_ARCHITECTURE misreports 'x86'.
foreach ($pa in @($env:PROCESSOR_ARCHITEW6432, $env:PROCESSOR_ARCHITECTURE)) {
if ([string]::IsNullOrWhiteSpace($pa)) { continue }
if ($pa -match 'ARM64') { return 'arm64' }
if ($pa -match '64') { return 'x64' }
}
# Fallback: RuntimeInformation, which some Windows PowerShell 5.1 hosts
# cannot resolve (the type lives in a facade assembly that is not always
# loaded), so it may throw rather than return.
try {
switch ("$([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture)") {
'X64' { return 'x64' }
'Arm64' { return 'arm64' }
}
} catch { }
return $null
}
# Ensure $PathToAdd is on the User PATH (appended if absent). No Machine PATH,
# no admin required, no positioning logic.
function Set-PathEnsureContains {
param(
[Parameter(Mandatory = $true)][string]$PathToAdd
)
$sep = ';'
function NormalizePath([string]$p) {
try { return ([IO.Path]::GetFullPath($p.Trim())).TrimEnd('\\').ToLowerInvariant() }
catch { return ($p.Trim()).TrimEnd('\\').ToLowerInvariant() }
}
$normalizedAdd = NormalizePath $PathToAdd
try {
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
$entries = @()
if ($userPath) { $entries = ($userPath -split $sep) | Where-Object { $_ -and $_.Trim() -ne '' } }
$alreadyPresent = $false
foreach ($e in $entries) {
if ((NormalizePath $e) -eq $normalizedAdd) { $alreadyPresent = $true; break }
}
if ($alreadyPresent) {
$userStatus = 'AlreadyPresent'
} else {
$newUserPath = if ($userPath) { "$userPath$sep$PathToAdd" } else { $PathToAdd }
[Environment]::SetEnvironmentVariable('Path', $newUserPath, 'User')
$userStatus = 'Updated'
}
} catch {
$userStatus = 'Error'
}
# Also update the current process PATH. Under `irm | iex` this process IS
# the user's PowerShell window, so `autter` resolves there immediately
# (issue #11). Prepend, so a stale autter.exe elsewhere on PATH cannot
# shadow the one just installed. A child process (`powershell -Command`)
# cannot reach its parent shell; the final notice covers that case.
try {
$procPath = $env:PATH
$procEntries = @()
if ($procPath) { $procEntries = ($procPath -split $sep) | Where-Object { $_ -and $_.Trim() -ne '' } }
$procHas = $false
foreach ($e in $procEntries) {
if ((NormalizePath $e) -eq $normalizedAdd) { $procHas = $true; break }
}
if (-not $procHas) {
$env:PATH = if ($procPath) { "$PathToAdd$sep$procPath" } else { $PathToAdd }
}
} catch { }
return [PSCustomObject]@{
UserStatus = $userStatus
}
}
# Whether $PathToCheck is already an entry of the persistent User PATH. Reads
# only; the dry run uses it to say what a real install would change.
function Test-UserPathContains {
param(
[Parameter(Mandatory = $true)][string]$PathToCheck
)
try {
$wanted = Normalize-PathString $PathToCheck
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
if (-not $userPath) { return $false }
foreach ($entry in ($userPath -split ';')) {
if ($entry -and $entry.Trim() -ne '' -and (Normalize-PathString $entry) -eq $wanted) {
return $true
}
}
} catch { }
return $false
}
# Git Bash (MSYS2/MinGW) puts its own directories in front of the Windows
# PATH, so the installer adds one PATH line to a bash profile. Returns $null
# when Git for Windows is not installed, else the profile that line goes in
# (~/.bashrc if it exists, else an existing ~/.bash_profile, else a new
# ~/.bashrc) and whether it is already there. Reads only: the install and the
# dry run both call it, so the dry run reports what the install would do.
function Get-GitBashPlan {
$gitBashInstalled = $false
$gitForWindowsPaths = @()
if ($env:ProgramFiles) { $gitForWindowsPaths += Join-Path $env:ProgramFiles 'Git\bin\bash.exe' }
if (${env:ProgramFiles(x86)}) { $gitForWindowsPaths += Join-Path ${env:ProgramFiles(x86)} 'Git\bin\bash.exe' }
if ($env:LOCALAPPDATA) { $gitForWindowsPaths += Join-Path $env:LOCALAPPDATA 'Programs\Git\bin\bash.exe' }
foreach ($p in $gitForWindowsPaths) {
if ($p -and (Test-Path -LiteralPath $p)) {
$gitBashInstalled = $true
break
}
}
if (-not $gitBashInstalled) {
return $null
}
$bashrcPath = Join-Path $HOME '.bashrc'
$bashProfilePath = Join-Path $HOME '.bash_profile'
if (Test-Path -LiteralPath $bashrcPath) {
$targetBashConfig = $bashrcPath
} elseif (Test-Path -LiteralPath $bashProfilePath) {
$targetBashConfig = $bashProfilePath
} else {
# No existing config; the install creates .bashrc
$targetBashConfig = $bashrcPath
}
$alreadyPresent = $false
if (Test-Path -LiteralPath $targetBashConfig) {
$content = Get-Content -LiteralPath $targetBashConfig -Raw -ErrorAction SilentlyContinue
if ($content -and $content.Contains('.autter/bin')) {
$alreadyPresent = $true
}
}
return [PSCustomObject]@{
Path = $targetBashConfig
AlreadyConfigured = $alreadyPresent
}
}
# Detect architecture and OS
$arch = Get-Architecture
if (-not $arch) {
# Do NOT probe RuntimeInformation here: on hosts where it is unavailable
# that probe itself throws, replacing this message with an unrelated
# PropertyNotFound/TypeNotFound error.
$reported = if ([string]::IsNullOrWhiteSpace($env:PROCESSOR_ARCHITECTURE)) { 'unknown' } else { $env:PROCESSOR_ARCHITECTURE }
Write-ErrorAndExit "Unsupported architecture (PROCESSOR_ARCHITECTURE='$reported'). autter provides Windows binaries for x64 and arm64."
}
$os = 'windows'
# git is required - autter wraps git and cannot function without it.
$gitFound = $false
try {
$null = & git --version 2>&1
$gitFound = ($LASTEXITCODE -eq 0)
} catch { }
if (-not $gitFound) {
Write-ErrorAndExit 'git is required but not found. Install Git for Windows (https://git-scm.com/download/win) and re-run the installer.'
}
# Determine binary name and download URLs
$binaryName = "autter-$os-$arch"
# Determine release tag
# Priority: 1. Local binary override, 2. Pinned version (for release builds), 3. Environment variable, 4. "latest"
if (-not [string]::IsNullOrWhiteSpace($env:AUTTER_LOCAL_BINARY)) {
$releaseTag = 'local'
} elseif ($PinnedVersion -ne $VersionSentinel) {
# Version-pinned install script from a release
$releaseTag = $PinnedVersion
$downloadUrlExe = "https://github.com/$Repo/releases/download/$releaseTag/$binaryName.exe"
$downloadUrlNoExt = "https://github.com/$Repo/releases/download/$releaseTag/$binaryName"
} elseif (-not [string]::IsNullOrWhiteSpace($env:AUTTER_RELEASE_TAG) -and $env:AUTTER_RELEASE_TAG -ne 'latest') {
# Environment variable override
$releaseTag = $env:AUTTER_RELEASE_TAG
$downloadUrlExe = "https://github.com/$Repo/releases/download/$releaseTag/$binaryName.exe"
$downloadUrlNoExt = "https://github.com/$Repo/releases/download/$releaseTag/$binaryName"
} else {
# Resolve the latest-release redirect to a concrete tag below.
$releaseTag = 'latest'
}
# Dry run: say what would happen and stop before the first network request.
# `return` leaves the scriptblock this whole file runs in; nothing below runs.
if ($dryRun) {
$dryInstallDir = Join-Path $HOME '.autter\bin'
$dryExe = Join-Path $dryInstallDir 'autter.exe'
$drySteps = New-Object System.Collections.Generic.List[string]
if (-not [string]::IsNullOrWhiteSpace($env:AUTTER_LOCAL_BINARY)) {
[void]$drySteps.Add("copy the local binary $($env:AUTTER_LOCAL_BINARY)")
} elseif ($releaseTag -eq 'latest') {
[void]$drySteps.Add("download $binaryName.exe from the latest release at https://github.com/$Repo/releases/latest and check its SHA-256 against that release's checksums.txt")
} else {
[void]$drySteps.Add("download $downloadUrlExe and check its SHA-256 against that release's checksums.txt")
}
if (Test-Path -LiteralPath $dryExe) {
[void]$drySteps.Add("replace $dryExe (the autter background service is stopped first and started again afterwards; a file still in use is renamed aside to autter.exe.old)")
} else {
[void]$drySteps.Add("install it as $dryExe")
}
if (Test-Path -LiteralPath (Join-Path $dryInstallDir 'git.exe')) {
[void]$drySteps.Add("refresh the copy at $(Join-Path $dryInstallDir 'git.exe')")
}
if ($env:AUTTER_SKIP_PATH_UPDATE -eq '1') {
[void]$drySteps.Add('leave PATH as it is (AUTTER_SKIP_PATH_UPDATE=1)')
} elseif (Test-UserPathContains -PathToCheck $dryInstallDir) {
[void]$drySteps.Add("leave your user PATH as it is ($dryInstallDir is already on it) and add it to this window's PATH")
} else {
[void]$drySteps.Add("add $dryInstallDir to your user PATH (for new terminals) and to this window's PATH")
}
$dryGitBash = $null
try { $dryGitBash = Get-GitBashPlan } catch { }
if ($dryGitBash) {
if ($dryGitBash.AlreadyConfigured) {
[void]$drySteps.Add("leave $($dryGitBash.Path) as it is (it already puts autter on the Git Bash PATH)")
} else {
[void]$drySteps.Add("add one line to $($dryGitBash.Path) that puts autter on the Git Bash PATH")
}
}
if ($env:AUTTER_NO_INSTALL_PING -eq '1' -or -not [string]::IsNullOrWhiteSpace($env:AUTTER_LOCAL_BINARY)) {
[void]$drySteps.Add('send no install ping')
} else {
[void]$drySteps.Add('send one anonymous install ping (OS, CPU architecture and version only; AUTTER_NO_INSTALL_PING=1 turns it off)')
}
if ($env:INSTALL_NONCE -and $env:API_BASE) {
[void]$drySteps.Add('sign this machine in with the single-use setup token from the dashboard')
}
[void]$drySteps.Add("run 'autter onboard', which asks before it installs agent hooks, changes your global git config or starts the background service")
if ($env:AUTTER_RESTART_DAEMON_AFTER_INSTALL -eq '1') {
[void]$drySteps.Add('start the autter background service again (AUTTER_RESTART_DAEMON_AFTER_INSTALL=1)')
}
Write-Host 'Dry run: nothing is downloaded, written or started.'
Write-Host ''
Write-Host 'The installer would:'
$dryStepNumber = 0
foreach ($dryStep in $drySteps) {
$dryStepNumber++
Write-Host (' {0}. {1}' -f $dryStepNumber, $dryStep)
}
Write-Host ''
Write-Host 'To install, clear the variable and run the installer again:'
Write-Host ' Remove-Item Env:\AUTTER_INSTALL_DRY_RUN'
Write-Host 'To undo an install later: autter uninstall'
return
}
# Resolve a specific release and load the checksum file produced by release.yml
# before downloading the executable. A missing/malformed checksum is fatal.
if ([string]::IsNullOrWhiteSpace($env:AUTTER_LOCAL_BINARY)) {
# Failures inside these try blocks are recorded and reported after them:
# Write-ErrorAndExit throws, and a surrounding catch would intercept it.
if ($releaseTag -eq 'latest') {
$latestUrl = $null
$latestError = $null
$latestReleaseUrl = "https://github.com/$Repo/releases/latest"
try {
$latestResponse = Invoke-WebRequest -Uri $latestReleaseUrl -Method Head -UseBasicParsing -ErrorAction Stop
$latestResponseUriProperty = $latestResponse.BaseResponse.PSObject.Properties['ResponseUri']
$latestUrl = if ($latestResponseUriProperty -and $latestResponseUriProperty.Value) {
$latestResponse.BaseResponse.ResponseUri.AbsoluteUri
} else {
$latestResponse.BaseResponse.RequestMessage.RequestUri.AbsoluteUri
}
} catch {
$latestError = $_.Exception.Message
}
if ($latestError) {
Write-ErrorAndExit "Failed to resolve the latest release from ${latestReleaseUrl}: $latestError`n`n$NpmFallbackHint"
}
if ("$latestUrl" -notmatch '/releases/tag/([^/?]+)') {
Write-ErrorAndExit 'Failed to resolve latest release to a specific version'
}
$releaseTag = $Matches[1]
}
$checksumsUrl = "https://github.com/$Repo/releases/download/$releaseTag/checksums.txt"
$checksumsTmp = [IO.Path]::GetTempFileName()
$checksumsError = $null
try {
$oldProgressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
try {
$null = Invoke-WebRequest -Uri $checksumsUrl -OutFile $checksumsTmp -UseBasicParsing -ErrorAction Stop
} finally {
$ProgressPreference = $oldProgressPreference
}
$EmbeddedChecksums = ((Get-Content -LiteralPath $checksumsTmp) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) -join '|'
} catch {
$checksumsError = $_.Exception.Message
} finally {
Remove-Item -Force -ErrorAction SilentlyContinue $checksumsTmp
}
if ($checksumsError) {
Write-ErrorAndExit "Failed to download release checksums from ${checksumsUrl}: $checksumsError`n`n$NpmFallbackHint"
}
if ([string]::IsNullOrWhiteSpace($EmbeddedChecksums)) {
Write-ErrorAndExit 'Release checksums are empty'
}
$downloadUrlExe = "https://github.com/$Repo/releases/download/$releaseTag/$binaryName.exe"
$downloadUrlNoExt = "https://github.com/$Repo/releases/download/$releaseTag/$binaryName"
}
# ============================================================
# Anonymous install ping.
# One fire-and-forget event so we can count installs. Contains only:
# OS, CPU architecture, requested release tag, and whether this run
# is a fresh install or a daemon self-upgrade. No hostname, username,
# paths, or any personal data. Disable with AUTTER_NO_INSTALL_PING=1.
# The API key is a public write-only project token (same one baked
# into release builds for opt-in telemetry).
# ============================================================
function Send-InstallPing {
if ($env:AUTTER_NO_INSTALL_PING -eq '1' -or -not [string]::IsNullOrWhiteSpace($env:AUTTER_LOCAL_BINARY)) { return }
$trigger = if (-not [string]::IsNullOrWhiteSpace($env:AUTTER_DAEMON_UPGRADE)) { 'upgrade' } else { 'install' }
# Keep daemon self-upgrades quiet; tell interactive installers what is sent
if ($trigger -eq 'install') {
Write-Host 'Counting this install with an anonymous ping (OS, architecture, and version only).'
Write-Host 'Set AUTTER_NO_INSTALL_PING=1 to disable.'
}
# releaseTag can come from an env var; sanitize before embedding
$safeTag = ($releaseTag -replace '[^A-Za-z0-9._-]', '')
$payload = @{
api_key = 'phc_aWveMd1bPhuEYtFnCS1G2IHgln3iGQqjfIdkfnuolxI'
event = 'install_script_run'
distinct_id = [guid]::NewGuid().ToString()
properties = @{
os = $os
arch = $arch
release_tag = $safeTag
trigger = $trigger
source = 'install.ps1'
}
} | ConvertTo-Json -Compress
try {
$null = Invoke-RestMethod -Uri 'https://us.i.posthog.com/capture/' -Method Post -ContentType 'application/json' -Body $payload -TimeoutSec 5
} catch { }
}
Send-InstallPing
# ============================================================
# Warn when installing as Administrator (not recommended).
# Running elevated creates files that normal-user processes
# cannot access, causing persistent daemon lock failures.
# ============================================================
$isElevated = $false
try {
# Detect explicit UAC elevation ("Run as Administrator") via TokenElevationType.
# Type 1 (Default) = no split token (UAC disabled or built-in Admin) -> no warn
# Type 2 (Full) = elevated half of a split token -> WARN (this is the danger case)
# Type 3 (Limited) = non-elevated half of a split token -> no warn
# We only warn on type 2: user explicitly elevated, so files will be admin-owned
# but normal processes won't be, causing the daemon.lock mismatch from issue #1287.
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public static class AutterElevation {
[DllImport("advapi32.dll", SetLastError=true)]
static extern bool OpenProcessToken(IntPtr h, uint access, out IntPtr token);
[DllImport("advapi32.dll", SetLastError=true)]
static extern bool GetTokenInformation(IntPtr token, int cls, ref int info, int len, out int ret);
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")]
static extern bool CloseHandle(IntPtr h);
public static bool IsElevated() {
IntPtr tok;
if (!OpenProcessToken(GetCurrentProcess(), 0x0008, out tok)) return false;
try {
int elevType = 0; int sz;
// TokenElevationType = class 18; returns 1/2/3
if (!GetTokenInformation(tok, 18, ref elevType, 4, out sz)) return false;
return elevType == 2; // TokenElevationTypeFull
} finally { CloseHandle(tok); }
}
}
"@ -ErrorAction SilentlyContinue
$isElevated = [AutterElevation]::IsElevated()
} catch { }
if ($isElevated -and $env:AUTTER_ALLOW_SUPERUSER -ne '1') {
# Auto-allow in CI environments and daemon-triggered self-updates
$isCi = $env:CI -or $env:GITHUB_ACTIONS -or $env:GITLAB_CI -or $env:JENKINS_URL `
-or $env:BUILDKITE -or $env:CIRCLECI -or $env:CODEBUILD_BUILD_ID `
-or $env:AGENT_OS -or $env:KUBERNETES_SERVICE_HOST `
-or $env:AUTTER_DAEMON_UPGRADE -or $env:container
if (-not $isCi) {
Write-Host ''
Write-Host 'Warning: installing autter as Administrator is not recommended.' -ForegroundColor Yellow
Write-Host ''
Write-Host 'Running with elevated privileges creates files owned by Administrator that'
Write-Host 'become inaccessible to your normal user account, causing persistent daemon'
Write-Host 'lock failures. A future version may refuse to install in this configuration.'
Write-Host ''
Write-Host 'To suppress this warning, either:'
Write-Host ' - Run this installer from a normal (non-elevated) PowerShell window (recommended), or'
Write-Host ' - Set $env:AUTTER_ALLOW_SUPERUSER = "1"' -ForegroundColor Yellow
Write-Host ''
}
# Propagate to child autter invocations (install-hooks, exchange-nonce, login)
$env:AUTTER_ALLOW_SUPERUSER = '1'
}
# Install directory: %USERPROFILE%\.autter\bin
$installDir = Join-Path $HOME ".autter\bin"
New-Item -ItemType Directory -Force -Path $installDir | Out-Null
Write-Host ("Downloading autter (release: {0})..." -f $releaseTag)
$tmpFile = Join-Path $installDir "autter.tmp.$PID.exe"
# Each failed attempt is recorded as "<url> -> <reason>" so the final error
# can report exactly what was tried instead of an opaque "HTTP error".
$downloadFailures = New-Object System.Collections.Generic.List[string]
# Show download progress only when a person is watching: not in CI, not for
# the background service's self-upgrade, and not when output is redirected
# to a file or another program. AUTTER_INSTALL_PROGRESS=1 or 0 forces it on
# or off (CI sets 1 to exercise the progress download).
function Test-ShowDownloadProgress {
if ($env:AUTTER_INSTALL_PROGRESS -eq '1') { return $true }
if ($env:AUTTER_INSTALL_PROGRESS -eq '0') { return $false }
if ($env:CI -or $env:GITHUB_ACTIONS -or $env:AUTTER_DAEMON_UPGRADE) { return $false }
try {
return ([Environment]::UserInteractive -and -not [Console]::IsOutputRedirected)
} catch {
return $false
}
}
function Format-DownloadProgress {
param(
[Parameter(Mandatory = $true)][long]$Done,
[Parameter(Mandatory = $true)][long]$Total
)
if ($Total -gt 0) {
$percent = [int][Math]::Floor(($Done * 100.0) / $Total)
return (' {0,6:F1} MB of {1:F1} MB ({2,3}%)' -f ($Done / 1MB), ($Total / 1MB), $percent)
}
return (' {0,6:F1} MB' -f ($Done / 1MB))
}
# Download $Url to $OutFile and show how far along it is on one status line.
#
# Invoke-WebRequest's own progress bar is not an option: Windows PowerShell
# 5.1 redraws it for every chunk received, which makes the download many
# times slower. This copies the response stream to the file in 80 KB chunks
# and rewrites one line of text at most four times a second, so the display
# costs a few dozen Write-Host calls in total.
#
# Returns $true only when the whole file arrived. On any failure it returns
# $false and reports nothing: the caller then runs the plain
# Invoke-WebRequest download, which retries and records the reason.
function Save-UrlWithProgress {
param(
[Parameter(Mandatory = $true)][string]$Url,
[Parameter(Mandatory = $true)][string]$OutFile
)
$response = $null
$source = $null
$target = $null
$lineOpen = $false
try {
$request = [System.Net.WebRequest]::Create($Url)
$request.UserAgent = 'autter-install-ps1'
$response = $request.GetResponse()
$total = [long]$response.ContentLength
$source = $response.GetResponseStream()
$target = [System.IO.File]::Create($OutFile)
$buffer = New-Object byte[] 81920
$done = [long]0
$clock = [System.Diagnostics.Stopwatch]::StartNew()
$nextDraw = [long]0
while ($true) {
$read = $source.Read($buffer, 0, $buffer.Length)
if ($read -le 0) { break }
$target.Write($buffer, 0, $read)
$done += $read
if ($clock.ElapsedMilliseconds -ge $nextDraw) {
$nextDraw = $clock.ElapsedMilliseconds + 250
Write-Host -NoNewline ("`r" + (Format-DownloadProgress -Done $done -Total $total))
$lineOpen = $true
}
}
Write-Host -NoNewline ("`r" + (Format-DownloadProgress -Done $done -Total $total))
Write-Host ''
$lineOpen = $false
if ($total -gt 0 -and $done -ne $total) {
return $false
}
return ($done -gt 0)
} catch {
return $false
} finally {
if ($lineOpen) { Write-Host '' }
if ($target) { $target.Dispose() }
if ($source) { $source.Dispose() }
if ($response) { $response.Close() }
}
}
$showDownloadProgress = Test-ShowDownloadProgress
function Try-Download {
param(
[Parameter(Mandatory = $true)][string]$Url
)
if ($showDownloadProgress) {
if (Save-UrlWithProgress -Url $Url -OutFile $tmpFile) {
return $true
}
# Fall through to the plain download below.
}
try {
# Keep Invoke-WebRequest's progress bar off: PowerShell's
# progress-stream rendering can make downloads 10-50x slower.
$oldProgressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
try {
Invoke-WebRequest -Uri $Url -OutFile $tmpFile -UseBasicParsing -ErrorAction Stop
} finally {
$ProgressPreference = $oldProgressPreference
}
return $true
} catch {
$reason = $_.Exception.Message
try {
# WebException (PowerShell 5.1) and HttpResponseException (7+) both
# carry the response; pure network/TLS failures have none, and on
# some exception types even probing .Response throws - hence the
# inner try/catch keeping the plain exception message.
if ($_.Exception.Response -and $_.Exception.Response.StatusCode) {
$reason = 'HTTP {0} {1}' -f [int]$_.Exception.Response.StatusCode, $_.Exception.Response.StatusCode
}
} catch { }
[void]$downloadFailures.Add((" {0}`n -> {1}" -f $Url, $reason))
return $false
}
}
# Track which download URL succeeded for checksum verification
$downloadedBinaryName = $null
if (-not [string]::IsNullOrWhiteSpace($env:AUTTER_LOCAL_BINARY)) {
if (-not (Test-Path -LiteralPath $env:AUTTER_LOCAL_BINARY)) {
Remove-Item -Force -ErrorAction SilentlyContinue $tmpFile
Write-ErrorAndExit "Local binary not found at $($env:AUTTER_LOCAL_BINARY)"
}
Copy-Item -Force -Path $env:AUTTER_LOCAL_BINARY -Destination $tmpFile
$downloadedBinaryName = "$binaryName.exe"
} elseif (Try-Download -Url $downloadUrlExe) {
$downloadedBinaryName = "$binaryName.exe"
} elseif (Try-Download -Url $downloadUrlNoExt) {
$downloadedBinaryName = $binaryName
}
if (-not $downloadedBinaryName) {
Remove-Item -Force -ErrorAction SilentlyContinue $tmpFile
$details = $downloadFailures -join "`n"
$message = "Failed to download $binaryName (release: $releaseTag). Attempted:`n$details"
if ($details -match 'HTTP 404') {
$message += "`nA 404 means release '$releaseTag' does not include a Windows binary named $binaryName."
$message += "`nWindows binaries ship with releases v1.6.8 and later - see https://github.com/$Repo/releases"
$message += "`nIf AUTTER_RELEASE_TAG pins an older version, unset it to install the latest release."
$message += "`nTo install the latest release with npm instead (needs Node.js 18+):"
$message += "`n npm install -g @autter/cli"
$message += "`n autter onboard"
} else {
$message += "`nCheck your network connection, proxy, and TLS settings, then retry."
$message += "`nReleases: https://github.com/$Repo/releases"
$message += "`n`n$NpmFallbackHint"
}
Write-ErrorAndExit $message
}
$downloadedSize = $null
try {
$downloadedSize = (Get-Item -LiteralPath $tmpFile).Length
} catch { }
if ($null -eq $downloadedSize) {
Remove-Item -Force -ErrorAction SilentlyContinue $tmpFile
Write-ErrorAndExit 'Download failed'
}
if ($downloadedSize -le 0) {
Remove-Item -Force -ErrorAction SilentlyContinue $tmpFile
Write-ErrorAndExit 'Downloaded file is empty'
}
# Verify before the executable is moved into place or run.
Verify-Checksum -File $tmpFile -BinaryName $downloadedBinaryName
$finalExe = Join-Path $installDir 'autter.exe'
# Stop the background service first; it is started again (on the new
# binary) by Start-DaemonIfRequested below.
$serviceWasRunning = Stop-ServiceForReplace -AutterExe $finalExe
$swap = Install-ExecutableFile -Source $tmpFile -Destination $finalExe
if ($swap.Error) {
Remove-Item -Force -ErrorAction SilentlyContinue $tmpFile
Write-ErrorAndExit ("Could not replace {0}: the file is in use ({1})`nThe autter background service, a git command run through autter, or another program (such as an antivirus scan) still has it open, and Windows does not replace a running program.`nThe previous autter is still installed and works.`nFix: run 'autter bg shutdown', then run the installer again." -f $finalExe, $swap.Error)
}
try { Unblock-File -Path $finalExe -ErrorAction SilentlyContinue } catch { }
# This installer now owns the binary: drop the npm package's marker, so the
# background service updates it again and `autter upgrade` stops pointing at npm.
Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $HOME '.autter\npm-install.json')
# Verify the binary runs before reporting success.
$installedVersion = ''
$versionExitCode = $null
$versionError = $null
try {
$installedVersion = (& $finalExe --version 2>&1 | Out-String).Trim()
$versionExitCode = $LASTEXITCODE
} catch {
$versionError = $_.Exception.Message
}
if ($versionError -or $versionExitCode -ne 0 -or [string]::IsNullOrWhiteSpace($installedVersion)) {
$versionDetail = if ($versionError) { " $versionError" } else { "`n$installedVersion" }
Remove-Item -Force -ErrorAction SilentlyContinue $finalExe
if (Restore-PreviousExecutable -Aside $swap.Aside -Destination $finalExe) {
$versionDetail += "`nThe previous autter is still installed."
}
Write-ErrorAndExit "The autter binary could not run on this system:$versionDetail"
}
Write-Host "Installed autter $installedVersion"