-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathinstall_python_venv.ps1
More file actions
1329 lines (1158 loc) · 52.9 KB
/
install_python_venv.ps1
File metadata and controls
1329 lines (1158 loc) · 52.9 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
#!/usr/bin/env pwsh
<#
install_python_venv.ps1
Robust, idempotent Python + venv bootstrapper for PyKotor.
Key improvements:
- Single consistent error trap; respects -noprompt.
- Structured logging with configurable levels (Trace|Debug|Info|Warn|Error|Silent).
- OS/distro detection without WMI on non-Windows.
- Idempotent venv creation/activation; clear reuse semantics.
- Non-interactive mode honored everywhere (no stray Read-Host).
- Secure downloads with retry logic and optional SHA256 verification.
- Centralized version map; defaults to Python 3.13.x, pip/setuptools recent pins.
- Proper dry-run support throughout all operations.
- Enhanced .env loading with value masking (unless -ShowEnvValues).
- Proper exit codes for success/failure scenarios.
#>
[CmdletBinding(PositionalBinding = $false)]
param(
[switch]$noprompt,
[string]$venv_name = ".venv",
[string]$force_python_version, # MAJOR.MINOR; overrides default target
[switch]$forceInstall, # proceed with installs without prompts
[switch]$skipVenv, # only detect/ensure python, skip venv creation
[switch]$skipEnvLoad, # skip loading .env
[switch]$dryRun, # print planned actions, make no changes
[switch]$acceptLicense, # auto-accept external installer licenses
[string]$logLevel = "Info", # Trace|Debug|Info|Warn|Error|Silent
[string]$venvPathOverride, # explicit venv path if not repo-root joined
[switch]$ShowEnvValues # when loading .env, print full values (otherwise masked)
)
#region Globals and configuration
$ErrorActionPreference = "Stop"
$PSNativeCommandUseErrorActionPreference = $true
$script:ExitCode = 1
$script:ErrorVerbosity = 3 # Compatibility with old error handler
# Detect whether this script is being dot-sourced.
# When dot-sourced, we MUST NOT call `exit`, because that terminates the caller's PowerShell session
# (e.g., a GitHub Actions step). In that case, we `return` on success and `throw` on failure,
# while still setting $env:pythonExePath and activating the venv in the caller session.
$script:IsDotSourced = $MyInvocation.InvocationName -eq '.'
# Normalize log level
$script:LogLevels = @{
"Trace" = 0
"Debug" = 1
"Info" = 2
"Warn" = 3
"Error" = 4
"Silent" = 5
}
if (-not $script:LogLevels.ContainsKey($logLevel)) { $logLevel = "Info" }
$script:CurrentLogLevel = $script:LogLevels[$logLevel]
# Centralized version pins (override with -force_python_version if desired)
$script:VersionPins = [pscustomobject]@{
PythonDefaultMajorMinor = "3.13"
PythonAltMajors = @("3.13", "3.12", "3.11", "3.10", "3.9", "3.8")
PythonSources = @{
"3.7" = "3.7.17"
"3.8" = "3.8.19"
"3.9" = "3.9.20"
"3.10" = "3.10.15"
"3.11" = "3.11.10"
"3.12" = "3.12.8"
"3.13" = "3.13.0"
}
PythonSourcesMac = @{
"3.7" = "3.7.9"
"3.8" = "3.8.10"
"3.9" = "3.9.13"
"3.10" = "3.10.11"
"3.11" = "3.11.8"
"3.12" = "3.12.2"
"3.13" = "3.13.0"
}
PythonSourcesWin = @{
"3.7" = "3.7.9"
"3.8" = "3.8.10"
"3.9" = "3.9.13"
"3.10" = "3.10.11"
"3.11" = "3.11.8"
"3.12" = "3.12.2"
"3.13" = "3.13.0"
}
PipVersion = "24.3.1"
SetuptoolsVersion = "75.2.0"
TclTkVersion = "8.6.14"
MinPythonVersion = [Version]"3.7.0"
MaxPythonVersion = [Version]"3.14.0"
RecommendedVersion = [Version]"3.8.10"
}
# Repo paths
$scriptPath = $MyInvocation.MyCommand.Definition
$repoRootPath = (Resolve-Path -LiteralPath (Join-Path -Path $scriptPath -ChildPath "..")).Path
$pathSep = [IO.Path]::DirectorySeparatorChar
$venvPath = if ($venvPathOverride) { $venvPathOverride } else { Join-Path -Path $repoRootPath -ChildPath $venv_name }
# Global python state
$global:force_python_version = $force_python_version
$global:pythonInstallPath = ""
$global:pythonVersion = ""
# Console colors toggle
$script:UseColor = $Host.UI -and $Host.UI.SupportsVirtualTerminal
#endregion Globals
#region Logging helpers
function Write-Log {
param(
[Parameter(Mandatory = $true)][ValidateSet("Trace", "Debug", "Info", "Warn", "Error")]
[string]$Level,
[Parameter(Mandatory = $true)][string]$Message
)
if ($script:LogLevels[$Level] -lt $script:CurrentLogLevel) { return }
$prefix = "[{0}] " -f $Level.ToUpper()
$color = switch ($Level) {
"Trace" { "DarkGray" }
"Debug" { "Gray" }
"Info" { "White" }
"Warn" { "Yellow" }
"Error" { "Red" }
}
if ($script:UseColor) { Write-Host "$prefix$Message" -ForegroundColor $color }
else { Write-Host "$prefix$Message" }
}
function Throw-Logged {
param([string]$Message)
Write-Log -Level "Error" -Message $Message
throw $Message
}
#endregion Logging
#region Error handling
trap {
$err = $_
if ($null -eq $err) { $err = $Error[0] }
Write-Log -Level "Error" -Message ("Unhandled error: {0}" -f $err.Exception.Message)
if ($script:ErrorVerbosity -ge 2 -and $err.ScriptStackTrace) {
Write-Log -Level "Debug" -Message $err.ScriptStackTrace
}
if ($script:ErrorVerbosity -ge 3 -and $err.InvocationInfo) {
$inv = $err.InvocationInfo
Write-Log -Level "Debug" -Message "At line $($inv.ScriptLineNumber): $($inv.Line.Trim())"
}
$global:LASTEXITCODE = 1
$script:ExitCode = 1
if (-not $noprompt) {
Write-Host "Press Enter to exit..."
Read-Host
}
if ($script:IsDotSourced) {
throw $err
}
exit 1
}
function Handle-Error {
param (
[Parameter(Mandatory = $true)][System.Management.Automation.ErrorRecord]$ErrorRecord,
[int]$Verbosity = $script:ErrorVerbosity
)
if ($Verbosity -eq 0 -or $Verbosity -eq 5) { return }
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss,fff"
$excType = $ErrorRecord.Exception.GetType().FullName
$excMessage = $ErrorRecord.Exception.Message
$helpLink = $ErrorRecord.Exception.HelpLink
if ($Verbosity -ge 1) {
Write-Host -ForegroundColor Red "$timestamp - $excType"
Write-Host -ForegroundColor Red $excMessage
if ($ErrorRecord.InvocationInfo) {
Write-Host -ForegroundColor Red "Line $($ErrorRecord.InvocationInfo.ScriptLineNumber): $($ErrorRecord.InvocationInfo.Line.Trim())"
}
}
if ($Verbosity -ge 2) {
Write-Host -ForegroundColor Red "Traceback (most recent call last):"
if ($null -ne (Get-Member -InputObject $ErrorRecord -Name ScriptStackTrace -ErrorAction SilentlyContinue)) {
Write-Host -ForegroundColor Red $ErrorRecord.ScriptStackTrace
}
else {
$callStack = Get-PSCallStack
for ($i = 0; $i -lt $callStack.Count; $i++) {
$frame = $callStack[$i]
Write-Host -ForegroundColor Red " File `"$($frame.ScriptName)`", line $($frame.ScriptLineNumber), in $($frame.FunctionName)"
}
}
}
if ($Verbosity -ge 3 -and $null -ne $ErrorRecord.InvocationInfo) {
$invInfo = $ErrorRecord.InvocationInfo
Write-Host -ForegroundColor Red " OffsetInLine = $($invInfo.OffsetInLine)"
Write-Host -ForegroundColor Red " ScriptName = `"$($invInfo.ScriptName)`""
Write-Host -ForegroundColor Red " InvocationName = `"$($invInfo.InvocationName)`""
}
}
function Format-VariableOutput {
param ($value, [int]$maxLength = 100, [int]$maxDepth = 3, [int]$currentDepth = 0)
if ($currentDepth -ge $maxDepth) { return "<max depth reached>" }
if ($null -eq $value) { return "None" }
elseif ($value -is [string]) { return "`"$($value.Substring(0, [Math]::Min($value.Length, $maxLength)))$(if ($value.Length -gt $maxLength) {"..."})`"" }
elseif ($value -is [int] -or $value -is [double]) { return $value.ToString() }
elseif ($value -is [bool]) { return $value.ToString().ToLower() }
elseif ($value -is [array] -or $value -is [System.Collections.IList]) {
$elements = $value | Select-Object -First 10 | ForEach-Object { Format-VariableOutput $_ -maxLength $maxLength -maxDepth $maxDepth -currentDepth ($currentDepth + 1) }
$var_output = "[" + ($elements -join ", ") + $(if ($value.Count -gt 10) { ", ..." }) + "]"
return $(if ($var_output.Length -gt $maxLength) { $var_output.Substring(0, $maxLength) + "..." } else { $var_output })
}
elseif ($value -is [hashtable] -or $value -is [System.Collections.IDictionary]) {
$elements = $value.GetEnumerator() | Select-Object -First 10 | ForEach-Object {
"$((Format-VariableOutput $_.Key -maxLength $maxLength -maxDepth $maxDepth -currentDepth ($currentDepth + 1))) = $((Format-VariableOutput $_.Value -maxLength $maxLength -maxDepth $maxDepth -currentDepth ($currentDepth + 1)))"
}
$var_output = "{" + ($elements -join ", ") + $(if ($value.Count -gt 10) { ", ..." }) + "}"
return $(if ($var_output.Length -gt $maxLength) { $var_output.Substring(0, $maxLength) + "..." } else { $var_output })
}
else {
$var_output = $value.ToString()
return $(if ($var_output.Length -gt $maxLength) { $var_output.Substring(0, $maxLength) + "..." } else { $var_output })
}
}
#endregion Error handling
#region Utility helpers
function Test-Command {
param([Parameter(Mandatory = $true)][string]$Name)
return [bool](Get-Command -Name $Name -ErrorAction SilentlyContinue)
}
function Require-Command {
param(
[Parameter(Mandatory = $true)][string]$Name,
[string]$InstallHint
)
if (-not (Test-Command $Name)) {
if ($InstallHint) {
Throw-Logged "$Name is required. $InstallHint"
}
else {
Throw-Logged "$Name is required but not found."
}
}
}
function Confirm-Action {
param(
[string]$Prompt,
[switch]$DefaultYes
)
if ($dryRun) {
Write-Log -Level "Info" -Message "[dry-run] Would prompt: $Prompt"
return $true
}
if ($noprompt -or $forceInstall) { return $true }
$suffix = if ($DefaultYes) { " [Y/n]" } else { " [y/N]" }
$resp = Read-Host "$Prompt$suffix"
if ($DefaultYes) { return ($resp -eq "" -or $resp -match '^(?i)y') }
return ($resp -match '^(?i)y')
}
function Mask-Value {
param([string]$Value)
if ($ShowEnvValues) { return $Value }
if ($Value.Length -le 4) { return "***" }
return ("{0}***" -f $Value.Substring(0, 4))
}
#endregion Utility helpers
#region OS detection
function Get-OS {
if ($IsWindows) { return "Windows" }
elseif ($IsMacOS) { return "Mac" }
elseif ($IsLinux) { return "Linux" }
# Fallback for older PowerShell
try {
$os = (Get-WmiObject -Class Win32_OperatingSystem -ErrorAction SilentlyContinue).Caption
if ($os -match "Windows") { return "Windows" }
elseif ($os -match "Mac") { return "Mac" }
elseif ($os -match "Linux") { return "Linux" }
}
catch {
Write-Log -Level "Warn" -Message "Could not determine OS via WMI"
}
Write-Error "Unknown Operating System"
if (-not $noprompt) {
Write-Host "Press any key to exit..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
if ($script:IsDotSourced) {
throw "Unknown Operating System"
}
exit 1
}
function Get-Linux-Distro-Name {
if (-not (Test-Path "/etc/os-release" -ErrorAction SilentlyContinue)) { return $null }
$osInfo = Get-Content "/etc/os-release" -Raw
if ($osInfo -match '\nID="?([^"\n]*)"?') {
$distroName = $Matches[1].Trim('"')
if ($distroName -eq "ol") { return "oracle" }
return $distroName
}
return $null
}
function Get-Linux-Distro-Version {
if (-not (Test-Path "/etc/os-release" -ErrorAction SilentlyContinue)) { return $null }
$osInfo = Get-Content "/etc/os-release" -Raw
if ($osInfo -match '\nVERSION_ID="?([^"\n]*)"?') {
return $Matches[1].Trim('"')
}
return $null
}
#endregion OS detection
#region Path/environment setup
$currentOS = Get-OS
Write-Log -Level "Debug" -Message "Detected OS: $currentOS"
Write-Log -Level "Debug" -Message "Script path: $scriptPath"
Write-Log -Level "Debug" -Message "Repo root: $repoRootPath"
# Setup LD_LIBRARY_PATH on Unix
if ($currentOS -ne "Windows") {
$ldLibraryPath = [System.Environment]::GetEnvironmentVariable('LD_LIBRARY_PATH', 'Process')
if ([string]::IsNullOrEmpty($ldLibraryPath)) {
Write-Log -Level "Warn" -Message "LD_LIBRARY_PATH not defined, creating it with /usr/lib:/usr/local/lib"
[System.Environment]::SetEnvironmentVariable('LD_LIBRARY_PATH', '/usr/lib:/usr/local/lib', 'Process')
}
elseif (-not $ldLibraryPath.Contains('/usr/local/lib')) {
Write-Log -Level "Warn" -Message "Adding /usr/local/lib to LD_LIBRARY_PATH"
$newLdLibraryPath = $ldLibraryPath + ':/usr/local/lib'
if (-not $newLdLibraryPath.Contains('/usr/lib')) {
$newLdLibraryPath += ':/usr/lib'
}
[System.Environment]::SetEnvironmentVariable('LD_LIBRARY_PATH', $newLdLibraryPath, 'Process')
}
}
# Check for admin rights on Windows
if ($currentOS -eq "Windows" -and -NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Log -Level "Warn" -Message "Please run PowerShell with administrator rights for best results"
}
#endregion Path/environment setup
#region Download + checksum
function Invoke-Download {
param(
[Parameter(Mandatory = $true)][string]$Uri,
[Parameter(Mandatory = $true)][string]$Destination,
[string]$Sha256,
[string]$Description = "file",
[int]$Retries = 3
)
if ($dryRun) {
Write-Log -Level "Info" -Message "[dry-run] Would download $Description from $Uri to $Destination"
return $true
}
for ($i = 1; $i -le $Retries; $i++) {
try {
Write-Log -Level "Info" -Message "Downloading $Description (attempt $i/$Retries)..."
Invoke-WebRequest -Uri $Uri -OutFile $Destination -UseBasicParsing
if ($Sha256) {
$hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $Destination).Hash.ToLowerInvariant()
if ($hash -ne $Sha256.ToLowerInvariant()) {
Throw-Logged "SHA256 mismatch for $Description. Expected $Sha256, got $hash"
}
Write-Log -Level "Debug" -Message "SHA256 verified for $Description"
}
return $true
}
catch {
if ($i -eq $Retries) {
Handle-Error -ErrorRecord $_
throw
}
Write-Log -Level "Warn" -Message "Download attempt $i failed, retrying..."
Start-Sleep -Seconds 2
}
}
return $false
}
#endregion Download + checksum
#region Bash command helpers
function Invoke-BashCommand {
param ([string]$Command)
if ($dryRun) {
Write-Log -Level "Info" -Message "[dry-run] Would run bash: $Command"
return ""
}
try {
$output = & bash -c $Command 2>&1
if (-not $? -or $LASTEXITCODE -ne 0) {
throw "Bash command '$Command' failed with exit code $LASTEXITCODE. Output: $output"
}
return $output
}
catch {
throw "Failed to execute Bash command '$Command'. Error: $_"
}
}
function Invoke-BashCommandOptional {
param (
[string]$Command,
[string]$FallbackMessage = "Command failed but continuing"
)
if ($dryRun) {
Write-Log -Level "Info" -Message "[dry-run] Would run bash (optional): $Command"
return $true
}
try {
& bash -c $Command 2>&1
if (-not $? -or $LASTEXITCODE -ne 0) {
Write-Log -Level "Warn" -Message "$FallbackMessage. Exit code: $LASTEXITCODE"
return $false
}
return $true
}
catch {
Write-Log -Level "Warn" -Message "$FallbackMessage. Error: $_"
return $false
}
}
#endregion Bash command helpers
#region Python version parsing
function Get-Python-Version {
Param ([string]$pythonPath)
$parseVersionString = {
param([string]$versionString)
if ([string]::IsNullOrWhiteSpace($versionString)) { return $null }
$trimmed = $versionString.Trim()
$match = [System.Text.RegularExpressions.Regex]::Match($trimmed, '(\d+)(\.\d+){1,3}')
if (-not $match.Success) { return $null }
$numericVersion = $match.Value
$segments = $numericVersion.Split('.')
while ($segments.Count -lt 3) { $segments += '0' }
return [Version]::Parse(($segments -join '.'))
}
try {
if (-not (Test-Path $pythonPath -ErrorAction SilentlyContinue)) {
return [Version]"0.0.0"
}
$pythonVersionOutput = & $pythonPath --version 2>&1 | Out-String
$pythonVersion = & $parseVersionString $pythonVersionOutput
if ($null -eq $pythonVersion) {
$platformVersionOutput = & $pythonPath -c "import platform; print(platform.python_version())" 2>&1 | Out-String
$pythonVersion = & $parseVersionString $platformVersionOutput
}
if ($null -eq $pythonVersion) {
$sysVersionOutput = & $pythonPath -c "import sys; print('.'.join(str(x) for x in sys.version_info[:3]))" 2>&1 | Out-String
$pythonVersion = & $parseVersionString $sysVersionOutput
}
if ($null -ne $pythonVersion) { return $pythonVersion }
}
catch {
Write-Log -Level "Debug" -Message "Failed to parse python version for path '$pythonPath': $($_.Exception.Message)"
}
return [Version]"0.0.0"
}
#endregion Python version parsing
#region Python discovery
function Get-PythonPaths {
Param ([string]$version)
$windowsVersion = $version -replace '\.', ''
$windowsPaths = @(
"C:\Program Files\Python$windowsVersion\python.exe",
"$env:ProgramFiles\Python$windowsVersion\python.exe",
"C:\Program Files (x86)\Python$windowsVersion\python.exe",
"$env:ProgramFiles(x86)\Python$windowsVersion\python.exe"
"C:\Program Files\Python$windowsVersion-32\python.exe",
"C:\Program Files (x86)\Python$windowsVersion-32\python.exe",
"$env:USERPROFILE\AppData\Local\Programs\Python\Python$windowsVersion\python.exe",
"$env:USERPROFILE\AppData\Local\Programs\Python\Python$windowsVersion-32\python.exe",
"$env:LOCALAPPDATA\Programs\Python\Python$windowsVersion-64\python.exe",
"$env:LOCALAPPDATA\Programs\Python\Python$windowsVersion\python.exe",
"$env:LOCALAPPDATA\Programs\Python\Python$windowsVersion-32\python.exe"
)
$linuxAndMacPaths = @(
"/usr/local/bin/python$version",
"/usr/bin/python$version",
"/bin/python$version",
"/sbin/python$version",
"~/.local/bin/python$version",
"~/.pyenv/versions/$version/bin/python3",
"~/.pyenv/versions/$version/bin/python",
"/usr/local/Cellar/python/$version/bin/python3",
"/opt/local/bin/python$version",
"/opt/python$version"
)
return @{ Windows = $windowsPaths; Linux = $linuxAndMacPaths; Mac = $linuxAndMacPaths }
}
function Test-PythonCommand {
param ([string]$CommandName)
$pythonCommand = Get-Command -Name $CommandName -ErrorAction SilentlyContinue
if ($null -eq $pythonCommand) { return $false }
$testPath = $pythonCommand.Source
$testVersion = Get-Python-Version $testPath
if ($testVersion -ge $VersionPins.MinPythonVersion -and $testVersion -lt $VersionPins.MaxPythonVersion) {
Write-Log -Level "Info" -Message "Found python command '$CommandName' with version $testVersion at path $testPath"
$global:pythonInstallPath = $testPath
$global:pythonVersion = $testVersion
return $true
}
else {
Write-Log -Level "Debug" -Message "Python '$testPath' version '$testVersion' not in supported range"
}
return $false
}
function Find-Python {
Param ([bool]$installIfNotFound)
# Check existing global path
if ($global:pythonInstallPath) {
$testVersion = Get-Python-Version -pythonPath $global:pythonInstallPath
if ($testVersion -ne [Version]"0.0.0" -and
$testVersion -ge $VersionPins.MinPythonVersion -and
$testVersion -lt $VersionPins.MaxPythonVersion) {
Write-Log -Level "Info" -Message "Using existing Python $testVersion at $global:pythonInstallPath"
$global:pythonVersion = $testVersion
return
}
}
# Determine versions to search for
if ($global:force_python_version) {
$fallbackVersion = $global:force_python_version
$pythonVersions = @("python$fallbackVersion")
}
else {
$fallbackVersion = "{0}.{1}" -f $VersionPins.RecommendedVersion.Major, $VersionPins.RecommendedVersion.Minor
$pythonVersions = @('python3.13', 'python3.12', 'python3.11', 'python3.10', 'python3.9', 'python3.8', 'python3', 'python')
}
# Search via commands
foreach ($pyCmd in $pythonVersions) {
if (Test-PythonCommand -CommandName $pyCmd) {
break
}
}
# Search via paths if not found
if (-not $global:pythonInstallPath) {
foreach ($version in $pythonVersions) {
$versionNum = $version -replace "python", ""
if (-not $versionNum) { continue }
$paths = (Get-PythonPaths $versionNum)[$currentOS]
foreach ($path in $paths) {
try {
$resolvedPath = [Environment]::ExpandEnvironmentVariables($path)
if (Test-Path $resolvedPath -ErrorAction SilentlyContinue) {
$thisVersion = Get-Python-Version $resolvedPath
if ($thisVersion -ge $VersionPins.MinPythonVersion -and $thisVersion -le $VersionPins.MaxPythonVersion) {
if (-not $global:pythonInstallPath -or $thisVersion -le $VersionPins.RecommendedVersion) {
Write-Log -Level "Info" -Message "Found Python $thisVersion at '$resolvedPath'"
$global:pythonInstallPath = $resolvedPath
$global:pythonVersion = $thisVersion
}
# Special handling for Debian/Ubuntu altinstall
if ($resolvedPath.StartsWith("/usr/local/bin/python")) {
$distro = Get-Linux-Distro-Name
if ($distro -eq "debian" -or $distro -eq "ubuntu") {
Write-Log -Level "Debug" -Message "Altinstall detected, using $resolvedPath"
return
}
}
}
}
}
catch {
Write-Log -Level "Debug" -Message "Error checking path ${path}: $_"
}
}
}
}
# Debian/Ubuntu: ensure venv packages even if Python exists
if ($installIfNotFound) {
$distro = Get-Linux-Distro-Name
if ($distro -eq "debian" -or $distro -eq "ubuntu") {
if ($global:pythonVersion) {
$shortVersion = "{0}.{1}" -f $global:pythonVersion.Major, $global:pythonVersion.Minor
}
else {
$shortVersion = $fallbackVersion
}
Write-Log -Level "Debug" -Message "Ensuring venv packages for Python $shortVersion on $distro"
Install-Python-Linux -pythonVersion $shortVersion
}
}
# Install if not found
if (-not $global:pythonInstallPath) {
if (-not $installIfNotFound) { return }
$displayVersion = if ($global:force_python_version) { $global:force_python_version } else { $VersionPins.RecommendedVersion }
if (-not (Confirm-Action -Prompt "Python $displayVersion not found. Install it?" -DefaultYes)) {
Throw-Logged "User declined installation; cannot proceed."
}
try {
switch ($currentOS) {
"Windows" { Install-PythonWindows -pythonVersion $fallbackVersion }
"Linux" { Install-Python-Linux -pythonVersion $fallbackVersion }
"Mac" { Install-Python-Mac -pythonVersion $fallbackVersion }
}
}
catch {
Handle-Error -ErrorRecord $_
Throw-Logged "Python installation failed"
}
Write-Log -Level "Info" -Message "Searching for Python again after installation..."
Find-Python -installIfNotFound $false
}
}
#endregion Python discovery
#region Tcl/Tk installation
function Install-TclTk {
function Test-TclTkVersion($command, $scriptCommand, $requiredVersion) {
$commandInfo = Get-Command -Name $command -ErrorAction SilentlyContinue
if (-not $commandInfo) {
if ($command -eq 'wish') {
$versionSpecificCommand = Get-Command 'wish*' -ErrorAction SilentlyContinue | Select-Object -First 1
if ($null -ne $versionSpecificCommand) {
Write-Log -Level "Info" -Message "Symlinking $($versionSpecificCommand.Source) to /usr/local/bin/wish"
Invoke-BashCommand "sudo ln -sv $($versionSpecificCommand.Source) /usr/local/bin/wish"
return $true
}
}
return $false
}
try {
$versionScript = "echo `$scriptCommand` | $command"
$versionString = Invoke-Expression $versionScript 2>&1
if ([string]::IsNullOrWhiteSpace($versionString)) { return $false }
$versionString = $versionString -replace '[^\d.]+', ''
if ([string]::IsNullOrEmpty($versionString)) { return $false }
$version = New-Object System.Version $versionString.Trim()
return $version -ge $requiredVersion
}
catch {
return $false
}
}
$tclVersionScript = "puts [info patchlevel];exit"
$tkVersionScript = "puts [info patchlevel];exit"
$recommendedVersion = $VersionPins.TclTkVersion
$requiredVersion = New-Object System.Version "8.6.0"
$tclCheck = Test-TclTkVersion "tclsh" $tclVersionScript $requiredVersion
$tkCheck = Test-TclTkVersion "wish" $tkVersionScript $requiredVersion
if ($tclCheck -and $tkCheck) {
Write-Log -Level "Info" -Message "Tcl/Tk $requiredVersion or higher already installed"
return
}
Write-Log -Level "Info" -Message "Tcl/Tk needs to be installed or updated"
if ($currentOS -eq "Mac") {
try {
$macOSVersion = Invoke-BashCommand -Command "sw_vers -productVersion"
$majorMacOSVersion = [int]$macOSVersion.Split('.')[0]
if ($majorMacOSVersion -ge 11 -or ($majorMacOSVersion -eq 10 -and [int]$macOSVersion.Split('.')[1] -ge 12)) {
Invoke-BashCommandOptional -Command 'brew install tcl-tk --overwrite --force || true' -FallbackMessage "Brew install tcl-tk failed"
return
}
}
catch {
Write-Log -Level "Warn" -Message "Could not install Tcl/Tk via brew: $_"
}
}
# Install from source
if ($dryRun) {
Write-Log -Level "Info" -Message "[dry-run] Would install Tcl/Tk $recommendedVersion from source"
return
}
$originalDir = Get-Location
try {
Write-Log -Level "Info" -Message "Installing Tcl from source..."
Invoke-BashCommand "curl -O -L https://prdownloads.sourceforge.net/tcl/tcl$recommendedVersion-src.tar.gz"
Invoke-BashCommand "tar -xzvf tcl$recommendedVersion-src.tar.gz"
Set-Location "tcl$recommendedVersion/unix"
Invoke-BashCommand "./configure --prefix=/usr/local"
Invoke-BashCommand "make"
Invoke-BashCommand "sudo make install"
Set-Location $originalDir
Write-Log -Level "Info" -Message "Installing Tk from source..."
Invoke-BashCommand "curl -O -L https://prdownloads.sourceforge.net/tcl/tk$recommendedVersion-src.tar.gz"
Invoke-BashCommand "tar -xzvf tk$recommendedVersion-src.tar.gz"
Set-Location "tk$recommendedVersion/unix"
Invoke-BashCommand "./configure --prefix=/usr/local --with-tcl=/usr/local/lib"
Invoke-BashCommand "make"
Invoke-BashCommand "sudo make install"
}
finally {
Set-Location $originalDir
}
}
#endregion Tcl/Tk installation
#region Python installation - Windows
function Install-PythonWindows {
Param ([string]$pythonVersion)
$pyVersion = $VersionPins.PythonSourcesWin[$pythonVersion]
if (-not $pyVersion) {
Throw-Logged "Unsupported Python version '$pythonVersion' for Windows"
}
$installerName = if ([System.Environment]::Is64BitOperatingSystem) {
"python-$pyVersion-amd64.exe"
}
else {
"python-$pyVersion.exe"
}
if ($env:GITHUB_ACTIONS -eq "true" -and $env:MATRIX_ARCH) {
$installerName = switch ($env:MATRIX_ARCH) {
"x86" { "python-$pyVersion.exe" }
"x64" { "python-$pyVersion-amd64.exe" }
default { $installerName }
}
}
$pythonInstallerUrl = "https://www.python.org/ftp/python/$pyVersion/$installerName"
$installerPath = "$env:TEMP\$installerName"
Invoke-Download -Uri $pythonInstallerUrl -Destination $installerPath -Description "Python $pyVersion installer"
if ($dryRun) { return $true }
$logPath = Join-Path (Get-Location).Path "PythonInstall.log"
Write-Log -Level "Info" -Message "Installing Python $pyVersion..."
Start-Process -FilePath $installerPath -Args "/quiet /log $logPath InstallAllUsers=0 PrependPath=1 InstallLauncherAllUsers=0" -Wait -NoNewWindow
Write-Log -Level "Debug" -Message "Python installation log:"
if (Test-Path $logPath) {
Get-Content -Path $logPath | ForEach-Object { Write-Log -Level "Debug" -Message $_ }
}
# Refresh PATH
$systemPath = Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH | Select-Object -ExpandProperty PATH
$userPath = Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Environment' -Name PATH | Select-Object -ExpandProperty PATH
$env:Path = $userPath + ";" + $systemPath
Remove-Item -LiteralPath $installerPath -ErrorAction SilentlyContinue
return $true
}
#endregion Python installation - Windows
#region Python installation - macOS
function Install-Python-Mac {
Param ([string]$pythonVersion)
$pyVersion = $VersionPins.PythonSourcesMac[$pythonVersion]
if (-not $pyVersion) {
Throw-Logged "Unsupported Python version '$pythonVersion' for macOS"
}
$pythonInstallers = @{
"3.7" = @("python-$pyVersion-macosx10.9.pkg")
"3.8" = @("python-$pyVersion-macos11.pkg", "python-$pyVersion-macosx10.9.pkg")
"3.9" = @("python-$pyVersion-macos11.pkg", "python-$pyVersion-macosx10.9.pkg")
"3.10" = @("python-$pyVersion-macos11.pkg")
"3.11" = @("python-$pyVersion-macos11.pkg")
"3.12" = @("python-$pyVersion-macos11.pkg")
"3.13" = @("python-$pyVersion-macos11.pkg")
}
Install-TclTk
try {
$macOSVersion = bash -c "sw_vers -productVersion"
$majorMacOSVersion = [int]$macOSVersion.Split('.')[0]
$installerSelection = $pythonInstallers[$pythonVersion] | Where-Object {
$_ -match "macos($majorMacOSVersion)"
} | Select-Object -First 1
if (-not $installerSelection) {
$installerSelection = $pythonInstallers[$pythonVersion] | Select-Object -First 1
Write-Log -Level "Warn" -Message "No exact macOS version match, using $installerSelection"
}
$pythonInstallerUrl = "https://www.python.org/ftp/python/$pyVersion/$installerSelection"
$installerPath = "/tmp/$installerSelection"
Invoke-Download -Uri $pythonInstallerUrl -Destination $installerPath -Description "Python $pyVersion pkg"
if (-not $dryRun) {
Invoke-BashCommand "sudo installer -pkg $installerPath -target /"
Remove-Item -LiteralPath $installerPath -ErrorAction SilentlyContinue
}
return $true
}
catch {
Handle-Error -ErrorRecord $_
Write-Log -Level "Warn" -Message "PKG install failed, trying source build..."
try {
Install-PythonUnixSource -pythonVersion $pythonVersion
return $true
}
catch {
Handle-Error -ErrorRecord $_
Write-Log -Level "Warn" -Message "Source build failed, trying brew..."
bash -c "brew install python@$pyVersion python-tk@$pyVersion"
return $true
}
}
}
#endregion Python installation - macOS
#region Python installation - Linux
function Install-Python-Linux {
Param ([string]$pythonVersion)
if (-not $pythonVersion) { $pythonVersion = "3" }
if (-not (Test-Path "/etc/os-release")) {
Throw-Logged "Cannot determine Linux distribution"
}
$distro = Get-Linux-Distro-Name
$versionId = Get-Linux-Distro-Version
Write-Log -Level "Info" -Message "Installing Python $pythonVersion on $distro $versionId"
try {
switch ($distro) {
"debian" {
Invoke-BashCommand -Command "sudo apt-get update -y"
$pipSuccess = Invoke-BashCommandOptional -Command "sudo apt-get install -y tk tcl libpython$pythonVersion-dev python$pythonVersion python$pythonVersion-dev python$pythonVersion-venv python$pythonVersion-pip" -FallbackMessage "pip package not available"
if (-not $pipSuccess) {
Invoke-BashCommand -Command "sudo apt-get install -y tk tcl libpython$pythonVersion-dev python$pythonVersion python$pythonVersion-dev python$pythonVersion-venv"
}
}
"ubuntu" {
Invoke-BashCommand -Command "sudo apt-get update -y"
$pipSuccess = Invoke-BashCommandOptional -Command "sudo apt-get install -y tk tcl libpython$pythonVersion-dev python$pythonVersion python$pythonVersion-dev python$pythonVersion-venv python$pythonVersion-pip" -FallbackMessage "pip package not available"
if (-not $pipSuccess) {
Invoke-BashCommand -Command "sudo apt-get install -y tk tcl libpython$pythonVersion-dev python$pythonVersion python$pythonVersion-dev python$pythonVersion-venv"
}
}
"alpine" {
if ($pythonVersion -eq "3") {
Invoke-BashCommand -Command "sudo apk update"
Invoke-BashCommand -Command "sudo apk add --update --no-cache tk-dev tcl-dev tcl tk python$pythonVersion python$pythonVersion-tkinter"
Invoke-BashCommand -Command "if [ ! -f /usr/local/bin/python3 ]; then sudo ln -sf /usr/bin/python$pythonVersion /usr/local/bin/python3; fi"
Invoke-BashCommand -Command "sudo ln -sf /usr/bin/python$pythonVersion /usr/local/bin/python$pythonVersion"
Invoke-BashCommand -Command "/usr/local/bin/python$pythonVersion -m ensurepip"
Invoke-BashCommand -Command "/usr/local/bin/python$pythonVersion -m pip install --no-cache --upgrade pip setuptools"
}
else {
throw "Python version $pythonVersion not supported on Alpine via package manager"
}
}
"fedora" {
Invoke-BashCommand -Command "sudo dnf update -y"
Invoke-BashCommand -Command "sudo dnf install python$pythonVersion python$pythonVersion-devel tk tcl tk-devel tcl-devel dnf-plugins-core -y"
}
"almalinux" {
Invoke-BashCommand -Command "sudo dnf update -y"
Invoke-BashCommand -Command "sudo dnf install python$pythonVersion python$pythonVersion-devel tk tcl tk-devel tcl-devel -y"
}
"centos" {
Invoke-BashCommand -Command "sudo yum update -y"
if ($versionId -eq "7") {
Invoke-BashCommand -Command "sudo yum install epel-release -y"
}
Invoke-BashCommand -Command "sudo yum install python$pythonVersion python$pythonVersion-devel tk tcl tk-devel tcl-devel -y"
}
"arch" {
if ($pythonVersion -eq "3") {
Invoke-BashCommand -Command "sudo pacman-key --init"
Invoke-BashCommand -Command "sudo pacman-key --populate archlinux"
Invoke-BashCommand -Command "sudo pacman -Sy archlinux-keyring --noconfirm"
Invoke-BashCommand -Command "sudo pacman -Sy --noconfirm"
Invoke-BashCommand -Command "sudo pacman -Sy base-devel python-pip python tk tcl --noconfirm"
}
else {
throw "Package manager does not support version '$pythonVersion' on Arch"
}
}
default {
throw "Unsupported Linux distribution for package manager install: $distro"
}
}
Find-Python -installIfNotFound $false
if (-not $global:pythonInstallPath) {
throw "Python not found after package install"
}
# Ensure pip
try {
& $global:pythonInstallPath -m pip --version 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Log -Level "Info" -Message "Bootstrapping pip with ensurepip..."
& $global:pythonInstallPath -m ensurepip --upgrade --default-pip
}
}
catch {
Write-Log -Level "Warn" -Message "Failed to check/bootstrap pip: $_"
}
}
catch {
Handle-Error -ErrorRecord $_
if ($noprompt) {
Write-Log -Level "Error" -Message "Non-interactive mode: cannot build from source"
throw "Python installation failed in non-interactive mode"
}
if (-not (Confirm-Action -Prompt "Package install failed. Build from source?" -DefaultYes:$false)) {
Throw-Logged "User declined source build"
}
# Install build dependencies
Install-TclTk
switch ($distro) {
{ $_ -in @("debian", "ubuntu") } {
Invoke-BashCommand -Command 'sudo apt-get update -y'
Invoke-BashCommand -Command 'sudo apt-get install -y tk tcl build-essential zlib1g-dev libncurses5-dev libgdbm-dev libssl-dev libreadline-dev libffi-dev libsqlite3-dev libbz2-dev tk-dev tcl-dev'
}
"alpine" {
Invoke-BashCommand -Command 'sudo apk add --update --no-cache tk tcl tk-dev tcl-dev alpine-sdk linux-headers zlib-dev bzip2-dev readline-dev sqlite-dev openssl-dev libffi-dev'
}
{ $_ -in @("fedora", "almalinux", "centos") } {
$pkgMgr = if ($distro -eq "centos") { "yum" } else { "dnf" }
Invoke-BashCommand -Command "sudo $pkgMgr groupinstall `"Development Tools`" -y"
Invoke-BashCommand -Command "sudo $pkgMgr install -y tk tcl tk-devel tcl-devel zlib-devel bzip2-devel readline-devel sqlite-devel openssl-devel libffi-devel"
}
default {
Write-Log -Level "Warn" -Message "No specific build dependency install for $distro, attempting generic..."
}
}
Install-PythonUnixSource -pythonVersion $pythonVersion
}
}
function Install-PythonUnixSource {
Param ([string]$pythonVersion)
$pyVersion = $VersionPins.PythonSources[$pythonVersion]
if (-not $pyVersion) {
Throw-Logged "Unsupported Python version '$pythonVersion' for source build"
}
$pythonSrcUrl = "https://www.python.org/ftp/python/$pyVersion/Python-$pyVersion.tgz"
$tarPath = "Python-$pyVersion.tgz"
Invoke-Download -Uri $pythonSrcUrl -Destination $tarPath -Description "Python $pyVersion source"