-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathdelphi-clean.ps1
More file actions
1445 lines (1216 loc) · 51.3 KB
/
Copy pathdelphi-clean.ps1
File metadata and controls
1445 lines (1216 loc) · 51.3 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
#requires -Version 5.1
# -----------------------------------------------------------------------------
# delphi-clean
#
# A PowerShell utility to remove Delphi build artifacts, intermediate files,
# and IDE-generated clutter, with support for preview, validation, and CI workflows.
#
# Part of Continuous-Delphi: Focused on strengthening Delphi's continued success
# https://github.com/continuous-delphi
#
# Project repository:
# https://github.com/continuous-delphi/delphi-clean
#
# Also included in the Continuous-Delphi PowerShell CI module:
# https://github.com/continuous-delphi/delphi-powershell-ci
#
# Copyright (c) 2026 Darian Miller
# Licensed under the MIT License.
# https://opensource.org/licenses/MIT
# SPDX-License-Identifier: MIT
# -----------------------------------------------------------------------------
<#
.SYNOPSIS
Cleans Delphi build artifacts from a repository tree using three cleanup levels.
.DESCRIPTION
Targets the current working directory by default.
Supports three cleanup levels:
basic - safe, low-risk cleanup of common transient files
standard - removes build outputs and common generated files
deep - aggressive cleanup including user-local IDE state files
Use -Check to audit without deleting. Use -OutputLevel to control verbosity.
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Level standard
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Level deep -Verbose
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Level deep -WhatIf
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Level standard -PassThru
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Level standard -Json
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Level basic -IncludeFilePattern '*.res'
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Level basic -IncludeFilePattern '*.res','*.mab' -ExcludeDirectoryPattern 'assets','vendor*'
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Version
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Version -Format json
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Level standard -RecycleBin
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Level standard -Check
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Level standard -Check -OutputLevel quiet
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -Level standard -OutputLevel summary
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -ShowConfig
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -ShowConfig -Json
.EXAMPLE
powershell.exe -File .\source\delphi-clean.ps1 -ConfigFile C:/ci/delphi-clean-ci.json -Level standard
.PARAMETER Level
Cleanup level to apply. One of: basic, standard, deep. Levels are cumulative --
standard includes everything basic removes, and deep includes everything standard
removes. Defaults to basic.
.PARAMETER RootPath
Root directory to scan. Defaults to the current working directory when omitted.
All scans and deletions are confined to this directory tree.
.PARAMETER ExcludeDirectoryPattern
One or more directory-name glob patterns to skip during scanning. Directories
whose names match any pattern (case-insensitive) are not entered and nothing
inside them is deleted. The built-in exclusions (.git, .vs, .claude) are always
applied in addition to any patterns supplied here.
.PARAMETER IncludeFilePattern
One or more additional file-name glob patterns to delete beyond the patterns
implied by -Level. Useful for project-specific artifacts such as *.res or *.mab.
.PARAMETER PassThru
Return a structured object to the pipeline containing the list of found items
and deletion results. Intended for scripting scenarios that consume the output
programmatically. May be combined with -WhatIf.
.PARAMETER Json
Emit a single JSON object to standard output instead of plain-text messages.
Suppresses all other output (Write-Information, Write-Progress). Suitable for
CI pipelines and tooling integrations.
.PARAMETER RecycleBin
Send items to the platform recycle bin / trash instead of deleting them
permanently. On Windows, uses Microsoft.VisualBasic.FileIO.FileSystem. On
macOS, moves items into `~/.Trash/`. On Linux, uses the FreeDesktop trash
location under `~/.local/share/Trash/`.
.PARAMETER Check
Audit-only mode. Scans for artifacts but does not delete anything. Exits with
code 0 when nothing is found, or 1 when artifacts are present. Cannot be
combined with -WhatIf.
.PARAMETER ShowConfig
Display the effective merged configuration (from all config files and CLI
flags) and exit without scanning or cleaning. Add -Json for machine-readable
output.
.PARAMETER ConfigFile
Path to an explicit JSON configuration file. Loaded at the highest priority
below command-line parameters, above project-level and local config files.
Useful in CI pipelines where the config lives outside the repository tree.
.PARAMETER OutputLevel
Controls the amount of plain-text output produced during a run.
detailed - header, per-item lines, and summary (default)
summary - header and summary only; per-item lines are suppressed
quiet - no output at all; use the exit code or -Json as the signal
Has no effect when -Json is active.
.PARAMETER Version
Display the tool version and exit. Cannot be combined with Clean parameters.
.PARAMETER Format
Output format when -Version is specified. One of: text (default), json.
#>
[CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Clean')]
param(
[Parameter(ParameterSetName = 'Version', Mandatory)]
[switch]$Version,
[Parameter(ParameterSetName = 'Version')]
[ValidateSet('text', 'json')]
[string]$Format = 'text',
[Parameter(ParameterSetName = 'Clean')]
[ValidateSet('basic', 'standard', 'deep')]
[string]$Level = 'basic',
[Parameter(ParameterSetName = 'Clean')]
[string]$RootPath,
[Parameter(ParameterSetName = 'Clean')]
[string[]]$ExcludeDirectoryPattern = @(),
[Parameter(ParameterSetName = 'Clean')]
[string[]]$IncludeFilePattern = @(),
[Parameter(ParameterSetName = 'Clean')]
[switch]$PassThru,
[Parameter(ParameterSetName = 'Clean')]
[switch]$Json,
[Parameter(ParameterSetName = 'Clean')]
[switch]$RecycleBin,
# Audit mode: scan only, never deletes. Exit 0 = nothing found, 1 = artifacts found.
# Cannot be combined with -WhatIf.
[Parameter(ParameterSetName = 'Clean')]
[switch]$Check,
# Show the effective merged configuration and exit. No scan or cleanup is performed.
[Parameter(ParameterSetName = 'Clean')]
[switch]$ShowConfig,
# Path to an explicit JSON config file. Loaded at highest config priority (above
# project and local files, below command-line parameters).
[Parameter(ParameterSetName = 'Clean')]
[string]$ConfigFile,
# Controls how much output is produced during a clean or check run.
# detailed - header, per-item lines, and summary (default)
# summary - header and summary only; per-item lines are suppressed
# quiet - no output at all; use the exit code as the signal
[Parameter(ParameterSetName = 'Clean')]
[ValidateSet('detailed', 'summary', 'quiet')]
[string]$OutputLevel = 'detailed'
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$script:ToolVersion = '1.3.0'
$script:OutputLevel = $OutputLevel
$script:BuiltInExcludeDirs = @('.git', '.vs', '.claude')
if ($Version) {
if ($Format -eq 'json') {
[PSCustomObject]@{
ok = $true
command = 'version'
tool = [PSCustomObject]@{
name = 'delphi-clean'
version = $script:ToolVersion
}
} | ConvertTo-Json -Depth 3 -Compress
}
else {
Write-Output "delphi-clean $script:ToolVersion"
}
exit 0
}
# ---------------------------------------------------------------------------
# Output helpers
# ---------------------------------------------------------------------------
# Write-Detail : visible at 'detailed' only
# Write-Summary : visible at 'detailed' and 'summary'
# Write-Section : section banner, visible at 'detailed' only
# Write-SummarySection: section banner, visible at 'detailed' and 'summary'
# Warnings and errors are never suppressed by -OutputLevel.
function Write-Detail {
param([AllowEmptyString()][Parameter(Mandatory)][string]$Message)
if ($script:OutputLevel -eq 'detailed' -and -not $Json) {
Write-Information $Message -InformationAction Continue
}
}
function Write-Summary {
param([AllowEmptyString()][Parameter(Mandatory)][string]$Message)
if ($script:OutputLevel -ne 'quiet' -and -not $Json) {
Write-Information $Message -InformationAction Continue
}
}
function Write-Section {
param([AllowEmptyString()][Parameter(Mandatory)][string]$Message)
if ($script:OutputLevel -eq 'detailed' -and -not $Json) {
Write-Information '' -InformationAction Continue
Write-Information ('=' * 70) -InformationAction Continue
Write-Information $Message -InformationAction Continue
Write-Information ('=' * 70) -InformationAction Continue
}
}
function Write-SummarySection {
param([AllowEmptyString()][Parameter(Mandatory)][string]$Message)
if ($script:OutputLevel -ne 'quiet' -and -not $Json) {
Write-Information '' -InformationAction Continue
Write-Information ('=' * 70) -InformationAction Continue
Write-Information $Message -InformationAction Continue
Write-Information ('=' * 70) -InformationAction Continue
}
}
# ---------------------------------------------------------------------------
# Size helpers
# ---------------------------------------------------------------------------
function Format-Duration {
param([long]$Milliseconds)
if ($Milliseconds -lt 1000) { return "$Milliseconds ms" }
return ('{0:N3} s' -f ($Milliseconds / 1000))
}
function Format-ByteSize {
param([long]$Bytes)
if ($Bytes -ge 1GB) { return ('{0:N1} GB' -f ($Bytes / 1GB)) }
if ($Bytes -ge 1MB) { return ('{0:N1} MB' -f ($Bytes / 1MB)) }
if ($Bytes -ge 1KB) { return ('{0:N1} KB' -f ($Bytes / 1KB)) }
return "$Bytes B"
}
function Get-TreeSize {
param(
[Parameter(Mandatory)]
[string]$Path
)
if (-not (Test-Path -LiteralPath $Path)) { return [long]0 }
$total = [long]0
foreach ($f in (Get-ChildItem -Path $Path -Recurse -File -Force -ErrorAction SilentlyContinue)) {
$total += $f.Length
}
return $total
}
# ---------------------------------------------------------------------------
# Trash / recycle helpers
# ---------------------------------------------------------------------------
function Get-TrashDestination {
param(
[Parameter(Mandatory)]
[string]$TrashFilesDir,
[Parameter(Mandatory)]
[string]$Name
)
$dest = Join-Path $TrashFilesDir $Name
if (-not (Test-Path -LiteralPath $dest)) {
return $dest
}
$base = [System.IO.Path]::GetFileNameWithoutExtension($Name)
$ext = [System.IO.Path]::GetExtension($Name)
$counter = 2
do {
$uniqueName = if ($ext) { "$base $counter$ext" } else { "$Name $counter" }
$dest = Join-Path $TrashFilesDir $uniqueName
$counter++
} while (Test-Path -LiteralPath $dest)
return $dest
}
function Send-ToMacTrash {
param(
[Parameter(Mandatory)]
[string]$Path
)
$trashDir = Join-Path $HOME '.Trash'
if (-not (Test-Path -LiteralPath $trashDir)) {
New-Item -ItemType Directory -Path $trashDir | Out-Null
}
$name = Split-Path -Path $Path -Leaf
$dest = Get-TrashDestination -TrashFilesDir $trashDir -Name $name
Move-Item -LiteralPath $Path -Destination $dest
}
function Send-ToLinuxTrash {
param(
[Parameter(Mandatory)]
[string]$Path
)
$trashRoot = Join-Path $HOME '.local/share/Trash'
$filesDir = Join-Path $trashRoot 'files'
$infoDir = Join-Path $trashRoot 'info'
foreach ($dir in @($filesDir, $infoDir)) {
if (-not (Test-Path -LiteralPath $dir)) {
New-Item -ItemType Directory -Path $dir | Out-Null
}
}
$name = Split-Path -Path $Path -Leaf
$destPath = Get-TrashDestination -TrashFilesDir $filesDir -Name $name
$destName = Split-Path -Path $destPath -Leaf
$infoFile = Join-Path $infoDir "$destName.trashinfo"
$absPath = [System.IO.Path]::GetFullPath($Path)
$timestamp = [datetime]::Now.ToString('yyyy-MM-ddTHH:mm:ss')
$trashInfoContent = "[Trash Info]`nPath=$absPath`nDeletionDate=$timestamp`n"
[System.IO.File]::WriteAllText($infoFile, $trashInfoContent)
try {
Move-Item -LiteralPath $Path -Destination $destPath
}
catch {
Remove-Item -LiteralPath $infoFile -Force -ErrorAction SilentlyContinue
throw
}
}
function Get-PlatformKind {
if (Get-Variable -Name IsWindows -ErrorAction SilentlyContinue) {
if ($IsWindows) { return 'Windows' }
if ($IsMacOS) { return 'macOS' }
if ($IsLinux) { return 'Linux' }
}
switch ([System.Environment]::OSVersion.Platform) {
'Win32NT' { return 'Windows' }
'Unix' {
try {
if ([System.IO.Directory]::Exists('/System/Library/CoreServices')) {
return 'macOS'
}
}
catch {
Write-Verbose "Platform probe for macOS fallback failed: $($_.Exception.Message)"
}
return 'Linux'
}
'MacOSX' { return 'macOS' }
default { return 'Unknown' }
}
}
function Send-ToRecycleBin {
param(
[Parameter(Mandatory)]
[string]$Path,
[Parameter(Mandatory)]
[ValidateSet('File', 'Directory')]
[string]$Type
)
$platformKind = Get-PlatformKind
if ($platformKind -eq 'Windows') {
Add-Type -AssemblyName Microsoft.VisualBasic -ErrorAction Stop
if ($Type -eq 'File') {
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile(
$Path,
[Microsoft.VisualBasic.FileIO.UIOption]::OnlyErrorDialogs,
[Microsoft.VisualBasic.FileIO.RecycleOption]::SendToRecycleBin
)
}
else {
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory(
$Path,
[Microsoft.VisualBasic.FileIO.UIOption]::OnlyErrorDialogs,
[Microsoft.VisualBasic.FileIO.RecycleOption]::SendToRecycleBin
)
}
}
elseif ($platformKind -eq 'macOS') {
Send-ToMacTrash -Path $Path
}
elseif ($platformKind -eq 'Linux') {
Send-ToLinuxTrash -Path $Path
}
else {
throw 'Unsupported platform for -RecycleBin.'
}
}
# ---------------------------------------------------------------------------
# Path helpers
# ---------------------------------------------------------------------------
function Get-RelativePathCompat {
param(
[Parameter(Mandatory)]
[string]$BasePath,
[Parameter(Mandatory)]
[string]$TargetPath
)
$baseFull = [System.IO.Path]::GetFullPath($BasePath)
$targetFull = [System.IO.Path]::GetFullPath($TargetPath)
if (-not $baseFull.EndsWith([string][System.IO.Path]::DirectorySeparatorChar)) {
$baseFull += [string][System.IO.Path]::DirectorySeparatorChar
}
$baseUri = New-Object System.Uri($baseFull)
$targetUri = New-Object System.Uri($targetFull)
$relativeUri = $baseUri.MakeRelativeUri($targetUri)
$relativePath = [System.Uri]::UnescapeDataString($relativeUri.ToString()) -replace '/', [System.IO.Path]::DirectorySeparatorChar
if ([string]::IsNullOrWhiteSpace($relativePath)) {
return '.'
}
return $relativePath
}
function Resolve-CleanRoot {
param(
[string]$InputRoot
)
if ([string]::IsNullOrWhiteSpace($InputRoot)) {
return (Get-Location).Path
}
$resolvedInput = Resolve-Path $InputRoot
return $resolvedInput.Path
}
function Test-SafeCleanRoot {
param(
[Parameter(Mandatory)]
[string]$Root
)
$fullRoot = [System.IO.Path]::GetFullPath($Root)
$rootOfRoot = [System.IO.Path]::GetPathRoot($fullRoot)
if ($fullRoot -eq $rootOfRoot) {
throw "Refusing to clean an unsafe root path: $fullRoot"
}
$resolved = Resolve-Path -LiteralPath $fullRoot
if (-not $resolved) {
throw "Invalid root path: $fullRoot"
}
}
function Test-PathUnderExcludedDirectory {
param(
[Parameter(Mandatory)]
[string]$FullName,
[Parameter(Mandatory)]
[string]$Root,
[Parameter(Mandatory)]
[string[]]$ExcludedDirPatterns
)
$relative = Get-RelativePathCompat -BasePath $Root -TargetPath $FullName
if ($relative -eq '.') {
return $false
}
$parts = $relative -split '[\\\/]'
foreach ($part in $parts) {
foreach ($pattern in $ExcludedDirPatterns) {
if ($part -ilike $pattern) {
return $true
}
}
}
return $false
}
# ---------------------------------------------------------------------------
# Configuration file helpers
# ---------------------------------------------------------------------------
function Get-ConfigValue {
param(
[object]$Config,
[Parameter(Mandatory)]
[string]$Key,
$Default = $null
)
if ($null -eq $Config) { return $Default }
$prop = $Config.PSObject.Properties[$Key]
if ($null -eq $prop) { return $Default }
return $prop.Value
}
function Read-ConfigFile {
param(
[Parameter(Mandatory)]
[string]$Path
)
if (-not (Test-Path -LiteralPath $Path)) {
return $null
}
try {
$content = Get-Content -LiteralPath $Path -Raw -Encoding UTF8
return $content | ConvertFrom-Json
}
catch {
Write-Warning "[config] Failed to parse '$Path': $($_.Exception.Message)"
return $null
}
}
function Merge-CleanConfig {
param(
[object[]]$Configs = @()
)
$resultLevel = $null
$resultOutputLevel = $null
$resultRecycleBin = $null
$resultSearchParent = $null
$seenInclude = New-Object 'System.Collections.Generic.HashSet[string]' -ArgumentList ([System.StringComparer]::OrdinalIgnoreCase)
$seenExclude = New-Object 'System.Collections.Generic.HashSet[string]' -ArgumentList ([System.StringComparer]::OrdinalIgnoreCase)
$resultInclude = New-Object 'System.Collections.Generic.List[string]'
$resultExclude = New-Object 'System.Collections.Generic.List[string]'
foreach ($config in $Configs) {
if ($null -eq $config) { continue }
$val = Get-ConfigValue -Config $config -Key 'level'
if ($null -ne $val) { $resultLevel = $val }
$val = Get-ConfigValue -Config $config -Key 'outputLevel'
if ($null -ne $val) { $resultOutputLevel = $val }
$val = Get-ConfigValue -Config $config -Key 'recycleBin'
if ($null -ne $val) { $resultRecycleBin = $val }
$val = Get-ConfigValue -Config $config -Key 'searchParentFolders'
if ($null -ne $val) { $resultSearchParent = $val }
foreach ($item in @(Get-ConfigValue -Config $config -Key 'includeFilePattern' -Default @())) {
if (-not [string]::IsNullOrEmpty($item) -and $seenInclude.Add($item)) {
$resultInclude.Add($item)
}
}
foreach ($item in @(Get-ConfigValue -Config $config -Key 'excludeDirectoryPattern' -Default @())) {
if (-not [string]::IsNullOrEmpty($item) -and $seenExclude.Add($item)) {
$resultExclude.Add($item)
}
}
}
return [PSCustomObject]@{
level = $resultLevel
outputLevel = $resultOutputLevel
recycleBin = $resultRecycleBin
searchParentFolders = $resultSearchParent
includeFilePattern = @($resultInclude)
excludeDirectoryPattern = @($resultExclude)
}
}
function Resolve-EffectiveConfig {
param(
[Parameter(Mandatory)]
[string]$RootPath,
[string]$ConfigFile = ''
)
$log = New-Object 'System.Collections.Generic.List[string]'
$anyConfigFound = $false
# Allow test suites to redirect the home directory lookup.
# Guard against $HOME being null/empty (e.g. minimal CI environments).
$homeDir = if (-not [string]::IsNullOrEmpty($env:DELPHI_CLEAN_HOME_OVERRIDE)) {
$env:DELPHI_CLEAN_HOME_OVERRIDE
} elseif (-not [string]::IsNullOrEmpty($HOME)) {
[string]$HOME
} else {
''
}
$projectConfigPath = Join-Path $RootPath 'delphi-clean.json'
$localConfigPath = Join-Path $RootPath 'delphi-clean.local.json'
$homeConfig = $null
if (-not [string]::IsNullOrEmpty($homeDir)) {
$homeConfigPath = Join-Path $homeDir 'delphi-clean.json'
$homeConfig = Read-ConfigFile -Path $homeConfigPath
Write-Verbose ("[config] user-level: {0}" -f $(if ($null -ne $homeConfig) { $homeConfigPath } else { "$homeConfigPath (not found)" }))
if ($null -ne $homeConfig) { $anyConfigFound = $true; $log.Add("[config] user-level: $homeConfigPath") }
} else {
Write-Verbose '[config] user-level: skipped ($HOME not set)'
}
$projectConfig = Read-ConfigFile -Path $projectConfigPath
$localConfig = Read-ConfigFile -Path $localConfigPath
# Write-Verbose always shows all paths; log only tracks found files
Write-Verbose ("[config] project-level: {0}" -f $(if ($null -ne $projectConfig) { $projectConfigPath } else { "$projectConfigPath (not found)" }))
Write-Verbose ("[config] local override: {0}" -f $(if ($null -ne $localConfig) { $localConfigPath } else { "$localConfigPath (not found)" }))
if ($null -ne $projectConfig) { $anyConfigFound = $true; $log.Add("[config] project-level: $projectConfigPath") }
if ($null -ne $localConfig) { $anyConfigFound = $true; $log.Add("[config] local override: $localConfigPath") }
# Traversal is triggered only by the project-level or local config.
# searchParentFolders in the $HOME config is intentionally ignored.
$traversalRequested = ((Get-ConfigValue -Config $projectConfig -Key 'searchParentFolders') -eq $true) -or
((Get-ConfigValue -Config $localConfig -Key 'searchParentFolders') -eq $true)
$traversedConfigs = @()
if ($traversalRequested) {
$current = Split-Path -Parent $RootPath
while (-not [string]::IsNullOrEmpty($current)) {
$parentConfigPath = Join-Path $current 'delphi-clean.json'
$parentConfig = Read-ConfigFile -Path $parentConfigPath
if ($null -ne $parentConfig) {
# Prepend so farthest ancestor ends up first (lowest priority among traversed)
$traversedConfigs = @($parentConfig) + $traversedConfigs
$anyConfigFound = $true
Write-Verbose "[config] traversed: $parentConfigPath"
$log.Add("[config] traversed: $parentConfigPath")
if ((Get-ConfigValue -Config $parentConfig -Key 'searchParentFolders') -eq $false) {
Write-Verbose '[config] (stop marker -- traversal ends here)'
$log.Add('[config] (stop marker -- traversal ends here)')
break
}
}
$parent = Split-Path -Parent $current
if ($parent -eq $current) { break } # filesystem root reached
$current = $parent
}
}
# Explicit config file (highest config priority, below CLI)
$explicitConfig = $null
if (-not [string]::IsNullOrEmpty($ConfigFile)) {
if (-not (Test-Path -LiteralPath $ConfigFile)) {
Write-Warning "[config] Explicit config file not found: $ConfigFile"
}
else {
$explicitConfig = Read-ConfigFile -Path $ConfigFile
if ($null -ne $explicitConfig) {
$anyConfigFound = $true
Write-Verbose "[config] explicit file: $ConfigFile"
$log.Add("[config] explicit file: $ConfigFile")
}
}
}
# Merge: lowest priority first
$allConfigs = @($homeConfig) + $traversedConfigs + @($projectConfig) + @($localConfig) + @($explicitConfig)
$merged = Merge-CleanConfig -Configs $allConfigs
$finalLogLines = @(
'[config] final merged values:'
("[config] level = {0}" -f $(if ($null -ne $merged.level) { $merged.level } else { '(not set)' }))
("[config] outputLevel = {0}" -f $(if ($null -ne $merged.outputLevel) { $merged.outputLevel } else { '(not set)' }))
("[config] recycleBin = {0}" -f $(if ($null -ne $merged.recycleBin) { "$($merged.recycleBin)" } else { '(not set)' }))
("[config] searchParentFolders = {0}" -f $(if ($null -ne $merged.searchParentFolders) { "$($merged.searchParentFolders)" } else { '(not set)' }))
("[config] includeFilePattern = [{0}]" -f ($merged.includeFilePattern -join ', '))
("[config] excludeDirectoryPattern = [{0}]" -f ($merged.excludeDirectoryPattern -join ', '))
)
foreach ($line in $finalLogLines) { Write-Verbose $line }
return [PSCustomObject]@{
Merged = $merged
Log = $log.ToArray()
ConfigsFound = $anyConfigFound
}
}
# ---------------------------------------------------------------------------
# Level definitions
# ---------------------------------------------------------------------------
function Get-LevelDefinition {
param(
[Parameter(Mandatory)]
[ValidateSet('basic', 'standard', 'deep')]
[string]$Name
)
# --- base (basic) ---
$basicFiles = @(
'*.dcu',
'*.identcache',
'*.bak',
'*.tmp',
'*.tvsconfig',
'*.stat'
)
$basicDirs = @(
'__history'
)
# --- standard additions ---
$standardFilesExtra = @(
'*.drc',
'*.map',
'*.rsm',
'*.tds',
'*.bpl',
'*.dcp',
'*.bpi',
'*.so',
'*.o',
'*.a',
'*.dylib',
'*.exe',
'*.hpp',
'*.dres',
'*.ilc',
'*.ild',
'*.ilf',
'*.ipu',
'*.ddp',
'*.prjmgc',
'*.vlb',
'dunitx-results.xml'
)
$standardDirsExtra = @(
'Win32',
'Win64',
'WinARM64EC',
'Debug',
'Release',
'OSX64',
'OSXARM64',
'Android',
'Android64',
'iOSDevice64',
'iOSSimulatorArm64',
'Linux64',
'LinuxARM64',
'TMSWeb'
)
# --- deep additions ---
$deepFilesExtra = @(
'*.local',
'*.dproj.local',
'*.groupproj.local',
'*.projdata',
'*.dsk',
'*.~*',
'*.lib',
'*.fbpInf',
'*.fbl8',
'*.fbpbrk',
'*.fb8lck',
'*.mab',
'TestInsightSettings.ini'
)
$deepDirsExtra = @(
'__recovery'
)
# --- compose ---
switch ($Name) {
'basic' {
$files = $basicFiles
$dirs = $basicDirs
}
'standard' {
$files = $basicFiles + $standardFilesExtra
$dirs = $basicDirs + $standardDirsExtra
}
'deep' {
$files = $basicFiles + $standardFilesExtra + $deepFilesExtra
$dirs = $basicDirs + $standardDirsExtra + $deepDirsExtra
}
}
# --- dedupe ---
$files = $files | Sort-Object -Unique
$dirs = $dirs | Sort-Object -Unique
return @{
FilePatterns = $files
DirectoryNames = $dirs
}
}
# ---------------------------------------------------------------------------
# Scan functions
# ---------------------------------------------------------------------------
function Get-FilesToDelete {
param(
[Parameter(Mandatory)]
[string]$Root,
[Parameter(Mandatory)]
[string[]]$Patterns,
[Parameter(Mandatory)]
[string[]]$ExcludedDirPatterns
)
Write-Verbose 'Scanning for matching files.'
$examined = 0
$allFiles = Get-ChildItem -Path $Root -Recurse -File -Force -ErrorAction SilentlyContinue |
ForEach-Object {
$examined++
if (-not $Json -and $examined % 500 -eq 0) {
Write-Progress -Activity 'delphi-clean' -Status "Scanning: $examined files examined..."
}
$_
} |
Where-Object {
-not (Test-PathUnderExcludedDirectory -FullName $_.FullName -Root $Root -ExcludedDirPatterns $ExcludedDirPatterns)
}
$allFiles |
Where-Object {
$file = $_
foreach ($pattern in $Patterns) {
if ($file.Name -like $pattern) {
return $true
}
}
return $false
} |
Sort-Object -Property FullName -Unique
}
function Get-DirectoriesToDelete {
param(
[Parameter(Mandatory)]
[string]$Root,
[Parameter(Mandatory)]
[string[]]$DirectoryNames,
[Parameter(Mandatory)]
[string[]]$ExcludedDirPatterns
)
Write-Verbose 'Scanning for matching directories.'
$nameSet = @{}
foreach ($dirName in $DirectoryNames) {
$nameSet[$dirName.ToUpperInvariant()] = $true
}
Get-ChildItem -Path $Root -Recurse -Directory -Force -ErrorAction SilentlyContinue |
Where-Object {
$nameSet.ContainsKey($_.Name.ToUpperInvariant()) -and
-not (Test-PathUnderExcludedDirectory -FullName $_.FullName -Root $Root -ExcludedDirPatterns $ExcludedDirPatterns)
} |
Sort-Object -Property FullName -Unique |
Sort-Object -Property { $_.FullName.Length } -Descending
}
# ---------------------------------------------------------------------------
# Deletion record
# ---------------------------------------------------------------------------
function ConvertTo-DeletionRecord {
param(
[Parameter(Mandatory)]
[ValidateSet('File', 'Directory')]
[string]$Type,
[Parameter(Mandatory)]
[string]$Path,
[Parameter(Mandatory)]
[bool]$Deleted,
[long]$Size = 0
)
[PSCustomObject]@{
Type = $Type
Path = $Path
Deleted = $Deleted
Size = $Size
}
}
# ---------------------------------------------------------------------------
# Removal functions
# ---------------------------------------------------------------------------
function Remove-FileList {
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[System.IO.FileInfo[]]$Files = @(),
[switch]$ReturnRecords,
[switch]$RecycleBin,
[switch]$SuppressWhatIfOutput
)
$result = [PSCustomObject]@{
DeletedCount = 0
FailedCount = 0
BytesFreed = [long]0
Records = New-Object System.Collections.Generic.List[object]
}
if (@($Files).Count -eq 0) {
return $result
}
$action = if ($RecycleBin) { 'Recycle file' } else { 'Delete file' }
$verb = if ($RecycleBin) { 'Recycled' } else { 'Deleted' }
foreach ($file in $Files) {
Write-Verbose "Evaluating file: $($file.FullName)"
if ($WhatIfPreference -and $SuppressWhatIfOutput) {
Write-Detail "Would $($action.ToLower()): $($file.FullName)"