-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDockerBuild.ps1
More file actions
1887 lines (1664 loc) · 71.9 KB
/
DockerBuild.ps1
File metadata and controls
1887 lines (1664 loc) · 71.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
# 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`.
<#
.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' (default) or 'hyperv'.
Memory and CPU limits only apply to hyperv isolation.
.PARAMETER Memory
Docker memory limit (e.g., "8g"). Only used with hyperv isolation. Defaults to 24g.
.PARAMETER Cpus
Docker CPU limit. Defaults to the host processor count. Only used with hyperv isolation.
.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 = 'hyperv', # Docker isolation mode (process or hyperv). Memory/CPU limits only apply to hyperv.
[string]$Memory = '24g', # Docker memory limit (e.g., "8g"). Only used with hyperv isolation.
[int]$Cpus = [Environment]::ProcessorCount, # Docker CPU limit. Only used with hyperv isolation.
[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'
####
$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
$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
}
if ($env:IS_TEAMCITY_AGENT)
{
Write-Host "Running on TeamCity agent at '$BuildAgentPath'" -ForegroundColor Cyan
}
# 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:EnvironmentVariablesToSet = $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:EnvironmentVariablesToSet = $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
{
param(
[switch]$Update
)
$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
}
if ($Update)
{
# Force update with full timestamp (seconds precision) to invalidate cache
$timestamp = [DateTime]::UtcNow.ToString("o") # ISO 8601 format
Set-Content -Path $timestampFile -Value $timestamp -NoNewline -Force
Write-Host "Timestamp file updated (forced): $timestamp" -ForegroundColor Cyan
}
else
{
# Daily timestamp - only update if file doesn't exist or date changed
$todayTimestamp = [DateTime]::UtcNow.Date.ToString("yyyy-MM-dd")
$needsUpdate = $true
if (Test-Path $timestampFile)
{
$currentTimestamp = Get-Content $timestampFile -Raw
# Check if current timestamp starts with today's date
if ($currentTimestamp -and $currentTimestamp.StartsWith($todayTimestamp))
{
$needsUpdate = $false
}
}
if ($needsUpdate)
{
Set-Content -Path $timestampFile -Value $todayTimestamp -NoNewline -Force
Write-Host "Timestamp file updated (daily): $todayTimestamp" -ForegroundColor Cyan
}
}
return $timestampFile
}
function Get-ContentHash
{
param(
[string]$DockerfilePath,
[string]$ContextDirectory
)
$hashInput = Get-Content $DockerfilePath -Raw -ErrorAction SilentlyContinue
if (-not $hashInput)
{
$hashInput = ""
}
# Add context files (excluding generated .g/ directory)
$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
}
}
$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()
}
# Dictionary to track volume mounts with "writable wins" logic
$script:VolumeMountDict = @{ }
# Background job for async registry push (if applicable)
$script:RegistryPushJob = $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
{
# Determine which Dockerfile will be used (needed for ImageName generation)
$DockerfilesDir = "$EngPath/docker"
if (-not $Dockerfile)
{
# Start with the base Dockerfile name
$Dockerfile = "$DockerfilesDir/Dockerfile"
# Append .claude suffix if in Claude mode
if ($Claude)
{
$Dockerfile = "$Dockerfile.claude"
}
# Win2022 detection - append .win2022 suffix (applies to both standard and Claude)
if ($IsWindows)
{
$osBuild = [System.Environment]::OSVersion.Version.Build
if ($osBuild -lt 26100)
{
$win2022Dockerfile = "$Dockerfile.win2022"
if (Test-Path (Join-Path $PSScriptRoot $win2022Dockerfile))
{
Write-Host "Detected Windows Server 2022 (build $osBuild), using $win2022Dockerfile" -ForegroundColor Cyan
$Dockerfile = $win2022Dockerfile
}
}
}
}
# Get the full path of the Dockerfile
if ( [System.IO.Path]::IsPathRooted($Dockerfile))
{
$dockerfileFullPath = $Dockerfile
}
else
{
$dockerfileFullPath = Join-Path $PSScriptRoot $Dockerfile
}
# Generate content-based hash for image tag
$contentHash = Get-ContentHash -DockerfilePath $dockerfileFullPath -ContextDirectory $dockerContextDirectory
$dockerRegistry = $env:DOCKER_REGISTRY
if ($dockerRegistry)
{
# Registry mode: use registry URL with image name and content hash
$ImageTag = "${dockerRegistry}/build-${contentHash}:${contentHash}"
Write-Host "Registry image tag: $ImageTag" -ForegroundColor Cyan
}
elseif ([string]::IsNullOrEmpty($ImageName))
{
$ImageTag = "dockerfile-$contentHash"
Write-Host "Generated image tag from content hash: $ImageTag" -ForegroundColor Cyan
}
else
{
$ImageTag = "$ImageName`:$contentHash"
Write-Host "Image will be tagged as: $ImageTag" -ForegroundColor Cyan
}
}
# Check MCP server availability for -Claude mode
# The MCP approval server is now a standalone GUI app that must be started separately
$mcpServerAvailable = $false
if ($Claude -and -not $NoMcp)
{
if (Test-McpServerRunning)
{
Write-Host "MCP approval server detected on port $mcpFixedPort" -ForegroundColor Cyan
$mcpServerAvailable = $true
}
else
{
Write-Warning "MCP approval server not running on port $mcpFixedPort."
Write-Warning "Start PostSharp.Engineering.McpApprovalServer.exe before using -Claude mode for host operations."
Write-Warning "Continuing without MCP server support."
}
}
# When building locally (as opposed as on the build agent), we can optionally do a complete cleanup because
# obj files may point to the host filesystem.
if ($Clean)
{
Write-Host "Cleaning up." -ForegroundColor Green
Get-ChildItem "bin" -Recurse | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
Get-ChildItem "obj" -Recurse | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
}
Write-Host "Preparing context and mounts." -ForegroundColor Green
# Collect environment variables for container (will be inlined in Init.g.ps1)
if (-not $KeepInit)
{
# Create timestamp file for cache invalidation (only if building image)
# This is used by Dockerfile.claude but doesn't affect other Dockerfiles
if (-not $NoBuildImage)
{
$timestampFile = Get-TimestampFile -Update:$Update
}
if ($Claude)
{
# Use Claude-specific environment variables (filtered and renamed)
New-ClaudeEnvHashtable
}
else
{
# Use standard build environment variables
if (-not $env:ENG_USERNAME)
{
$env:ENG_USERNAME = $env:USERNAME
}
# Add git identity to environment
if ($env:IS_TEAMCITY_AGENT)
{
# On TeamCity agents, check if the environment variables are set.
if (-not $env:GIT_USER_EMAIL -or -not $env:GIT_USER_NAME)
{
Write-Error "On TeamCity agents, the GIT_USER_EMAIL and GIT_USER_NAME environment variables must be set."
exit 1
}
}
else
{
# On developer machines, use the current git user.
$env:GIT_USER_EMAIL = git config --global user.email
$env:GIT_USER_NAME = git config --global user.name
}
New-EnvHashtable -EnvironmentVariableList $EnvironmentVariables
}
}
# Get the source directory name from $PSScriptRoot (script location)
$SourceDirName = $PSScriptRoot
# Start timing the entire process except cleaning
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
# Ensure docker context directory exists (not needed for registry images)
if (-not $RegistryImage -and -not (Test-Path $dockerContextDirectory))
{
New-Item -ItemType Directory -Path $dockerContextDirectory -Force | Out-Null
}
# Container user profile (matches actual user in container)
$containerUserProfile = if ($IsUnix)
{
"/root"
}
else
{
"C:\Users\ContainerAdministrator"
}
# Initialize arrays for special mounts (those with different host/container paths)
$VolumeMappings = @()
$MountPoints = @()
$GitDirectories = @()
# Prepare volume mappings using the dictionary
Add-VolumeMount -Path $SourceDirName -Writable
# Define static Git system directory for mapping. This used by Teamcity as an LFS parent repo.
$gitSystemDir = "$BuildAgentPath\system\git"
if (Test-Path $gitSystemDir)
{
Add-VolumeMount -Path $gitSystemDir
}
# Mount the host NuGet cache in the container.
if (-not $NoNuGetCache)
{
# Use NUGET_PACKAGES from environment or default to user profile
$nugetCacheDir = $env:NUGET_PACKAGES
if ( [string]::IsNullOrEmpty($nugetCacheDir))
{
if ($IsUnix)
{
$nugetCacheDir = Join-Path $env:HOME ".nuget/packages"
}
else
{
$nugetCacheDir = Join-Path $env:USERPROFILE ".nuget\packages"
}
}
Write-Host "NuGet cache directory: $nugetCacheDir" -ForegroundColor Cyan
if (-not (Test-Path $nugetCacheDir))
{
Write-Host "Creating NuGet cache directory on host: $nugetCacheDir"
New-Item -ItemType Directory -Force -Path $nugetCacheDir | Out-Null
}
# Mount to the same path in the container (will be transformed by Get-ContainerPath later)
Add-VolumeMount -Path $nugetCacheDir -Writable
}
# Mount PostSharp.Engineering data directory (for version counters)
$hostEngineeringDataDir = if ($IsUnix)
{
Join-Path $env:HOME ".local/share/PostSharp.Engineering"
}
else
{
Join-Path $env:LOCALAPPDATA "PostSharp.Engineering"
}
if (-not (Test-Path $hostEngineeringDataDir))
{
New-Item -ItemType Directory -Force -Path $hostEngineeringDataDir | Out-Null
}
$containerEngineeringDataDir = if ($IsUnix)
{
Join-Path $containerUserProfile ".local/share/PostSharp.Engineering"
}
else
{
Join-Path $containerUserProfile "AppData\Local\PostSharp.Engineering"
}
$VolumeMappings += "${hostEngineeringDataDir}:${containerEngineeringDataDir}"
$MountPoints += $containerEngineeringDataDir
# Mount VS Remote Debugger
if ($StartVsmon)
{
if (-not $env:DevEnvDir)
{
Write-Host "Environment variable 'DevEnvDir' is not defined." -ForegroundColor Red
exit 1
}
$remoteDebuggerHostDir = "$( $env:DevEnvDir )Remote Debugger\x64"
if (-not (Test-Path $remoteDebuggerHostDir))
{
Write-Host "Directory '$remoteDebuggerHostDir' does not exist." -ForegroundColor Red
exit 1
}
$remoteDebuggerContainerDir = "C:\msvsmon"
$VolumeMappings += "${remoteDebuggerHostDir}:${remoteDebuggerContainerDir}:ro"
$MountPoints += $remoteDebuggerContainerDir
}
# Discover symbolic links in source-dependencies and add their targets to mount points
$sourceDependenciesDir = Join-Path $SourceDirName "source-dependencies"
if (Test-Path $sourceDependenciesDir)
{
$symbolicLinks = Get-ChildItem -Path $sourceDependenciesDir -Force | Where-Object { $_.LinkType -eq 'SymbolicLink' }
foreach ($link in $symbolicLinks)
{
$targetPath = $link.Target
if (-not [string]::IsNullOrEmpty($targetPath) -and (Test-Path $targetPath))
{
Write-Host "Found symbolic link '$( $link.Name )' -> '$targetPath'" -ForegroundColor Cyan
Add-VolumeMount -Path $targetPath
}
else
{
Write-Host "Warning: Symbolic link '$( $link.Name )' target '$targetPath' does not exist or is invalid" -ForegroundColor Yellow
}
}
$sourceDirectories = Get-ChildItem -Path $sourceDependenciesDir -Force | Where-Object { $_.LinkType -eq $null }
foreach ($sourceDirectory in $sourceDirectories)
{
Write-Host "Mounting source-dependencies directory: $( $sourceDirectory.FullName )" -ForegroundColor Cyan
$GitDirectories += $sourceDirectory.FullName
}
}
# Mount sibling directories from the product family (parent directory)
# Only if parent is a recognized product family (PostSharp* or Metalama*)
$parentDir = Split-Path $SourceDirName -Parent
$parentDirName = Split-Path $parentDir -Leaf
if ($parentDir -and (Test-Path $parentDir) -and ($parentDirName -like "PostSharp*" -or $parentDirName -like "Metalama*"))
{
Write-Host "Detected product family directory: $parentDirName" -ForegroundColor Cyan
$siblingDirs = Get-ChildItem -Path $parentDir -Directory -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -ne $SourceDirName }
foreach ($sibling in $siblingDirs)
{
$siblingPath = $sibling.FullName
Write-Host "Mounting product family sibling: $siblingPath" -ForegroundColor Cyan
Add-VolumeMount -Path $siblingPath
}
}
# Mount PostSharp.Engineering.* directories from grandparent
# This provides access to engineering tools and related repos
$grandparentDir = Split-Path $parentDir -Parent
if ($grandparentDir -and (Test-Path $grandparentDir))
{
$engineeringDirs = Get-ChildItem -Path $grandparentDir -Directory -Filter "PostSharp.Engineering*" -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -ne $SourceDirName }
foreach ($engDir in $engineeringDirs)
{
$engDirPath = $engDir.FullName
Write-Host "Mounting engineering repo: $engDirPath" -ForegroundColor Cyan
Add-VolumeMount -Path $engDirPath
}
}
# Process -Mount parameter for additional directory mounts
if ($Mount -and $Mount.Count -gt 0)
{
foreach ($mountSpec in $Mount)
{
# Check if writable (ends with :w)
$isWritable = $false
$pattern = $mountSpec
if ($mountSpec -match ':w$')
{
$isWritable = $true
$pattern = $mountSpec -replace ':w$', ''
}
# Trim trailing slashes
$pattern = $pattern.TrimEnd('\', '/')
# Check if pattern contains glob characters
if ($pattern -match '\*')
{
# Expand glob pattern to match directories only
# Get the base directory (everything before the first glob)
$patternParts = $pattern -split '[\\/]'
$basePathParts = @()
$globStartIndex = -1
for ($i = 0; $i -lt $patternParts.Count; $i++)
{
if ($patternParts[$i] -match '\*')
{
$globStartIndex = $i
break
}
$basePathParts += $patternParts[$i]
}
if ($basePathParts.Count -gt 0)
{
$basePath = $basePathParts -join [System.IO.Path]::DirectorySeparatorChar
}
else
{
$basePath = "."
}
if (Test-Path $basePath)
{
# Determine if recursive search is needed (pattern contains **)
$isRecursive = $pattern -match '\*\*'
# Build the glob pattern for the part after the base path
$globPart = ($patternParts[$globStartIndex..($patternParts.Count - 1)]) -join [System.IO.Path]::DirectorySeparatorChar
# Get matching directories
$matchingDirs = @()
if ($isRecursive)
{
# For ** patterns, recurse and convert ** to * for -like matching
# Replace ** with a regex-friendly pattern for matching
$likePattern = $pattern -replace '\*\*', '*'
$matchingDirs = Get-ChildItem -Path $basePath -Directory -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -like $likePattern }
}
else
{
# For single * patterns, use direct matching without recursion
$matchingDirs = Get-ChildItem -Path $basePath -Directory -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -like $pattern }
}