-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBuild.ps1
More file actions
990 lines (875 loc) · 41.2 KB
/
Copy pathBuild.ps1
File metadata and controls
990 lines (875 loc) · 41.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
<#
.SYNOPSIS
DeepPurge Build Script v0.9.3
Compiles the project into single portable .exe files (GUI + CLI)
.DESCRIPTION
Requires the pinned .NET 10.0.302 SDK, then builds self-contained
single-file portable executables. No Visual Studio required.
.NOTES
Run from the DeepPurge project root directory.
Output: build\DeepPurge.exe (GUI) + build\DeepPurgeCli.exe (CLI)
#>
param(
[ValidateSet("Release","Debug")]
[string]$Configuration = "Release",
[switch]$SkipClean,
[switch]$OpenOutput,
# Run the xUnit suite after build, before publish. Release builds
# run it by default; dev-inner-loop builds can opt out explicitly.
[switch]$Test,
[switch]$SkipTests,
# ── Signing (optional) ──────────────────────────────────────────
# Pass -Sign to Authenticode-sign the two published exes. Certificate
# source is auto-detected in this order:
# 1. -CertPath <.pfx> + -CertPassword (or $env:DEEPPURGE_CERT_PASSWORD)
# 2. $env:DEEPPURGE_CERT_PATH + $env:DEEPPURGE_CERT_PASSWORD
# 3. -CertThumbprint <SHA1> pointing at a cert in CurrentUser\My
# Only used for official releases — day-to-day dev builds skip signing.
[switch]$Sign,
[string]$CertPath,
[securestring]$CertPassword,
[string]$CertThumbprint,
[string]$TimestampUrl = "http://timestamp.digicert.com",
[switch]$ValidateRelease,
[switch]$ValidateReleaseOnly,
[switch]$AuditDependenciesOnly,
[string]$ReleaseChecksumsPath
)
$ErrorActionPreference = "Continue"
$ProjectRoot = $PSScriptRoot
if ([string]::IsNullOrEmpty($ProjectRoot)) { $ProjectRoot = Get-Location }
$BuildDir = Join-Path $ProjectRoot "build"
$SolutionFile = Join-Path $ProjectRoot "DeepPurge.sln"
$AppProject = Join-Path $ProjectRoot "src\DeepPurge.App\DeepPurge.App.csproj"
$CliProject = Join-Path $ProjectRoot "src\DeepPurge.Cli\DeepPurge.Cli.csproj"
$CoreProject = Join-Path $ProjectRoot "src\DeepPurge.Core\DeepPurge.Core.csproj"
$TestsProject = Join-Path $ProjectRoot "tests\DeepPurge.Tests\DeepPurge.Tests.csproj"
Write-Host ""
Write-Host " ============================================" -ForegroundColor Cyan
Write-Host " DeepPurge Build Script v0.9.3" -ForegroundColor Cyan
Write-Host " ============================================" -ForegroundColor Cyan
Write-Host ""
# ── Authenticode signing helper ───────────────────────────────
# Locates signtool.exe and a certificate (in priority order:
# 1. -CertPath + -CertPassword
# 2. env DEEPPURGE_CERT_PATH + DEEPPURGE_CERT_PASSWORD
# 3. -CertThumbprint in CurrentUser\My
# ) then signs each exe with SHA256 + RFC 3161 timestamping. Throws
# on failure so the caller can decide whether to ship unsigned.
function Get-SignTool {
$candidates = @(
(Get-Command signtool.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source -ErrorAction SilentlyContinue)
)
$sdkRoot = "${env:ProgramFiles(x86)}\Windows Kits\10\bin"
if (Test-Path $sdkRoot) {
# Prefer the newest SDK build. signtool lives under <version>\<arch>\signtool.exe.
Get-ChildItem $sdkRoot -Directory | Sort-Object Name -Descending | ForEach-Object {
$candidates += (Join-Path $_.FullName "x64\signtool.exe")
$candidates += (Join-Path $_.FullName "x86\signtool.exe")
}
}
foreach ($c in $candidates) {
if ($c -and (Test-Path $c)) { return $c }
}
throw "signtool.exe not found. Install the Windows 10/11 SDK."
}
function Invoke-Signing {
param([string[]]$ExePaths)
$signtool = Get-SignTool
# Resolve cert source.
$pfxPath = $CertPath
if ([string]::IsNullOrEmpty($pfxPath) -and -not [string]::IsNullOrEmpty($env:DEEPPURGE_CERT_PATH)) {
$pfxPath = $env:DEEPPURGE_CERT_PATH
}
$pfxSecure = $CertPassword
if (-not $pfxSecure -and -not [string]::IsNullOrEmpty($env:DEEPPURGE_CERT_PASSWORD)) {
$pfxSecure = ConvertTo-SecureString -String $env:DEEPPURGE_CERT_PASSWORD -AsPlainText -Force
}
foreach ($exe in $ExePaths) {
if (-not (Test-Path $exe)) { continue }
if (-not [string]::IsNullOrEmpty($pfxPath) -and (Test-Path $pfxPath)) {
# PFX-file path. signtool accepts the password as plaintext on its
# command line — we decode from SecureString only right here.
$pfxPlain = ''
if ($pfxSecure) {
$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($pfxSecure)
try { $pfxPlain = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) }
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) }
}
$signArgs = @("sign", "/fd", "SHA256", "/tr", $TimestampUrl, "/td", "SHA256",
"/f", $pfxPath)
if ($pfxPlain) { $signArgs += @("/p", $pfxPlain) }
$signArgs += $exe
& $signtool @signArgs
}
elseif (-not [string]::IsNullOrEmpty($CertThumbprint)) {
& $signtool sign /fd SHA256 /tr $TimestampUrl /td SHA256 /sha1 $CertThumbprint $exe
}
else {
throw "No cert source: pass -CertPath + -CertPassword, -CertThumbprint, or set DEEPPURGE_CERT_PATH + DEEPPURGE_CERT_PASSWORD."
}
if ($LASTEXITCODE -ne 0) { throw "signtool failed on $exe (exit $LASTEXITCODE)" }
# Verify the freshly-applied signature.
& $signtool verify /pa /q $exe
if ($LASTEXITCODE -ne 0) { throw "signature verify failed on $exe" }
}
}
# ── Verify the pinned .NET 10 SDK ──────────────────────────────
function Add-ReleaseValidationFailure {
param(
[Parameter(Mandatory=$true)][string]$Key,
[Parameter(Mandatory=$true)][string]$Message
)
if ($null -eq $script:ReleaseValidationFailures) {
$script:ReleaseValidationFailures = [System.Collections.Generic.List[string]]::new()
}
$script:ReleaseValidationFailures.Add("${Key}: $Message") | Out-Null
}
function Get-CsprojVersion {
param(
[Parameter(Mandatory=$true)][string]$Path,
[Parameter(Mandatory=$true)][string]$Key
)
if (-not (Test-Path $Path)) {
Add-ReleaseValidationFailure $Key "file is missing"
return $null
}
try {
[xml]$projectXml = Get-Content $Path -Raw
$version = $projectXml.Project.PropertyGroup |
ForEach-Object { $_.Version } |
Where-Object { -not [string]::IsNullOrWhiteSpace($_) } |
Select-Object -First 1
if ([string]::IsNullOrWhiteSpace($version)) {
Add-ReleaseValidationFailure $Key "Version is missing"
return $null
}
return $version.Trim()
} catch {
Add-ReleaseValidationFailure $Key "could not parse project XML: $_"
return $null
}
}
function Assert-ReleaseValue {
param(
[Parameter(Mandatory=$true)][string]$Key,
[AllowNull()][string]$Actual,
[Parameter(Mandatory=$true)][string]$Expected
)
if ($Actual -ne $Expected) {
Add-ReleaseValidationFailure $Key "expected '$Expected', found '$Actual'"
}
}
function Assert-NoReleasePlaceholders {
param(
[Parameter(Mandatory=$true)][string]$Path,
[Parameter(Mandatory=$true)][string]$Content
)
$lines = $Content -split "\r?\n"
for ($i = 0; $i -lt $lines.Count; $i++) {
if ($lines[$i] -match "PLACEHOLDER|REPLACE_WITH|<<") {
Add-ReleaseValidationFailure "${Path}:$($i + 1)" "release placeholder remains"
}
}
}
function Get-ReleaseChecksumPath {
if (-not [string]::IsNullOrWhiteSpace($ReleaseChecksumsPath)) {
$resolved = Resolve-Path $ReleaseChecksumsPath -ErrorAction SilentlyContinue
if ($resolved) { return $resolved.Path }
return $ReleaseChecksumsPath
}
return (Join-Path $BuildDir "SHA256SUMS.txt")
}
function Read-ReleaseChecksums {
param([Parameter(Mandatory=$true)][string]$Path)
$checksums = @{}
if ([string]::IsNullOrWhiteSpace($Path) -or -not (Test-Path $Path)) {
Add-ReleaseValidationFailure "SHA256SUMS.txt" "checksum file is missing at '$Path'"
return $checksums
}
$lineNumber = 0
foreach ($line in Get-Content $Path) {
$lineNumber++
if ([string]::IsNullOrWhiteSpace($line)) { continue }
if ($line -notmatch "^(?<hash>[A-Fa-f0-9]{64})\s+\*?(?<name>[^\\/:*?`"<>|\r\n]+)$") {
Add-ReleaseValidationFailure "${Path}:$lineNumber" "expected '<64-char sha256> <asset name>'"
continue
}
$checksums[$matches.name.Trim()] = $matches.hash.ToUpperInvariant()
}
if ($checksums.Count -eq 0) {
Add-ReleaseValidationFailure "SHA256SUMS.txt" "checksum file contains no assets"
}
return $checksums
}
function Get-FileSha256Hex {
param([Parameter(Mandatory=$true)][string]$Path)
$stream = [IO.File]::OpenRead($Path)
try {
$sha256 = [Security.Cryptography.SHA256]::Create()
try {
return ([BitConverter]::ToString($sha256.ComputeHash($stream))).Replace("-", "").ToUpperInvariant()
} finally {
$sha256.Dispose()
}
} finally {
$stream.Dispose()
}
}
function Write-Sha256Sums {
param([Parameter(Mandatory=$true)][string[]]$ArtifactPaths)
$lines = New-Object System.Collections.Generic.List[string]
foreach ($artifact in $ArtifactPaths) {
if (-not (Test-Path $artifact)) {
Add-ReleaseValidationFailure $artifact "release artifact is missing"
continue
}
$hash = Get-FileSha256Hex $artifact
$name = Split-Path $artifact -Leaf
$lines.Add("$hash $name") | Out-Null
}
$checksumPath = Join-Path $BuildDir "SHA256SUMS.txt"
Set-Content -Path $checksumPath -Value $lines -Encoding ASCII
Write-Host " [OK] SHA256SUMS.txt generated" -ForegroundColor Green
return $checksumPath
}
function Get-ReleaseAssetName {
param([Parameter(Mandatory=$true)][string]$Url)
$cleanUrl = ($Url -split "#", 2)[0]
try {
return [Uri]::UnescapeDataString(([Uri]$cleanUrl).Segments[-1])
} catch {
return [IO.Path]::GetFileName($cleanUrl)
}
}
function Assert-ReleaseAsset {
param(
[Parameter(Mandatory=$true)][string]$Key,
[Parameter(Mandatory=$true)][string]$Url,
[Parameter(Mandatory=$true)][string]$ManifestHash,
[Parameter(Mandatory=$true)][hashtable]$Checksums,
[Parameter(Mandatory=$true)][string]$Version
)
$expectedPrefix = "https://github.com/SysAdminDoc/DeepPurge/releases/download/v$Version/"
if (-not $Url.StartsWith($expectedPrefix, [StringComparison]::OrdinalIgnoreCase)) {
Add-ReleaseValidationFailure $Key "release URL must start with '$expectedPrefix'"
}
$assetName = Get-ReleaseAssetName $Url
if ([string]::IsNullOrWhiteSpace($assetName)) {
Add-ReleaseValidationFailure $Key "could not resolve asset name from URL"
return
}
if (-not $Checksums.ContainsKey($assetName)) {
Add-ReleaseValidationFailure $Key "asset '$assetName' is missing from SHA256SUMS.txt"
return
}
$expectedHash = $Checksums[$assetName]
if ($ManifestHash.ToUpperInvariant() -ne $expectedHash) {
Add-ReleaseValidationFailure $Key "hash for '$assetName' must be '$expectedHash'"
}
}
function Assert-LocalArtifactsMatchChecksums {
param([Parameter(Mandatory=$true)][hashtable]$Checksums)
foreach ($entry in $Checksums.GetEnumerator()) {
$artifactPath = Join-Path $BuildDir $entry.Key
if (-not (Test-Path $artifactPath)) {
Add-ReleaseValidationFailure "build\$($entry.Key)" "checksum entry has no matching local artifact"
continue
}
$actual = Get-FileSha256Hex $artifactPath
if ($actual -ne $entry.Value) {
Add-ReleaseValidationFailure "build\$($entry.Key)" "SHA256SUMS.txt has '$($entry.Value)', local file is '$actual'"
}
}
}
function Invoke-DocumentationContractValidation {
Write-Host ""
Write-Host " [*] Validating release documentation and capability routes..." -ForegroundColor Yellow
$docs = @(
(Join-Path $ProjectRoot "README.md"),
(Join-Path $ProjectRoot "ARCHITECTURE.md"),
(Join-Path $ProjectRoot "CONTRIBUTING.md"),
(Join-Path $ProjectRoot "packaging\README.md")
)
$docContents = @{}
foreach ($docPath in $docs) {
if (-not (Test-Path $docPath)) {
Add-ReleaseValidationFailure "documentation:$([IO.Path]::GetFileName($docPath))" "file is missing"
continue
}
$docContents[$docPath] = Get-Content $docPath -Raw
}
$testOutput = (& $script:DotNetExe test $TestsProject -c $Configuration --no-build --no-restore --list-tests --nologo --verbosity minimal 2>&1 | Out-String)
$testExitCode = $LASTEXITCODE
if ($testExitCode -ne 0) {
Add-ReleaseValidationFailure "documentation:test-count" "could not enumerate tests (exit $testExitCode)"
} else {
$testCount = ([regex]::Matches($testOutput, '(?m)^[ \t]+DeepPurge\.Tests\.[^\r\n]+')).Count
if ($testCount -le 0) {
Add-ReleaseValidationFailure "documentation:test-count" "test enumeration returned no DeepPurge.Tests entries"
} else {
foreach ($docPath in $docs | Where-Object { $_ -notlike "*packaging\README.md" }) {
$docText = $docContents[$docPath]
$match = [regex]::Match($docText, '(?im)\b(?:all\s+)?(?<count>\d+)\s+(?:tests|cases)\b')
if (-not $match.Success) {
Add-ReleaseValidationFailure "documentation:$([IO.Path]::GetFileName($docPath)):test-count" "documented test count is missing"
continue
}
if ([int]$match.Groups["count"].Value -ne $testCount) {
Add-ReleaseValidationFailure "documentation:$([IO.Path]::GetFileName($docPath)):test-count" "expected $testCount tests, found $($match.Groups["count"].Value)"
}
}
}
}
foreach ($docPath in $docContents.Keys) {
$docName = [IO.Path]::GetFileName($docPath)
$docText = $docContents[$docPath]
if ($docText -match 'Build\.ps1\s+-Test\s+-Sign') {
Add-ReleaseValidationFailure "documentation:${docName}:command" "stale '-Test -Sign' release command; Release builds run tests by default"
}
if ($docText -notmatch 'Build\.ps1\s+-Sign') {
Add-ReleaseValidationFailure "documentation:${docName}:command" "signed release command is missing"
}
}
$appManifest = Get-Content (Join-Path $ProjectRoot "src\DeepPurge.App\app.manifest") -Raw
$cliManifest = Get-Content (Join-Path $ProjectRoot "src\DeepPurge.Cli\app.manifest") -Raw
if ($appManifest -notmatch 'requestedExecutionLevel\s+level="requireAdministrator"') {
Add-ReleaseValidationFailure "documentation:privilege" "GUI manifest must requireAdministrator"
}
if ($cliManifest -notmatch 'requestedExecutionLevel\s+level="asInvoker"') {
Add-ReleaseValidationFailure "documentation:privilege" "CLI manifest must be asInvoker"
}
$readmeText = $docContents[(Join-Path $ProjectRoot "README.md")]
if ($readmeText -notmatch 'requireAdministrator' -or $readmeText -notmatch 'asInvoker') {
Add-ReleaseValidationFailure "documentation:privilege" "README must document GUI requireAdministrator and CLI asInvoker posture"
}
$xamlPath = Join-Path $ProjectRoot "src\DeepPurge.App\Views\MainWindow.xaml"
$codeBehindPath = Join-Path $ProjectRoot "src\DeepPurge.App\Views\MainWindow.xaml.cs"
$cliPath = Join-Path $ProjectRoot "src\DeepPurge.Cli\Program.cs"
$xaml = Get-Content $xamlPath -Raw
$codeBehind = Get-Content $codeBehindPath -Raw
$cli = Get-Content $cliPath -Raw
foreach ($contract in @(
@{ Claim = "Health Dashboard"; Tag = "Health"; Element = "panelHealth"; Cli = "health" },
@{ Claim = "System Slimming"; Tag = "Slimming"; Element = "panelSlimming"; Cli = "slim" },
@{ Claim = "Expert / Safe mode"; Tag = "Settings"; Element = "panelSettings"; Cli = "settings" }
)) {
if ($readmeText -notmatch [regex]::Escape($contract.Claim)) {
Add-ReleaseValidationFailure "documentation:capability:$($contract.Claim)" "README claim is missing"
}
if ($xaml -notmatch [regex]::Escape(('Tag="' + $contract.Tag + '"'))) {
Add-ReleaseValidationFailure "documentation:capability:$($contract.Claim)" "GUI navigation tag is missing"
}
if ($xaml -notmatch [regex]::Escape(('x:Name="' + $contract.Element + '"'))) {
Add-ReleaseValidationFailure "documentation:capability:$($contract.Claim)" "GUI panel is missing"
}
if ($codeBehind -notmatch [regex]::Escape(('case "' + $contract.Tag + '"'))) {
Add-ReleaseValidationFailure "documentation:capability:$($contract.Claim)" "GUI navigation case is missing"
}
if ($cli -notmatch [regex]::Escape(('"' + $contract.Cli + '"'))) {
Add-ReleaseValidationFailure "documentation:capability:$($contract.Claim)" "CLI route is missing"
}
}
if ($xaml -notmatch 'Tag="Hunter"[^>]*Visibility="[^"]*ExpertMode' -and
$xaml -notmatch 'ExpertMode[^"]*BoolToVis') {
Add-ReleaseValidationFailure "documentation:capability:Expert / Safe mode" "Expert mode does not gate advanced navigation"
}
if ($cli -notmatch 'health\s+\[--json\]' -or $cli -notmatch 'slim\s+\[--delete\]') {
Add-ReleaseValidationFailure "documentation:capability:CLI help" "health/slim CLI help routes are missing"
}
return $true
}
function Invoke-ReleaseReadinessValidation {
$script:ReleaseValidationFailures = [System.Collections.Generic.List[string]]::new()
Write-Host ""
Write-Host " [*] Validating release and Scoop manifest..." -ForegroundColor Yellow
$appVersion = Get-CsprojVersion $AppProject "src/DeepPurge.App/DeepPurge.App.csproj:Version"
$coreVersion = Get-CsprojVersion $CoreProject "src/DeepPurge.Core/DeepPurge.Core.csproj:Version"
$cliVersion = Get-CsprojVersion $CliProject "src/DeepPurge.Cli/DeepPurge.Cli.csproj:Version"
if (-not [string]::IsNullOrWhiteSpace($appVersion)) {
Assert-ReleaseValue "src/DeepPurge.Core/DeepPurge.Core.csproj:Version" $coreVersion $appVersion
Assert-ReleaseValue "src/DeepPurge.Cli/DeepPurge.Cli.csproj:Version" $cliVersion $appVersion
}
$readmePath = Join-Path $ProjectRoot "README.md"
$readme = if (Test-Path $readmePath) { Get-Content $readmePath -Raw } else { "" }
if ($readme -match "version-v(?<version>\d+\.\d+\.\d+)") {
Assert-ReleaseValue "README.md:version badge" $matches.version $appVersion
} else {
Add-ReleaseValidationFailure "README.md:version badge" "version badge is missing"
}
if ($readme -match "(?m)^# DeepPurge v(?<version>\d+\.\d+\.\d+)") {
Assert-ReleaseValue "README.md:heading version" $matches.version $appVersion
} else {
Add-ReleaseValidationFailure "README.md:heading version" "version heading is missing"
}
$changelogPath = Join-Path $ProjectRoot "CHANGELOG.md"
$changelog = if (Test-Path $changelogPath) { Get-Content $changelogPath -Raw } else { "" }
if ($changelog -notmatch ("(?m)^## \[v?" + [regex]::Escape($appVersion) + "\]")) {
Add-ReleaseValidationFailure "CHANGELOG.md:version heading" "current version heading is missing"
}
$buildScript = Get-Content (Join-Path $ProjectRoot "Build.ps1") -Raw
if ($buildScript -match "Build Script v(?<version>\d+\.\d+\.\d+)") {
Assert-ReleaseValue "Build.ps1:Build Script version" $matches.version $appVersion
} else {
Add-ReleaseValidationFailure "Build.ps1:Build Script version" "script version banner is missing"
}
$buildBatPath = Join-Path $ProjectRoot "BUILD.bat"
$buildBat = if (Test-Path $buildBatPath) { Get-Content $buildBatPath -Raw } else { "" }
if ($buildBat -match "Builder v(?<version>\d+\.\d+\.\d+)") {
Assert-ReleaseValue "BUILD.bat:title version" $matches.version $appVersion
} else {
Add-ReleaseValidationFailure "BUILD.bat:title version" "title version is missing"
}
$checksumPath = Get-ReleaseChecksumPath
$checksums = Read-ReleaseChecksums $checksumPath
if ([string]::IsNullOrWhiteSpace($ReleaseChecksumsPath)) {
Assert-LocalArtifactsMatchChecksums $checksums
}
$scoopPath = Join-Path $ProjectRoot "packaging\scoop\deeppurge.json"
if (Test-Path $scoopPath) {
$scoopContent = Get-Content $scoopPath -Raw
Assert-NoReleasePlaceholders "packaging/scoop/deeppurge.json" $scoopContent
try {
$scoop = $scoopContent | ConvertFrom-Json
Assert-ReleaseValue "packaging/scoop/deeppurge.json:version" $scoop.version $appVersion
$expectedHashUrl = 'https://github.com/SysAdminDoc/DeepPurge/releases/download/v$version/SHA256SUMS.txt'
Assert-ReleaseValue "packaging/scoop/deeppurge.json:autoupdate.hash.url" $scoop.autoupdate.hash.url $expectedHashUrl
foreach ($arch in $scoop.architecture.PSObject.Properties) {
$urls = @($arch.Value.url)
$hashes = @($arch.Value.hash)
if ($urls.Count -ne $hashes.Count) {
Add-ReleaseValidationFailure "packaging/scoop/deeppurge.json:architecture.$($arch.Name)" "url count ($($urls.Count)) does not match hash count ($($hashes.Count))"
continue
}
for ($i = 0; $i -lt $urls.Count; $i++) {
Assert-ReleaseAsset "packaging/scoop/deeppurge.json:architecture.$($arch.Name).hash[$i]" $urls[$i] $hashes[$i] $checksums $appVersion
}
}
} catch {
Add-ReleaseValidationFailure "packaging/scoop/deeppurge.json" "could not parse JSON: $_"
}
} else {
Add-ReleaseValidationFailure "packaging/scoop/deeppurge.json" "file is missing"
}
if (-not (Invoke-DependencyAuditValidation)) {
Add-ReleaseValidationFailure "NuGet dependency audit" "project-level dependency audit failed"
}
Invoke-DocumentationContractValidation | Out-Null
if ($script:ReleaseValidationFailures.Count -gt 0) {
Write-Host " [ERROR] Release readiness validation failed:" -ForegroundColor Red
foreach ($failure in $script:ReleaseValidationFailures) {
Write-Host " - $failure" -ForegroundColor Red
}
return $false
}
Write-Host " [OK] Release readiness validation passed" -ForegroundColor Green
return $true
}
function Add-DependencyAuditFailure {
param(
[Parameter(Mandatory=$true)][string]$Key,
[Parameter(Mandatory=$true)][string]$Message
)
if ($null -eq $script:DependencyAuditFailures) {
$script:DependencyAuditFailures = [System.Collections.Generic.List[string]]::new()
}
$script:DependencyAuditFailures.Add("${Key}: $Message") | Out-Null
}
function Invoke-DependencyAuditCommand {
param(
[Parameter(Mandatory=$true)][string]$ProjectName,
[Parameter(Mandatory=$true)][string]$AuditName,
[Parameter(Mandatory=$true)][string[]]$Arguments,
[Parameter(Mandatory=$true)][string]$SuccessText,
[Parameter(Mandatory=$true)][string]$FailureMessage,
[switch]$AdvisoryOnly
)
$output = & $script:DotNetExe @Arguments 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
Add-DependencyAuditFailure "$ProjectName $AuditName" "command failed with exit $LASTEXITCODE`n$output"
return
}
if ($output -notmatch [regex]::Escape($SuccessText)) {
if ($AdvisoryOnly) {
Write-Host " [WARN] $ProjectName $AuditName advisory:`n$output" -ForegroundColor Yellow
return
}
Add-DependencyAuditFailure "$ProjectName $AuditName" "$FailureMessage`n$output"
}
}
function Invoke-DependencyAuditValidation {
$script:DependencyAuditFailures = [System.Collections.Generic.List[string]]::new()
Write-Host ""
Write-Host " [*] Auditing NuGet dependencies project-by-project..." -ForegroundColor Yellow
$projects = @(
@{ Name = "DeepPurge.Core"; Path = $CoreProject },
@{ Name = "DeepPurge.App"; Path = $AppProject },
@{ Name = "DeepPurge.Cli"; Path = $CliProject },
@{ Name = "DeepPurge.Tests"; Path = $TestsProject }
)
foreach ($project in $projects) {
if (-not (Test-Path $project.Path)) {
Add-DependencyAuditFailure $project.Name "project file is missing at '$($project.Path)'"
continue
}
Invoke-DependencyAuditCommand `
-ProjectName $project.Name `
-AuditName "outdated" `
-Arguments @("list", $project.Path, "package", "--outdated", "--no-restore") `
-SuccessText "has no updates" `
-FailureMessage "outdated packages found" `
-AdvisoryOnly
Invoke-DependencyAuditCommand `
-ProjectName $project.Name `
-AuditName "vulnerable" `
-Arguments @("list", $project.Path, "package", "--vulnerable", "--include-transitive", "--no-restore") `
-SuccessText "has no vulnerable packages" `
-FailureMessage "vulnerable packages found"
}
if ($script:DependencyAuditFailures.Count -gt 0) {
Write-Host " [ERROR] NuGet dependency audit failed:" -ForegroundColor Red
foreach ($failure in $script:DependencyAuditFailures) {
Write-Host " - $failure" -ForegroundColor Red
}
return $false
}
Write-Host " [OK] NuGet dependency audit passed" -ForegroundColor Green
return $true
}
function Invoke-BuildInputValidation {
$failures = [System.Collections.Generic.List[string]]::new()
$globalJsonPath = Join-Path $ProjectRoot "global.json"
$propsPath = Join-Path $ProjectRoot "Directory.Build.props"
$nugetPath = Join-Path $ProjectRoot "NuGet.Config"
if (-not (Test-Path $globalJsonPath)) {
$failures.Add("global.json is missing") | Out-Null
} else {
try {
$globalJson = Get-Content $globalJsonPath -Raw | ConvertFrom-Json
if ($globalJson.sdk.version -ne "10.0.302" -or
$globalJson.sdk.rollForward -ne "disable" -or
$globalJson.sdk.allowPrerelease -ne $false) {
$failures.Add("global.json must pin SDK 10.0.302 with rollForward=disable and allowPrerelease=false") | Out-Null
}
} catch {
$failures.Add("global.json could not be parsed: $_") | Out-Null
}
}
if (-not (Test-Path $propsPath) -or
(Get-Content $propsPath -Raw) -notmatch "<RestoreLockedMode>true</RestoreLockedMode>") {
$failures.Add("Directory.Build.props must enable RestoreLockedMode") | Out-Null
}
if (-not (Test-Path $nugetPath)) {
$failures.Add("NuGet.Config is missing") | Out-Null
}
foreach ($lockPath in @(
(Join-Path $ProjectRoot "src\DeepPurge.Core\packages.lock.json"),
(Join-Path $ProjectRoot "src\DeepPurge.App\packages.lock.json"),
(Join-Path $ProjectRoot "src\DeepPurge.Cli\packages.lock.json"),
(Join-Path $ProjectRoot "tests\DeepPurge.Tests\packages.lock.json"))) {
if (-not (Test-Path $lockPath)) { $failures.Add("package lock is missing: $lockPath") | Out-Null }
}
if ($failures.Count -gt 0) {
Write-Host " [ERROR] Build input validation failed:" -ForegroundColor Red
foreach ($failure in $failures) { Write-Host " - $failure" -ForegroundColor Red }
return $false
}
Write-Host " [OK] Pinned SDK, locked restore, source map, and lock files validated" -ForegroundColor Green
return $true
}
function Find-DotNet {
# Check common locations. global.json below this script pins the exact
# SDK feature band and disables roll-forward.
$candidates = @(
(Get-Command dotnet -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source -ErrorAction SilentlyContinue),
"$env:ProgramFiles\dotnet\dotnet.exe",
"$env:LOCALAPPDATA\dotnet\dotnet.exe",
"$env:USERPROFILE\.dotnet\dotnet.exe"
) | Where-Object { $_ -and (Test-Path $_ -ErrorAction SilentlyContinue) }
Push-Location $ProjectRoot
try {
foreach ($path in $candidates) {
try {
$output = (& $path --version 2>&1 | Out-String).Trim()
if ($output -eq "10.0.302") { return $path }
} catch { }
}
return $null
} finally {
Pop-Location
}
}
function Confirm-DotNetSDK {
$dotnetPath = Find-DotNet
if ($dotnetPath) {
try {
Push-Location $ProjectRoot
try {
$version = (& $dotnetPath --version 2>&1 | Out-String).Trim()
} finally {
Pop-Location
}
if ($version -eq "10.0.302") {
Write-Host " [OK] .NET SDK $version found at: $dotnetPath" -ForegroundColor Green
$script:DotNetExe = $dotnetPath
return
}
Write-Host " [ERROR] global.json requires .NET SDK 10.0.302, found '$version'." -ForegroundColor Red
} catch { }
}
Write-Host " [ERROR] Required .NET SDK 10.0.302 is not installed." -ForegroundColor Red
Write-Host " Install the pinned SDK from https://dotnet.microsoft.com/download/dotnet/10.0 and rerun this build." -ForegroundColor Yellow
exit 1
}
$script:DotNetExe = "dotnet"
Confirm-DotNetSDK
# Ensure DOTNET_ROOT is set for the SDK to find its runtime packs
$dotnetDir = Split-Path $script:DotNetExe -Parent
$env:DOTNET_ROOT = $dotnetDir
$env:PATH = "$dotnetDir;$env:PATH"
Write-Host " [*] DOTNET_ROOT = $dotnetDir" -ForegroundColor Gray
Write-Host ""
# ── Validate project files exist ──────────────────────────────
if (-not (Test-Path $SolutionFile)) {
Write-Host " [ERROR] Solution file not found: $SolutionFile" -ForegroundColor Red
Write-Host " Make sure you're running this from the DeepPurge root folder." -ForegroundColor Yellow
Write-Host ""
Read-Host " Press Enter to exit"
exit 1
}
if (-not (Test-Path $AppProject)) {
Write-Host " [ERROR] App project not found: $AppProject" -ForegroundColor Red
Read-Host " Press Enter to exit"
exit 1
}
if (-not (Test-Path $CliProject)) {
Write-Host " [ERROR] CLI project not found: $CliProject" -ForegroundColor Red
Read-Host " Press Enter to exit"
exit 1
}
if (-not (Test-Path $CoreProject)) {
Write-Host " [ERROR] Core project not found: $CoreProject" -ForegroundColor Red
Read-Host " Press Enter to exit"
exit 1
}
if (-not (Invoke-BuildInputValidation)) { exit 1 }
if ($ValidateReleaseOnly) {
if (-not (Invoke-ReleaseReadinessValidation)) { exit 1 }
exit 0
}
if ($AuditDependenciesOnly) {
if (-not (Invoke-DependencyAuditValidation)) { exit 1 }
exit 0
}
# ── Clean ──────────────────────────────────────────────────────
if (-not $SkipClean) {
Write-Host " [*] Cleaning previous build artifacts..." -ForegroundColor Yellow
if (Test-Path $BuildDir) { Remove-Item $BuildDir -Recurse -Force -ErrorAction SilentlyContinue }
# Aggressively clean ALL bin/obj directories under src/
$srcDir = Join-Path $ProjectRoot "src"
if (Test-Path $srcDir) {
Get-ChildItem -Path $srcDir -Recurse -Directory -ErrorAction SilentlyContinue |
Where-Object { $_.Name -eq 'bin' -or $_.Name -eq 'obj' } |
ForEach-Object {
Write-Host " Removing $($_.FullName)" -ForegroundColor DarkGray
Remove-Item $_.FullName -Recurse -Force -ErrorAction SilentlyContinue
}
}
# Also run dotnet clean to clear MSBuild caches
try {
& $script:DotNetExe clean $SolutionFile --nologo 2>&1 | Out-Null
} catch { }
Write-Host " [OK] Clean complete" -ForegroundColor Green
}
New-Item -ItemType Directory -Path $BuildDir -Force | Out-Null
# ── Verify project files ──────────────────────────────────────
Write-Host " [*] Verifying project configuration..." -ForegroundColor Yellow
$appCsproj = Join-Path (Join-Path (Join-Path $ProjectRoot "src") "DeepPurge.App") "DeepPurge.App.csproj"
if (Test-Path $appCsproj) {
$csprojContent = Get-Content $appCsproj -Raw
if ($csprojContent -match "UseWindowsForms") {
Write-Host " [ERROR] App.csproj contains UseWindowsForms - this causes type ambiguity!" -ForegroundColor Red
Write-Host " Please re-extract from the latest archive to a CLEAN folder." -ForegroundColor Red
Read-Host " Press Enter to exit"
exit 1
}
Write-Host " [OK] Project files verified" -ForegroundColor Green
}
# ── Restore ────────────────────────────────────────────────────
Write-Host " [*] Restoring NuGet packages..." -ForegroundColor Yellow
$nugetConfig = Join-Path $ProjectRoot "NuGet.Config"
$restoreArgs = @("restore", $SolutionFile, "--nologo", "--locked-mode", "--ignore-failed-sources", "--runtime", "win-x64", "--source", "https://api.nuget.org/v3/index.json")
if (Test-Path $nugetConfig) { $restoreArgs += @("--configfile", $nugetConfig) }
$restoreOutput = & $script:DotNetExe @restoreArgs 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
Write-Host " [ERROR] Restore failed:" -ForegroundColor Red
Write-Host $restoreOutput -ForegroundColor Gray
Read-Host " Press Enter to exit"
exit 1
}
Write-Host " [OK] Packages restored" -ForegroundColor Green
if ($Configuration -eq "Release") {
if (-not (Invoke-DependencyAuditValidation)) { exit 1 }
}
# -- Tests (required for Release unless explicitly skipped) ----
$runTests = $Test -or ($Configuration -eq "Release" -and -not $SkipTests)
if ($runTests) {
Write-Host ""
Write-Host " [*] Running test suite..." -ForegroundColor Yellow
$testProject = Join-Path $ProjectRoot "tests\DeepPurge.Tests\DeepPurge.Tests.csproj"
if (-not (Test-Path $testProject)) {
Write-Host " [!] Test project missing at $testProject - skipping." -ForegroundColor Yellow
} else {
& $script:DotNetExe test $testProject -c $Configuration --nologo --no-restore --verbosity minimal
if ($LASTEXITCODE -ne 0) {
Write-Host " [ERROR] Tests failed - refusing to publish." -ForegroundColor Red
Read-Host " Press Enter to exit"
exit 1
}
Write-Host " [OK] All tests passed" -ForegroundColor Green
}
}
# ── Build (Single-File Portable) ──────────────────────────────
Write-Host ""
Write-Host " [*] Building portable single-file executable..." -ForegroundColor Yellow
Write-Host " Configuration: $Configuration" -ForegroundColor Gray
Write-Host " Runtime: win-x64" -ForegroundColor Gray
Write-Host " Self-contained: Yes" -ForegroundColor Gray
Write-Host " Single-file: Yes" -ForegroundColor Gray
Write-Host ""
$publishArgs = @(
"publish", $AppProject,
"-c", $Configuration,
"-r", "win-x64",
"--self-contained", "true",
"-p:PublishSingleFile=true",
"-p:IncludeNativeLibrariesForSelfExtract=true",
"-p:EnableCompressionInSingleFile=true",
"-p:DebugType=none",
"-p:DebugSymbols=false",
"--no-restore",
"--output", $BuildDir,
"--nologo",
"--source", "https://api.nuget.org/v3/index.json"
)
$buildOutput = & $script:DotNetExe @publishArgs 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
Write-Host ""
Write-Host " [ERROR] GUI build failed!" -ForegroundColor Red
Write-Host ""
Write-Host $buildOutput -ForegroundColor Gray
Write-Host ""
Read-Host " Press Enter to exit"
exit 1
}
# ── Build CLI companion ────────────────────────────────────────
Write-Host ""
Write-Host " [*] Building CLI companion (DeepPurgeCli.exe)..." -ForegroundColor Yellow
$cliPublishArgs = @(
"publish", $CliProject,
"-c", $Configuration,
"-r", "win-x64",
"--self-contained", "true",
"-p:PublishSingleFile=true",
"-p:IncludeNativeLibrariesForSelfExtract=true",
"-p:EnableCompressionInSingleFile=true",
"-p:DebugType=none",
"-p:DebugSymbols=false",
"--no-restore",
"--output", $BuildDir,
"--nologo",
"--source", "https://api.nuget.org/v3/index.json"
)
$cliOutput = & $script:DotNetExe @cliPublishArgs 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
Write-Host " [ERROR] CLI build failed!" -ForegroundColor Red
Write-Host $cliOutput -ForegroundColor Gray
Read-Host " Press Enter to exit"
exit 1
}
# ── Build Slim (Framework-Dependent) ─────────────────────────
$SlimDir = Join-Path $BuildDir "slim"
New-Item -ItemType Directory -Path $SlimDir -Force | Out-Null
Write-Host ""
Write-Host " [*] Building framework-dependent slim executables..." -ForegroundColor Yellow
Write-Host " Output: build/slim/ (requires .NET 10 runtime on target)" -ForegroundColor Gray
$slimCommon = @(
"-c", $Configuration,
"-r", "win-x64",
"--no-self-contained",
"-p:PublishSingleFile=true",
"-p:DebugType=none",
"-p:DebugSymbols=false",
"--no-restore",
"--nologo",
"--source", "https://api.nuget.org/v3/index.json"
)
$slimGuiOut = & $script:DotNetExe publish $AppProject @slimCommon --output $SlimDir 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
Write-Host " [WARN] Slim GUI build failed (self-contained builds still available)" -ForegroundColor Yellow
} else {
$slimCliOut = & $script:DotNetExe publish $CliProject @slimCommon --output $SlimDir 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
Write-Host " [WARN] Slim CLI build failed" -ForegroundColor Yellow
} else {
Get-ChildItem $SlimDir -Exclude "DeepPurge.exe","DeepPurgeCli.exe" |
Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
$slimGuiSize = if (Test-Path (Join-Path $SlimDir "DeepPurge.exe")) { [math]::Round((Get-Item (Join-Path $SlimDir "DeepPurge.exe")).Length / 1MB, 1) } else { 0 }
$slimCliSize = if (Test-Path (Join-Path $SlimDir "DeepPurgeCli.exe")) { [math]::Round((Get-Item (Join-Path $SlimDir "DeepPurgeCli.exe")).Length / 1MB, 1) } else { 0 }
Write-Host " [OK] Slim GUI: $slimGuiSize MB | Slim CLI: $slimCliSize MB" -ForegroundColor Green
}
}
# ── Verify Output ──────────────────────────────────────────────
$exePath = Join-Path $BuildDir "DeepPurge.exe"
$cliPath = Join-Path $BuildDir "DeepPurgeCli.exe"
if (Test-Path $exePath) {
$guiInfo = Get-Item $exePath
$guiSizeMB = [math]::Round($guiInfo.Length / 1MB, 1)
$cliSizeMB = 0
if (Test-Path $cliPath) { $cliSizeMB = [math]::Round((Get-Item $cliPath).Length / 1MB, 1) }
# Keep only the two final exes; drop side artifacts (pdb leftovers, hostfxr extras).
Get-ChildItem $BuildDir -Exclude "DeepPurge.exe","DeepPurgeCli.exe" |
Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
# ── Authenticode signing (release only, optional) ─────────────
if ($Sign) {
Write-Host " [*] Signing release artifacts..." -ForegroundColor Yellow
try {
Invoke-Signing -ExePaths @($exePath, $cliPath)
Write-Host " [OK] Authenticode signature applied" -ForegroundColor Green
} catch {
Write-Host " [ERROR] Signing failed: $_" -ForegroundColor Red
Write-Host " Continuing with unsigned artifacts. SmartScreen will warn users." -ForegroundColor Yellow
}
} else {
Write-Host " [i] Skipped signing (-Sign not passed). Release builds should sign." -ForegroundColor DarkGray
}
$checksumPath = Write-Sha256Sums -ArtifactPaths @($exePath, $cliPath)
if ($ValidateRelease) {
if (-not (Invoke-ReleaseReadinessValidation)) { exit 1 }
}
Write-Host ""
Write-Host " ============================================" -ForegroundColor Green
Write-Host " BUILD SUCCESSFUL" -ForegroundColor Green
Write-Host " ============================================" -ForegroundColor Green
Write-Host ""
Write-Host " GUI: $exePath ($guiSizeMB MB)" -ForegroundColor White
Write-Host " CLI: $cliPath ($cliSizeMB MB)" -ForegroundColor White
Write-Host " SHA256: $checksumPath" -ForegroundColor White
Write-Host ""
Write-Host " This is a portable executable." -ForegroundColor Gray
Write-Host " No installation required - just run it." -ForegroundColor Gray
Write-Host " Requires: Windows 10/11 x64" -ForegroundColor Gray
Write-Host " Must run as: Administrator" -ForegroundColor Gray
Write-Host ""
if ($OpenOutput) {
Start-Process explorer.exe -ArgumentList "/select,`"$exePath`""
}
}
else {
Write-Host " [ERROR] Output exe not found at: $exePath" -ForegroundColor Red
Write-Host ""
Write-Host " Build output:" -ForegroundColor Gray
Write-Host $buildOutput -ForegroundColor Gray
Read-Host " Press Enter to exit"
exit 1
}