-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDockerBuild.ps1
More file actions
2161 lines (1912 loc) · 88.5 KB
/
Copy pathDockerBuild.ps1
File metadata and controls
2161 lines (1912 loc) · 88.5 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
# The original of this file is in <PostSharp.Engineering>/src/PostSharp.Engineering.BuildTools/Resources/DockerBuild.ps1.
# You can generate this file using `./Build.ps1 generate-scripts`.
# Documentation: https://raw.githubusercontent.com/postsharp/PostSharp.Engineering/HEAD/doc/dockerbuild.md
<#
.SYNOPSIS
Builds and runs a Docker container for building the product or running Claude CLI.
.DESCRIPTION
Builds a Docker image from the repository's Dockerfile, then runs the build script
(or Claude CLI) inside a container with the source tree and dependencies mounted.
The script automatically:
- Collects environment variables and generates Init.g.ps1 for container startup
- Mounts the source directory, NuGet cache, source-dependencies, and sibling repos
- Handles non-C: drive letters on Windows via subst
- Supports registry image caching for faster CI builds
.PARAMETER Interactive
Opens an interactive PowerShell session inside the container.
.PARAMETER BuildImage
Only builds the Docker image without running the build.
.PARAMETER NoBuildImage
Skips building the Docker image (assumes it already exists).
.PARAMETER Clean
Performs cleanup of bin and obj directories before building.
.PARAMETER NoNuGetCache
Does not mount the host NuGet cache in the container.
.PARAMETER KeepInit
Does not regenerate Init.g.ps1 (keeps the existing one as-is).
The existing Init.g.ps1 is still executed. Cannot be combined with -PostInit.
.PARAMETER PostInit
Path to a script to execute at the end of Init.g.ps1.
The build fails if the PostInit script returns a non-zero exit code.
Cannot be combined with -KeepInit or -NoInit.
.PARAMETER Claude
Runs Claude CLI instead of Build.ps1. Use -Claude for interactive mode,
or pass a prompt as a trailing argument for non-interactive mode.
.PARAMETER NoMcp
Do not connect to the MCP approval server (for -Claude mode).
.PARAMETER Update
Force full timestamp update to invalidate Docker cache and force Claude/plugin updates.
.PARAMETER ImageName
Docker image name. Defaults to a content-hash-based name.
.PARAMETER BuildAgentPath
Path to build agent directory. Defaults based on platform.
.PARAMETER LoadEnvFromKeyVault
Forces loading environment variables from the PostSharpBuildEnv key vault.
.PARAMETER StartVsmon
Mounts and enables the Visual Studio remote debugger in the container.
.PARAMETER Script
The build script to execute inside Docker. Defaults to 'Build.ps1'.
.PARAMETER Dockerfile
Path to a custom Dockerfile. Defaults to Dockerfile or Dockerfile.claude based on -Claude.
.PARAMETER RegistryImage
Use a pre-built image from a registry, skipping Dockerfile build entirely.
.PARAMETER NoInit
Do not generate or call Init.g.ps1 (skips environment variables, git config, safe.directory, etc).
.PARAMETER Isolation
Docker isolation mode: 'process' or 'hyperv'.
When not specified, defaults to 'hyperv' on Windows Desktop and 'process' on Windows Server.
Memory and CPU limits only apply to hyperv isolation.
.PARAMETER Memory
Docker memory limit (e.g., "8g"). Only used with hyperv isolation.
Defaults to $env:BuildAgentMemory (an integer in GB) if set, otherwise 24g.
.PARAMETER Cpus
Docker CPU limit. Use a positive integer for a static limit, or "dynamic" for
automatic allocation that rebalances CPUs across all managed containers.
Only used with hyperv isolation (static) or any isolation (dynamic).
Defaults to $env:BuildAgentCpus if set, otherwise the host processor count.
.PARAMETER Mount
Additional directories to mount from the host (readonly by default, append :w for writable).
Supports * and ** glob patterns.
.PARAMETER Env
Additional environment variables to pass from host to container.
Supports "NAME" (read from host) and "NAME=VALUE" (literal) forms.
.PARAMETER Ports
Port mappings from host to container (e.g., "8080:80", "3000").
.PARAMETER Label
Label to apply to the container for identification (e.g., for cleanup of orphaned build containers).
The label is set as "postsharp.build=<value>" on the container.
.PARAMETER BuildArgs
Arguments passed to Build.ps1 within the container (or Claude prompt if -Claude is specified).
.EXAMPLE
.\DockerBuild.ps1 build
Builds the image and runs Build.ps1 inside the container.
.EXAMPLE
.\DockerBuild.ps1 -Claude
Builds the image and starts an interactive Claude CLI session.
.EXAMPLE
.\DockerBuild.ps1 -Claude "Fix the failing tests"
Runs Claude CLI with the given prompt in non-interactive mode.
.EXAMPLE
.\DockerBuild.ps1 -Interactive
Opens an interactive PowerShell session inside the container.
.EXAMPLE
.\DockerBuild.ps1 build -PostInit eng/SetupLocalDb.ps1
Runs the build with a PostInit script that executes after Init.g.ps1.
#>
[CmdletBinding(PositionalBinding = $false)]
param(
[switch]$Interactive, # Opens an interactive PowerShell session
[switch]$BuildImage, # Only builds the image, but does not build the product.
[switch]$NoBuildImage, # Does not build the image.
[switch]$Clean, # Performs cleanup of bin and obj directories.
[switch]$NoNuGetCache, # Does not mount the host nuget cache in the container.
[switch]$KeepInit, # Does not regenerate Init.g.ps1 (keeps the existing one as-is).
[string]$PostInit, # Script to execute at the end of Init.g.ps1 (fails the build if it fails).
[switch]$Claude, # Run Claude CLI instead of Build.ps1. Use -Claude for interactive, -Claude "prompt" for non-interactive.
[switch]$NoMcp, # Do not start the MCP approval server (for -Claude mode).
[switch]$Update, # Force full timestamp update to invalidate Docker cache and force Claude/plugin updates.
[string]$ImageName, # Image name (defaults to a name based on the directory).
[string]$BuildAgentPath, # Path to build agent directory (defaults based on platform).
[switch]$LoadEnvFromKeyVault, # Forces loading environment variables form the key vault.
[switch]$StartVsmon, # Enable the remote debugger.
[string]$Script = 'Build.ps1', # The build script to be executed inside Docker.
[string]$Dockerfile, # Path to custom Dockerfile (defaults to Dockerfile or Dockerfile.claude based on -Claude).
[string]$RegistryImage, # Use a pre-built image from a registry, skipping Dockerfile build entirely.
[switch]$NoInit, # Do not generate or call Init.g.ps1 (skips git config, safe.directory, etc).
[string]$Isolation = 'process', # Docker isolation mode (process or hyperv). When not specified, defaults to hyperv on Windows Desktop and process on Windows Server. Memory/CPU limits only apply to hyperv.
[string]$Memory = $(if ($env:BuildAgentMemory) { "${env:BuildAgentMemory}g" } else { '24g' }), # Docker memory limit (e.g., "8g"). Only used with hyperv isolation. Defaults to $env:BuildAgentMemory (in GB) or 24g.
[string]$Cpus = $(if ($env:BuildAgentCpus) { $env:BuildAgentCpus } else { [Environment]::ProcessorCount }), # Docker CPU limit. Use a positive integer or "dynamic". Defaults to $env:BuildAgentCpus or host processor count.
[string[]]$Mount, # Additional directories to mount from host (readonly by default, append :w for writable). Supports * and ** glob patterns.
[string[]]$Env, # Additional environment variables to pass from host to container.
[string[]]$Ports, # Port mappings from host to container (e.g., "8080:80", "3000").
[string]$Label, # Label to apply to the container (e.g., for identifying build containers for cleanup).
[Parameter(ValueFromRemainingArguments)]
[string[]]$BuildArgs # Arguments passed to `Build.ps1` within the container (or Claude prompt if -Claude is specified).
)
# Require PowerShell 7.5 or higher (run with pwsh, not powershell)
if ($PSVersionTable.PSVersion -lt [Version]'7.5')
{
Write-Error "This script requires PowerShell 7.5 or higher (run with 'pwsh', not 'powershell'). Current version: $( $PSVersionTable.PSVersion )"
exit 1
}
####
# These settings are replaced by the generate-scripts command.
$EngPath = 'eng'
$EnvironmentVariables = 'AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AZ_IDENTITY_USERNAME,AZURE_CLIENT_ID,AZURE_CLIENT_SECRET,AZURE_DEVOPS_TOKEN,AZURE_DEVOPS_USER,AZURE_TENANT_ID,CLAUDE_CODE_OAUTH_TOKEN,DOC_API_KEY,DOWNLOADS_API_KEY,ENG_USERNAME,GIT_USER_EMAIL,GIT_USER_NAME,GITHUB_AUTHOR_EMAIL,GITHUB_REVIEWER_TOKEN,GITHUB_TOKEN,IS_POSTSHARP_OWNED,IS_TEAMCITY_AGENT,MetalamaLicense,NUGET_ORG_API_KEY,PostSharpLicense,SIGNSERVER_SECRET,TEAMCITY_CLOUD_TOKEN,TYPESENSE_API_KEY,VS_MARKETPLACE_ACCESS_TOKEN,VSS_NUGET_EXTERNAL_FEED_ENDPOINTS'
$DockerImagePrefix = 'postsharpengineering-2023.2'
$OvercommitRatio = 1.0
####
$ErrorActionPreference = "Stop"
$dockerContextDirectory = "$EngPath/docker-context"
# Detect platform (use built-in variables if available, fallback for older PowerShell)
if ($null -eq $IsWindows)
{
$IsWindows = [System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT
}
$IsUnix = -not $IsWindows # Covers both Linux and macOS
# Docker isolation is Windows-only. Windows Server supports process isolation (faster,
# no per-container VM); Windows Desktop (client) only reliably runs hyperv isolation.
# Auto-detect by Windows edition unless -Isolation was passed explicitly.
if ($IsWindows -and -not $PSBoundParameters.ContainsKey('Isolation'))
{
# Win32_OperatingSystem.ProductType: 1 = Workstation (Desktop), 2/3 = Server.
$productType = (Get-CimInstance -ClassName Win32_OperatingSystem).ProductType
$Isolation = if ($productType -eq 1) { 'hyperv' } else { 'process' }
Write-Host "Detected Windows ProductType=$productType; using --isolation=$Isolation" -ForegroundColor Cyan
}
$isolationArg = if ($IsWindows)
{
"--isolation=$Isolation"
}
else
{
""
}
# Set BuildAgentPath default based on platform
if ( [string]::IsNullOrEmpty($BuildAgentPath))
{
if ($env:TEAMCITY_JRE)
{
$BuildAgentPath = Split-Path $env:TEAMCITY_JRE -Parent
}
elseif ($IsUnix)
{
$BuildAgentPath = '/build-agent'
}
else
{
$BuildAgentPath = 'C:\BuildAgent'
}
}
# Capture the calling directory (where the user invoked the script from)
# This will be used as the working directory in the container
$CallingDirectory = (Get-Location).Path
# Resolve Dockerfile path relative to original current directory (before changing location)
# This must be done before Set-Location to preserve the user's intended relative path
if ($Dockerfile -and -not [System.IO.Path]::IsPathRooted($Dockerfile))
{
$Dockerfile = Join-Path $CallingDirectory $Dockerfile
}
# Resolve PostInit path relative to original current directory (before changing location)
if ($PostInit -and -not [System.IO.Path]::IsPathRooted($PostInit))
{
$PostInit = Join-Path $CallingDirectory $PostInit
}
# Save current location and restore on exit
Push-Location
try
{
Set-Location $PSScriptRoot
# Validate parameter combinations
if ($PostInit -and $NoInit)
{
Write-Error "-PostInit cannot be used with -NoInit."
exit 1
}
if ($PostInit -and $KeepInit)
{
Write-Error "-PostInit cannot be used with -KeepInit."
exit 1
}
# Validate and parse -Cpus parameter
$isDynamicCpus = $false
if ($Cpus -eq 'dynamic')
{
$isDynamicCpus = $true
$TotalCpus = if ($env:BuildAgentCpus) { [int]$env:BuildAgentCpus } else { [Environment]::ProcessorCount }
Write-Host "Dynamic CPU allocation enabled. Total CPUs: $TotalCpus, Overcommit ratio: $OvercommitRatio" -ForegroundColor Cyan
}
else
{
$cpuInt = 0
if (-not [int]::TryParse($Cpus, [ref]$cpuInt) -or $cpuInt -le 0)
{
Write-Error "-Cpus must be a positive integer or 'dynamic'. Got: '$Cpus'"
exit 1
}
$Cpus = $cpuInt
}
if ($env:IS_TEAMCITY_AGENT)
{
Write-Host "Running on TeamCity agent at '$BuildAgentPath'" -ForegroundColor Cyan
}
# Dynamic CPU allocation helpers
$DynamicCpuLabel = 'managed-by=DockerBuild'
function Get-DynamicCpuAllocation
{
param(
[int]$AdditionalContainers = 0
)
$budget = $TotalCpus * (1.0 + $OvercommitRatio)
# Count running containers with the dynamic CPU label
$containerIds = @(docker ps -q --filter "label=$DynamicCpuLabel" 2>$null)
# Filter out empty strings from docker output
$containerIds = @($containerIds | Where-Object { $_ -and $_.Trim() -ne '' })
$runningCount = $containerIds.Count
$totalContainers = $runningCount + $AdditionalContainers
if ($totalContainers -le 0) { $totalContainers = 1 }
$allocation = [Math]::Min($TotalCpus, [Math]::Floor($budget / $totalContainers))
if ($allocation -lt 1) { $allocation = 1 }
return @{
Allocation = [int]$allocation
ContainerIds = $containerIds
}
}
function Invoke-DynamicCpuRebalance
{
param(
[int]$AdditionalContainers = 0
)
$result = Get-DynamicCpuAllocation -AdditionalContainers $AdditionalContainers
$allocation = $result.Allocation
$containerIds = $result.ContainerIds
if ($containerIds.Count -gt 0)
{
Write-Host "Rebalancing $( $containerIds.Count ) managed container(s) to $allocation CPUs each" -ForegroundColor Cyan
foreach ($cid in $containerIds)
{
try
{
docker update --cpus=$allocation $cid 2>$null | Out-Null
}
catch
{
Write-Warning "Failed to rebalance container $cid`: $_"
}
}
}
else
{
Write-Host "Dynamic CPU allocation: $allocation CPUs (no other managed containers)" -ForegroundColor Cyan
}
return $allocation
}
# Function to collect environment variables for container
function New-EnvHashtable
{
param(
[string]$EnvironmentVariableList
)
# Parse comma-separated environment variable names
$envVarNames = $EnvironmentVariableList -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }
# Build hashtable with environment variable values
$envVariables = @{ }
foreach ($envVarName in $envVarNames)
{
$value = [Environment]::GetEnvironmentVariable($envVarName)
if (-not [string]::IsNullOrEmpty($value))
{
$envVariables[$envVarName] = $value
}
}
# Process additional environment variables from -Env parameter
# Supports both "NAME" (read from host) and "NAME=VALUE" (literal value) forms
if ($Env -and $Env.Count -gt 0)
{
foreach ($envSpec in $Env)
{
if ($envSpec -match '^([^=]+)=(.*)$')
{
# NAME=VALUE form: use literal value
$envVarName = $Matches[1]
$value = $Matches[2]
$envVariables[$envVarName] = $value
}
else
{
# NAME form: read from host environment
$envVarName = $envSpec
$value = [Environment]::GetEnvironmentVariable($envVarName)
if (-not [string]::IsNullOrEmpty($value))
{
$envVariables[$envVarName] = $value
}
}
}
}
# Add NUGET_PACKAGES with default if not set
if (-not $envVariables.ContainsKey("NUGET_PACKAGES"))
{
$nugetPackages = $env:NUGET_PACKAGES
if ( [string]::IsNullOrEmpty($nugetPackages))
{
if ($IsUnix)
{
$nugetPackages = Join-Path $env:HOME ".nuget/packages"
}
else
{
$nugetPackages = Join-Path $env:USERPROFILE ".nuget\packages"
}
}
$envVariables["NUGET_PACKAGES"] = $nugetPackages
}
# Add secrets from the PostSharpBuildEnv key vault, on our development machines.
# On CI agents, these environment variables are supposed to be set by the host.
if ($LoadEnvFromKeyVault -or ($env:IS_POSTSHARP_OWNED -and -not $env:IS_TEAMCITY_AGENT))
{
$moduleName = "Az.KeyVault"
if (-not (Get-Module -ListAvailable -Name $moduleName))
{
Write-Error "The required module '$moduleName' is not installed. Please install it with: Install-Module -Name $moduleName"
exit 1
}
Import-Module $moduleName
foreach ($secret in Get-AzKeyVaultSecret -VaultName "PostSharpBuildEnv")
{
$secretWithValue = Get-AzKeyVaultSecret -VaultName "PostSharpBuildEnv" -Name $secret.Name
$envName = $secretWithValue.Name -Replace "-", "_"
$envValue = (ConvertFrom-SecureString $secretWithValue.SecretValue -AsPlainText)
$envVariables[$envName] = $envValue
}
}
# Print sorted list of environment variables being passed
$sortedKeys = $envVariables.Keys | Sort-Object
Write-Host "Environment variables: $( $sortedKeys -join ', ' )" -ForegroundColor Gray
# Store in script-level variable for Init.g.ps1 generation
$script:ContainerEnvironmentVariables = $envVariables
}
# Function to collect Claude-specific environment variables for container
function New-ClaudeEnvHashtable
{
$claudeEnv = @{ }
# Process $EnvironmentVariables list - only transfer variables that have CLAUDE_ prefix defined
# e.g., if CLAUDE_GITHUB_TOKEN is set, transfer it as GITHUB_TOKEN
$envVarNames = $EnvironmentVariables -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }
foreach ($envVarName in $envVarNames)
{
$claudeVarName = "CLAUDE_$envVarName"
$value = [Environment]::GetEnvironmentVariable($claudeVarName)
if (-not [string]::IsNullOrEmpty($value))
{
$claudeEnv[$envVarName] = $value
}
}
# Preserved variables (transferred as-is, without requiring CLAUDE_ prefix)
if ($env:ANTHROPIC_API_KEY)
{
$claudeEnv["ANTHROPIC_API_KEY"] = $env:ANTHROPIC_API_KEY
}
if ($env:CLAUDE_CODE_OAUTH_TOKEN)
{
$claudeEnv["CLAUDE_CODE_OAUTH_TOKEN"] = $env:CLAUDE_CODE_OAUTH_TOKEN
}
if ($env:IS_POSTSHARP_OWNED)
{
$claudeEnv["IS_POSTSHARP_OWNED"] = $env:IS_POSTSHARP_OWNED
}
if ($env:IS_TEAMCITY_AGENT)
{
$claudeEnv["IS_TEAMCITY_AGENT"] = $env:IS_TEAMCITY_AGENT
}
# Git identity - CLAUDE_ prefixed vars take precedence, then GIT_USER_*, then git config
$gitUserName = $env:CLAUDE_GIT_USER_NAME
if (-not $gitUserName)
{
$gitUserName = $env:GIT_USER_NAME
}
if (-not $gitUserName)
{
$gitUserName = git config --global user.name
}
$gitUserEmail = $env:CLAUDE_GIT_USER_EMAIL
if (-not $gitUserEmail)
{
$gitUserEmail = $env:GIT_USER_EMAIL
}
if (-not $gitUserEmail)
{
$gitUserEmail = git config --global user.email
}
if ($gitUserName)
{
$claudeEnv["GIT_USER_NAME"] = $gitUserName
}
if ($gitUserEmail)
{
$claudeEnv["GIT_USER_EMAIL"] = $gitUserEmail
}
# Add NUGET_PACKAGES with default if not set
$nugetPackages = $env:NUGET_PACKAGES
if ( [string]::IsNullOrEmpty($nugetPackages))
{
if ($IsUnix)
{
$nugetPackages = Join-Path $env:HOME ".nuget/packages"
}
else
{
$nugetPackages = Join-Path $env:USERPROFILE ".nuget\packages"
}
}
$claudeEnv["NUGET_PACKAGES"] = $nugetPackages
# Process additional environment variables from -Env parameter
# Supports both "NAME" (read from host) and "NAME=VALUE" (literal value) forms
# In Claude mode, CLAUDE_FOO takes precedence over FOO
if ($Env -and $Env.Count -gt 0)
{
foreach ($envSpec in $Env)
{
if ($envSpec -match '^([^=]+)=(.*)$')
{
# NAME=VALUE form: use literal value
$envVarName = $Matches[1]
$value = $Matches[2]
$claudeEnv[$envVarName] = $value
}
else
{
# NAME form: read from host environment (with CLAUDE_ prefix support)
$envVarName = $envSpec
$claudeVarName = "CLAUDE_$envVarName"
$value = [Environment]::GetEnvironmentVariable($claudeVarName)
if ( [string]::IsNullOrEmpty($value))
{
$value = [Environment]::GetEnvironmentVariable($envVarName)
}
if (-not [string]::IsNullOrEmpty($value))
{
$claudeEnv[$envVarName] = $value
}
}
}
}
# Print sorted list of environment variables being passed
$sortedKeys = $claudeEnv.Keys | Sort-Object
Write-Host "Environment variables: $( $sortedKeys -join ', ' )" -ForegroundColor Gray
# Store in script-level variable for Init.g.ps1 generation
$script:ContainerEnvironmentVariables = $claudeEnv
}
# Fixed port for MCP approval server (must match McpHttpServer.FixedPort)
$mcpFixedPort = 9847
# Function to check if the MCP approval server is running
function Test-McpServerRunning
{
param(
[int]$Port = $mcpFixedPort
)
try
{
$response = Invoke-WebRequest -Uri "http://localhost:$Port/health" -TimeoutSec 10 -ErrorAction Stop
return $response.StatusCode -eq 200
}
catch
{
return $false
}
}
function Get-TimestampFile
{
# Persists $script:DayStamp (the single source of truth, also mixed
# into the image tag by Get-ContentHash in Claude mode) to disk so
# Dockerfile.claude can COPY it in and invalidate inner layers on
# the same day boundary as the outer image tag.
$timestampDir = if ($IsUnix)
{
Join-Path $env:HOME ".local/share/PostSharp.Engineering"
}
else
{
Join-Path $env:LOCALAPPDATA "PostSharp.Engineering"
}
$timestampFile = Join-Path $timestampDir "update.timestamp"
# Ensure directory exists
if (-not (Test-Path $timestampDir))
{
New-Item -ItemType Directory -Path $timestampDir -Force | Out-Null
}
# Only rewrite the file if the content would actually change — avoids
# bumping mtime on every run, which would pointlessly invalidate the
# Docker COPY layer for the timestamp file.
$needsUpdate = $true
if (Test-Path $timestampFile)
{
$currentTimestamp = Get-Content $timestampFile -Raw -ErrorAction SilentlyContinue
if ($currentTimestamp -eq $script:DayStamp)
{
$needsUpdate = $false
}
}
if ($needsUpdate)
{
Set-Content -Path $timestampFile -Value $script:DayStamp -NoNewline -Force
$label = if ($Update) { "forced" } else { "daily" }
Write-Host "Timestamp file updated ($label): $script:DayStamp" -ForegroundColor Cyan
}
return $timestampFile
}
function Get-ContentHash
{
param(
[string]$DockerfilePath,
[string]$ContextDirectory,
[string]$DayStamp, # non-empty => mix into hash (used in -Claude mode)
[string]$ExtraInput # folded in so a base-image (or OS) change invalidates this image's hash
)
$hashInput = Get-Content $DockerfilePath -Raw -ErrorAction SilentlyContinue
if (-not $hashInput)
{
$hashInput = ""
}
# Add context files (excluding generated .g/ directory, which holds
# per-invocation files like env.g.json and Init.g.ps1).
$contextFiles = Get-ChildItem $ContextDirectory -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -notmatch '[/\\]\.g[/\\]' } |
Sort-Object FullName
foreach ($file in $contextFiles)
{
$content = Get-Content $file.FullName -Raw -ErrorAction SilentlyContinue
if ($content)
{
$hashInput += "`n--- $( $file.Name ) ---`n"
$hashInput += $content
}
}
# When a day stamp is supplied (Claude mode), rotate the image tag once
# per UTC day so @latest npm installs of the Claude CLI and marketplace
# plug-ins actually get refreshed. Same string as update.timestamp.
if ($DayStamp)
{
$hashInput += "`n--- day-stamp ---`n$DayStamp"
}
# Fold the base/OS discriminator so a parent-image change (or a different WINDOWS_VERSION) yields a
# different tag for this image and all its descendants.
if ($ExtraInput)
{
$hashInput += "`n--- base ---`n$ExtraInput"
}
# Normalize line endings so the hash is identical whether files were checked out with LF (typical on a
# dev machine) or CRLF (git autocrlf on CI). Otherwise the same Dockerfile yields a different tag on CI
# than on dev, the registry cache never hits, and CI rebuilds the chain from scratch every time.
$hashInput = $hashInput -replace "`r", ""
$hashBytes = [System.Security.Cryptography.SHA256]::Create().ComputeHash(
[System.Text.Encoding]::UTF8.GetBytes($hashInput)
)
# Use 8 bytes (16 hex chars) for uniqueness
return [System.BitConverter]::ToString($hashBytes, 0, 8).Replace("-", "").ToLower()
}
# --- Image chain resolution ---------------------------------------------------------------------
# A Dockerfile may declare its parent with `ARG BASE_IMAGE=<parent>.Dockerfile`. We resolve that to the
# parent's content-hash tag (building or pulling it first), fold the parent tag into this image's hash, and
# inject --build-arg BASE_IMAGE=<parentTag>. The image NAME is the Dockerfile stem (e.g.
# <prefix>-build.Dockerfile -> image <prefix>-build), so the product/version prefix lives in the file name.
$script:resolvedTags = @{ }
function Get-DockerfileStem([string]$dfPath)
{
return [System.IO.Path]::GetFileNameWithoutExtension($dfPath)
}
# Per-image build context: docker-context/<stem>, falling back to the shared docker-context when there is
# no per-image directory (keeps un-stemmed/legacy Dockerfiles working).
function Get-ContextDirFor([string]$dfPath)
{
$perImage = Join-Path $dockerContextDirectory (Get-DockerfileStem $dfPath)
if (Test-Path $perImage) { return $perImage } else { return $dockerContextDirectory }
}
# Parse the parent Dockerfile from `ARG BASE_IMAGE=<parent>.Dockerfile`; $null if this is a chain root.
function Get-BaseDockerfile([string]$dfPath)
{
foreach ($line in (Get-Content $dfPath -ErrorAction SilentlyContinue))
{
if ($line -match '^\s*ARG\s+BASE_IMAGE\s*=\s*(\S+\.Dockerfile)\s*$')
{
return (Join-Path (Split-Path $dfPath -Parent) $Matches[1])
}
}
return $null
}
# Pure: compute the content-hash tag for a Dockerfile and (recursively) its ancestors. No docker calls.
function Resolve-ImageTag([string]$dfPath)
{
$key = $dfPath.ToLower()
if ($script:resolvedTags.ContainsKey($key)) { return $script:resolvedTags[$key] }
$baseFold = $null
$baseDf = Get-BaseDockerfile $dfPath
if ($baseDf)
{
if (-not (Test-Path $baseDf)) { Write-Error "Base Dockerfile '$baseDf' referenced by '$dfPath' was not found."; exit 1 }
# Fold only the base's CONTENT HASH (the part after the last ':'), never the full tag - so the child
# hash is independent of the registry prefix and is identical in local and registry modes.
$baseFold = ((Resolve-ImageTag $baseDf) -split ':')[-1]
}
# OS discriminator so ltsc2025 / ltsc2022 produce distinct tags of the same image name. Propagates to
# descendants through $baseFold.
$extra = "os=$windowsVersion|base=$baseFold"
# Fold the daily stamp only for images that bake the update.timestamp cache-buster (the Claude leaf), so
# @latest npm installs of the Claude CLI and plug-ins refresh once per UTC day.
$body = Get-Content $dfPath -Raw -ErrorAction SilentlyContinue
$hashDayStamp = if ($body -and $body -match 'update\.timestamp') { $script:DayStamp } else { $null }
$hash = Get-ContentHash -DockerfilePath $dfPath -ContextDirectory (Get-ContextDirFor $dfPath) -DayStamp $hashDayStamp -ExtraInput $extra
# The image NAME carries the product/version prefix ($DockerImagePrefix); the Dockerfile file stem does
# not. e.g. stem 'build' -> image '<prefix>-build'. ARG BASE_IMAGE references stems (prefix-free).
$imageName = "$DockerImagePrefix-$( Get-DockerfileStem $dfPath )"
$tag = if ($dockerRegistry) { "${dockerRegistry}/${imageName}:${hash}" } else { "${imageName}:${hash}" }
$script:resolvedTags[$key] = $tag
return $tag
}
# The platform-specific mountpoints-creation step. This is NEVER baked into a chain Dockerfile - it goes
# only into the dynamically generated boot image (see New-BootImage), so the chain images stay clean and
# free of the machine-specific mount set.
function Get-MountpointsBlock
{
if ($IsWindows)
{
return @"
ARG MOUNTPOINTS
RUN if (`$env:MOUNTPOINTS) { ``
`$mounts = `$env:MOUNTPOINTS -split ';'; ``
foreach (`$dir in `$mounts) { ``
if (`$dir) { ``
Write-Host "Creating directory `$dir``."; ``
New-Item -ItemType Directory -Path `$dir -Force | Out-Null; ``
} ``
} ``
}
"@
}
else
{
return @"
ARG MOUNTPOINTS
RUN if [ -n "`$MOUNTPOINTS" ]; then \
OLD_IFS="`$IFS"; \
IFS=':'; \
set -- `$MOUNTPOINTS; \
IFS="`$OLD_IFS"; \
for dir in "`$@"; do \
if [ -n "`$dir" ]; then \
echo "Creating directory `$dir."; \
mkdir -p "`$dir"; \
fi; \
done; \
fi
"@
}
}
# Build one chain image from its STATIC Dockerfile, unmodified (per-image context, base build-arg).
function Build-OneImage([string]$dfPath, [string]$tag, [string[]]$baseBuildArg)
{
$content = Get-Content -Raw $dfPath # piped to docker build verbatim - the file on disk is never changed
$ctxDir = Get-ContextDirFor $dfPath
$cmd = @('build', '-t', $tag)
if ($isolationArg) { $cmd += $isolationArg }
if ($Memory -and $Isolation -ne 'process') { $cmd += "--memory=$Memory" }
# Pass WINDOWS_VERSION only to the root image that declares it (avoids 'unconsumed build-arg' warnings).
if ($IsWindows -and $windowsVersion -and ($content -match 'ARG\s+WINDOWS_VERSION'))
{
$cmd += @('--build-arg', "WINDOWS_VERSION=$windowsVersion")
}
$cmd += $baseBuildArg
$cmd += @('-f', '-', $ctxDir)
Write-Host "Building $tag" -ForegroundColor Green
Write-Host "Docker command: docker $( $cmd -join ' ' )" -ForegroundColor Cyan
# Pipe docker output to the host so it does NOT become this function's return value (which would
# otherwise pollute the tag string the caller folds into the next --build-arg BASE_IMAGE).
$content | & docker @cmd 2>&1 | Out-Host
if ($LASTEXITCODE -ne 0) { Write-Host "Docker build failed for $tag (exit $LASTEXITCODE)" -ForegroundColor Red; exit $LASTEXITCODE }
$script:builtNewImage = $true
}
# Build the local "boot" image: a thin layer over the resolved chain image that creates the bind-mount
# directories. The mount set is machine-specific, so this is kept out of the shared chain images and is
# never pushed. Returns the boot image tag, which is what `docker run` uses.
#
# The boot image is the leaf that `docker run` actually executes, so its tag must be GLOBALLY UNIQUE:
# concurrent invocations on the same host resolve to the same chain hash and would otherwise collide on a
# single boot tag, with one run rebuilding (or removing) the image out from under the other. A
# YYYYMMDDTHHmmss timestamp suffix keeps each run's leaf image distinct. The image is removed after the run
# (see the boot-image cleanup near the end), so unique tags do not accumulate.
function New-BootImage([string]$baseTag)
{
$ref = ($baseTag -split '/')[-1] # strip any registry prefix - the boot image is local only
$stamp = (Get-Date).ToString("yyyyMMdd'T'HHmmss") # local time; only needs to be unique per host run
if ($ref -match '^(.*):([^:]+)$') { $bootTag = "$( $Matches[1] )-boot:$( $Matches[2] )-$stamp" } else { $bootTag = "$ref-boot:$stamp" }
$script:BootImageTag = $bootTag # tracked so the run can remove this leaf image afterwards
# On Windows the mountpoints RUN uses backtick line-continuations, so set `# escape=` + backtick. On
# Unix the block uses backslash continuations, so keep Docker's default escape char (emit no directive).
$escapeLine = if ($IsWindows) { "# escape=$([char]96)`n" } else { "" }
$content = $escapeLine + "FROM $baseTag`n" + (Get-MountpointsBlock)
# The boot layer has no COPY, so build it against an empty context.
$bootCtx = Join-Path ([System.IO.Path]::GetTempPath()) "docker-boot-$( New-Guid )"
New-Item -ItemType Directory -Path $bootCtx -Force | Out-Null
try
{
$cmd = @('build', '-t', $bootTag)
if ($isolationArg) { $cmd += $isolationArg }
if ($Memory -and $Isolation -ne 'process') { $cmd += "--memory=$Memory" }
$cmd += @('--build-arg', "MOUNTPOINTS=$mountPointsAsString", '-f', '-', $bootCtx)
Write-Host "Building boot image $bootTag (bind-mount dirs) over $baseTag" -ForegroundColor Green
$content | & docker @cmd 2>&1 | Out-Host
if ($LASTEXITCODE -ne 0) { Write-Host "Boot image build failed for $bootTag (exit $LASTEXITCODE)" -ForegroundColor Red; exit $LASTEXITCODE }
}
finally { Remove-Item $bootCtx -Recurse -Force -ErrorAction SilentlyContinue }
return $bootTag
}
# Ensure the image and its ancestors exist (parent first): use local, else pull, else build; queue a push
# when building in registry mode. Returns the image tag.
function Ensure-Image([string]$dfPath)
{
$baseBuildArg = @()
$baseDf = Get-BaseDockerfile $dfPath
if ($baseDf)
{
$baseTag = Ensure-Image $baseDf
$baseBuildArg = @('--build-arg', "BASE_IMAGE=$baseTag")
}
$tag = Resolve-ImageTag $dfPath
Write-Host "Ensuring image: $tag" -ForegroundColor Cyan
docker image inspect $tag *> $null
if ($LASTEXITCODE -eq 0)
{
Write-Host " found locally" -ForegroundColor Green
}
elseif ($dockerRegistry -and (& { docker @dockerConfigArg manifest inspect $tag *> $null; $LASTEXITCODE -eq 0 }))
{
Write-Host " pulling from registry" -ForegroundColor Green
docker @dockerConfigArg pull $tag 2>&1 | Out-Host
if ($LASTEXITCODE -ne 0) { Write-Host "Docker pull failed for $tag" -ForegroundColor Red; exit 1 }
return $tag
}
else
{
Build-OneImage $dfPath $tag $baseBuildArg
}
# Queue an async push if the image isn't already in the registry. Pushes run in background jobs started
# after ALL builds (so a push never overlaps a host docker build) and are waited for at the end.
if ($dockerRegistry)
{
docker @dockerConfigArg manifest inspect $tag *> $null
if ($LASTEXITCODE -ne 0)
{
Write-Host " queued for async push to registry" -ForegroundColor Cyan
$script:ImagesToPush += $tag
}
}
return $tag
}
# Dictionary to track volume mounts with "writable wins" logic
$script:VolumeMountDict = @{ }
# Async registry push: images are queued during chain resolution, pushed in background jobs started after
# ALL builds complete (so a push never overlaps a host docker build), and all waited for at the end.
$script:ImagesToPush = @()
$script:RegistryPushJobs = @()
# Tag of the local, run-specific boot image (set by New-BootImage); removed after the container exits.
$script:BootImageTag = $null
function Add-VolumeMount
{
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[switch]$Writable
)
$normalizedPath = $Path.TrimEnd('\', '/')
$normalizedKey = $normalizedPath.ToLower()
$isGitDirectory = Test-Path (Join-Path $normalizedPath ".git")
if ( $script:VolumeMountDict.ContainsKey($normalizedKey))
{
if ($Writable)
{
$script:VolumeMountDict[$normalizedKey].Writable = $true
}
}
else
{
$script:VolumeMountDict[$normalizedKey] = @{
HostPath = $normalizedPath
Writable = [bool]$Writable
IsGitDirectory = $isGitDirectory
}
}
}
if ($env:RUNNING_IN_DOCKER)
{
Write-Error "Already running in Docker."
exit 1
}
if ($RegistryImage)
{
# Use the pre-built registry image directly, skip all Dockerfile logic
$ImageTag = $RegistryImage
$NoBuildImage = $true
Write-Host "Using registry image: $ImageTag" -ForegroundColor Cyan
}
else
{
# Single source of truth for today's cache-busting stamp, shared by
# Get-ContentHash (image tag, Claude mode only) and Get-TimestampFile
# (update.timestamp file baked into the image). Computing it once here
# guarantees both consumers see the same value even if the wall clock
# crosses UTC midnight mid-run.
$script:DayStamp = if ($Update)
{
[DateTime]::UtcNow.ToString("o") # full ISO 8601, seconds precision
}
else
{
[DateTime]::UtcNow.Date.ToString("yyyy-MM-dd")
}
# Determine which Dockerfile will be used.
$DockerfilesDir = "$EngPath/docker"
# Detect the Windows base-image tag. The OS variant is delivered as the WINDOWS_VERSION build-arg (and
# folded into the content hash) rather than as a separate Dockerfile, so one chain serves both editions.
# Windows build < 26100 is Windows Server 2022; otherwise Windows Server 2025.
$windowsVersion = $null
if ($IsWindows)
{
$osBuild = [System.Environment]::OSVersion.Version.Build
$windowsVersion = if ($osBuild -lt 26100) { 'ltsc2022' } else { 'ltsc2025' }
Write-Host "Detected Windows build $osBuild; using base image tag '$windowsVersion'" -ForegroundColor Cyan
}
if (-not $Dockerfile)
{
# Dockerfile names are prefix-free ("<layer>.Dockerfile"). -Claude targets the claude leaf; otherwise
# the build leaf. The chain resolver walks ARG BASE_IMAGE to build/pull the ancestors first.
$layer = if ($Claude) { 'claude' } else { 'build' }
$Dockerfile = "$DockerfilesDir/$layer.Dockerfile"
}
# Get the full path of the Dockerfile
if ( [System.IO.Path]::IsPathRooted($Dockerfile))
{
$dockerfileFullPath = $Dockerfile
}
else
{
$dockerfileFullPath = Join-Path $PSScriptRoot $Dockerfile
}
# Resolve the Docker registry for build images (env-based). Registry mode is off (local image tags) if
# not set. Set before Resolve-ImageTag, which uses it to form the tag.