-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap.ps1
More file actions
510 lines (426 loc) · 15 KB
/
bootstrap.ps1
File metadata and controls
510 lines (426 loc) · 15 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
param(
[string]$PreferredPythonVersion = "3.11",
[switch]$RunTests,
[switch]$RunApp,
[switch]$RebuildVenv
)
$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest
function New-PythonCandidate {
param(
[string]$Label,
[string]$FilePath,
[string[]]$Arguments
)
[pscustomobject]@{
Label = $Label
FilePath = $FilePath
Arguments = @($Arguments)
}
}
function Get-ProbeFailureCategory {
param(
[string]$Text
)
if ([string]::IsNullOrWhiteSpace($Text)) {
return "unknown failure"
}
if ($Text -match "No installed Python found") {
return "No installed Python found"
}
if ($Text -match "Fatal error in launcher") {
return "Fatal error in launcher"
}
if ($Text -match "Access is denied") {
return "Access is denied"
}
if ($Text -match "cannot be loaded because running scripts is disabled on this system|running scripts is disabled on this system") {
return "PowerShell execution policy blocked the script"
}
if ($Text -match "cannot find the path specified|The system cannot find the path specified") {
return "The system cannot find the path specified"
}
if ($Text -match "is not recognized as the name of a cmdlet|not recognized as the name of a cmdlet|not recognized") {
return "CommandNotFound"
}
return "non-zero exit or launch failure"
}
function Invoke-ExecutableProbe {
param(
[string]$FilePath,
[string[]]$Arguments
)
$stdoutPath = [System.IO.Path]::GetTempFileName()
$stderrPath = [System.IO.Path]::GetTempFileName()
try {
& $FilePath @Arguments 1> $stdoutPath 2> $stderrPath
$exitCode = $LASTEXITCODE
$stdout = if (Test-Path $stdoutPath) { Get-Content -Raw $stdoutPath } else { "" }
$stderr = if (Test-Path $stderrPath) { Get-Content -Raw $stderrPath } else { "" }
[pscustomobject]@{
Started = $true
ExitCode = $exitCode
StdOut = $stdout
StdErr = $stderr
ErrorMessage = $null
}
} catch {
[pscustomobject]@{
Started = $false
ExitCode = $null
StdOut = ""
StdErr = ""
ErrorMessage = $_.Exception.Message
}
} finally {
if (Test-Path $stdoutPath) {
Remove-Item -Force $stdoutPath -ErrorAction SilentlyContinue
}
if (Test-Path $stderrPath) {
Remove-Item -Force $stderrPath -ErrorAction SilentlyContinue
}
}
}
function Test-PythonExecutable {
param(
[string]$Label,
[string]$FilePath,
[string[]]$PrefixArguments
)
$probeScript = "import sys; print(sys.executable); print(sys.version)"
$arguments = @()
if ($PrefixArguments) {
$arguments += $PrefixArguments
}
$arguments += @("-c", $probeScript)
$probe = Invoke-ExecutableProbe -FilePath $FilePath -Arguments $arguments
$combinedOutput = @($probe.ErrorMessage, $probe.StdErr, $probe.StdOut) -join "`n"
if (-not $probe.Started) {
return [pscustomobject]@{
Label = $Label
FilePath = $FilePath
Arguments = $PrefixArguments
IsAvailable = $false
ExitCode = $null
ExecutablePath = $null
StdOut = $probe.StdOut
StdErr = $probe.StdErr
ErrorMessage = $probe.ErrorMessage
FailureCategory = Get-ProbeFailureCategory -Text $combinedOutput
}
}
if ($probe.ExitCode -ne 0) {
return [pscustomobject]@{
Label = $Label
FilePath = $FilePath
Arguments = $PrefixArguments
IsAvailable = $false
ExitCode = $probe.ExitCode
ExecutablePath = $null
StdOut = $probe.StdOut
StdErr = $probe.StdErr
ErrorMessage = $probe.ErrorMessage
FailureCategory = Get-ProbeFailureCategory -Text $combinedOutput
}
}
$stdoutLines = @($probe.StdOut -split "\r?\n" | ForEach-Object { $_.Trim() } | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
if ($stdoutLines.Count -lt 1) {
return [pscustomobject]@{
Label = $Label
FilePath = $FilePath
Arguments = $PrefixArguments
IsAvailable = $false
ExitCode = 0
ExecutablePath = $null
StdOut = $probe.StdOut
StdErr = $probe.StdErr
ErrorMessage = "Probe succeeded but did not report sys.executable."
FailureCategory = "non-zero exit or launch failure"
}
}
$executablePath = $stdoutLines[0]
if (-not (Test-Path $executablePath)) {
return [pscustomobject]@{
Label = $Label
FilePath = $FilePath
Arguments = $PrefixArguments
IsAvailable = $false
ExitCode = 0
ExecutablePath = $executablePath
StdOut = $probe.StdOut
StdErr = $probe.StdErr
ErrorMessage = "Probe succeeded but reported executable path '$executablePath' does not exist."
FailureCategory = "reported executable path missing"
}
}
[pscustomobject]@{
Label = $Label
FilePath = $FilePath
Arguments = $PrefixArguments
IsAvailable = $true
ExitCode = 0
ExecutablePath = $executablePath
StdOut = $probe.StdOut
StdErr = $probe.StdErr
ErrorMessage = $null
FailureCategory = $null
}
}
function Get-PythonCandidates {
param(
[string]$PreferredVersion
)
$candidates = New-Object System.Collections.Generic.List[object]
$candidates.Add((New-PythonCandidate -Label "py -$PreferredVersion" -FilePath "py" -Arguments @("-$PreferredVersion")))
$candidates.Add((New-PythonCandidate -Label "py" -FilePath "py" -Arguments @()))
$candidates.Add((New-PythonCandidate -Label "python" -FilePath "python" -Arguments @()))
$candidates.Add((New-PythonCandidate -Label "python3" -FilePath "python3" -Arguments @()))
foreach ($explicitPath in @(
(Join-Path $env:LocalAppData "Programs\Python\Python311\python.exe"),
(Join-Path $env:LocalAppData "Programs\Python\Python313\python.exe")
)) {
if (-not [string]::IsNullOrWhiteSpace($explicitPath)) {
$candidates.Add((New-PythonCandidate -Label "explicit path: $explicitPath" -FilePath $explicitPath -Arguments @()))
}
}
return $candidates
}
function Resolve-Python {
param(
[string]$Version
)
$attempts = New-Object System.Collections.Generic.List[object]
foreach ($candidate in (Get-PythonCandidates -PreferredVersion $Version)) {
Write-Host "[bootstrap] probing $($candidate.Label)..."
$result = Test-PythonExecutable -Label $candidate.Label -FilePath $candidate.FilePath -PrefixArguments $candidate.Arguments
$attempts.Add($result)
if ($result.IsAvailable) {
Write-Host "[bootstrap] using $($result.Label): $($result.ExecutablePath)"
return $result.ExecutablePath
}
$reason = if ($result.ErrorMessage) { $result.ErrorMessage } else { $result.FailureCategory }
Write-Host "[bootstrap] $($candidate.Label) unusable: $reason"
}
$summaryLines = $attempts | ForEach-Object {
$reason = if ($_.ErrorMessage) { $_.ErrorMessage } else { $_.FailureCategory }
"- $($_.Label) : $reason"
}
throw @"
No usable Python interpreter was found.
What this means:
- PATH may not expose a working Python command in this shell.
- A Python executable may exist on disk but this sandbox or shell cannot actually run it.
- If you already have a venv, it may be bound to an old interpreter and is no longer healthy.
Checked candidates:
$($summaryLines -join "`n")
Suggested local recovery steps:
1. Open a normal PowerShell terminal on your machine.
2. Run `py --version` and `py -3.13 -c "import sys; print(sys.executable)"`.
3. If that succeeds, remove the stale `backend\.venv`.
4. Re-run this bootstrap script from the repository root.
If `py --version` works but `py -3.13 -c "import sys; print(sys.executable)"` fails with Access denied, the current shell or sandbox can see Python but cannot execute that user-installation path.
"@
}
function Read-VenvConfig {
param(
[string]$VenvRoot
)
$configPath = Join-Path $VenvRoot "pyvenv.cfg"
if (-not (Test-Path $configPath)) {
return $null
}
$config = @{}
foreach ($line in Get-Content $configPath) {
if ($line -match "^\s*([^=]+?)\s*=\s*(.+)\s*$") {
$config[$Matches[1].Trim()] = $Matches[2].Trim()
}
}
[pscustomobject]@{
ConfigPath = $configPath
Values = $config
}
}
function Test-VenvHealthy {
param(
[string]$VenvRoot
)
$config = Read-VenvConfig -VenvRoot $VenvRoot
$venvPython = Join-Path $VenvRoot "Scripts\python.exe"
if ($null -eq $config) {
return [pscustomobject]@{
IsHealthy = $false
Reason = "pyvenv.cfg is missing."
Config = $null
PythonPath = $venvPython
Probe = $null
}
}
if (-not (Test-Path $venvPython)) {
return [pscustomobject]@{
IsHealthy = $false
Reason = "Scripts\python.exe is missing."
Config = $config
PythonPath = $venvPython
Probe = $null
}
}
$probe = Test-PythonExecutable -Label "venv python" -FilePath $venvPython -PrefixArguments @()
if (-not $probe.IsAvailable) {
$details = if ($probe.ErrorMessage) { $probe.ErrorMessage } else { $probe.FailureCategory }
return [pscustomobject]@{
IsHealthy = $false
Reason = "backend\.venv python could not be executed: $details"
Config = $config
PythonPath = $venvPython
Probe = $probe
}
}
[pscustomobject]@{
IsHealthy = $true
Reason = $null
Config = $config
PythonPath = $venvPython
Probe = $probe
}
}
function Get-VenvProcesses {
param(
[string]$VenvRoot
)
$resolvedVenvRoot = [System.IO.Path]::GetFullPath($VenvRoot).TrimEnd('\')
Get-Process -ErrorAction SilentlyContinue | Where-Object {
$_.Path -and ([System.IO.Path]::GetFullPath($_.Path) -like "$resolvedVenvRoot*")
}
}
function Stop-VenvProcesses {
param(
[string]$VenvRoot
)
$processes = @(Get-VenvProcesses -VenvRoot $VenvRoot)
if ($processes.Count -eq 0) {
return $false
}
foreach ($process in $processes) {
Write-Host "[bootstrap] stopping locked process $($process.ProcessName) ($($process.Id))"
try {
Stop-Process -Id $process.Id -Force -ErrorAction Stop
} catch {
Write-Host "[bootstrap] unable to stop process $($process.Id): $($_.Exception.Message)"
}
}
Start-Sleep -Milliseconds 500
return $true
}
function Remove-VenvTree {
param(
[string]$VenvRoot
)
if (-not (Test-Path $VenvRoot)) {
return
}
for ($attempt = 1; $attempt -le 3; $attempt++) {
Stop-VenvProcesses -VenvRoot $VenvRoot | Out-Null
try {
Remove-Item -LiteralPath $VenvRoot -Recurse -Force -ErrorAction Stop
return
} catch {
if ($attempt -eq 3) {
throw
}
Write-Host "[bootstrap] remove attempt $attempt failed, retrying: $($_.Exception.Message)"
Start-Sleep -Seconds 1
}
}
}
function Invoke-Pip {
param(
[string]$VenvPython,
[string[]]$Arguments
)
& $VenvPython -m pip --version | Out-Null
if ($LASTEXITCODE -ne 0) {
Write-Host "[bootstrap] pip is missing, bootstrapping it with ensurepip..."
& $VenvPython -m ensurepip --upgrade
}
& $VenvPython -m pip @Arguments
}
function Ensure-Venv {
param(
[string]$PythonExe,
[string]$VenvRoot,
[switch]$Rebuild
)
$venvPython = Join-Path $VenvRoot "Scripts\python.exe"
if ($Rebuild -and (Test-Path $VenvRoot)) {
Write-Host "[bootstrap] rebuilding $VenvRoot..."
Remove-VenvTree -VenvRoot $VenvRoot
}
if (Test-Path $VenvRoot) {
$health = Test-VenvHealthy -VenvRoot $VenvRoot
if (-not $health.IsHealthy) {
$boundHome = $null
$boundExecutable = $null
if ($health.Config -and $health.Config.Values) {
$boundHome = $health.Config.Values["home"]
$boundExecutable = $health.Config.Values["executable"]
}
throw @"
Existing backend\.venv is unhealthy.
Reason: $($health.Reason)
pyvenv.cfg home: $boundHome
pyvenv.cfg executable: $boundExecutable
If you have a working base interpreter, rerun this script with -RebuildVenv to recreate the environment.
If the base interpreter itself cannot run in this shell, fix that first in a normal local PowerShell session.
"@
}
return $venvPython
}
Write-Host "[bootstrap] creating backend\.venv with $PythonExe"
& $PythonExe -m venv $VenvRoot
$health = Test-VenvHealthy -VenvRoot $VenvRoot
if (-not $health.IsHealthy) {
$boundHome = $null
$boundExecutable = $null
if ($health.Config -and $health.Config.Values) {
$boundHome = $health.Config.Values["home"]
$boundExecutable = $health.Config.Values["executable"]
}
throw @"
Virtual environment creation did not produce a healthy backend\.venv.
Reason: $($health.Reason)
pyvenv.cfg home: $boundHome
pyvenv.cfg executable: $boundExecutable
Re-run the bootstrap from a normal local PowerShell session after confirming a working Python interpreter.
"@
}
return $venvPython
}
$repoRoot = $PSScriptRoot
Set-Location $repoRoot
$backendRoot = Join-Path $repoRoot "backend"
if (-not (Test-Path $backendRoot)) {
throw "Backend directory not found at $backendRoot."
}
Set-Location $backendRoot
$pythonExe = Resolve-Python -Version $PreferredPythonVersion
$venvPython = Ensure-Venv -PythonExe $pythonExe -VenvRoot (Join-Path $backendRoot ".venv") -Rebuild:$RebuildVenv
Invoke-Pip -VenvPython $venvPython -Arguments @("install", "--upgrade", "pip", "setuptools", "wheel")
Invoke-Pip -VenvPython $venvPython -Arguments @("install", "-e", ".[dev]")
if ($RunTests) {
& $venvPython -m pytest tests -q
}
if ($RunApp) {
# Load local overrides so real providers work without Docker.
$envFile = Join-Path $backendRoot ".env.docker.local"
if (Test-Path $envFile) {
foreach ($line in Get-Content $envFile) {
if ($line -match '^\s*(.+?)\s*=\s*(.*)$' -and $line -notmatch '^\s*#') {
$key = $Matches[1].Trim()
$val = $Matches[2].Trim()
if ($key -and $val) { [System.Environment]::SetEnvironmentVariable($key, $val, 'Process') }
}
}
Write-Host "[bootstrap] loaded env overrides from $envFile"
}
& $venvPython -m uvicorn app.main:app --reload
}