Skip to content

Commit 01f0016

Browse files
nohwndCopilot
andcommitted
Fix #2657: Optimize Clear-TestDrive to delete only root new items
Copilot-generated fix. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent d5f7c87 commit 01f0016

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

src/functions/TestDrive.ps1

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,12 +112,32 @@ function Clear-TestDrive {
112112

113113
Remove-TestDriveSymbolicLinks -Path $TestDrivePath
114114

115-
foreach ($i in [IO.Directory]::GetFileSystemEntries($TestDrivePath, '*.*', [System.IO.SearchOption]::AllDirectories)) {
116-
if ($Exclude -contains $i) {
117-
continue
115+
$allCurrent = [IO.Directory]::GetFileSystemEntries($TestDrivePath, '*.*', [System.IO.SearchOption]::AllDirectories)
116+
117+
# Collect new items (those not in the snapshot taken before the test)
118+
$newItems = foreach ($i in $allCurrent) {
119+
if ($Exclude -notcontains $i) {
120+
$i
118121
}
122+
}
119123

120-
& $SafeCommands['Remove-Item'] -Force -Recurse $i -ErrorAction Ignore
124+
if (-not $newItems) {
125+
return
126+
}
127+
128+
# Build a set of new item paths for O(1) parent lookups
129+
$newItemSet = [System.Collections.Generic.HashSet[string]]::new(
130+
[string[]]@($newItems),
131+
[System.StringComparer]::OrdinalIgnoreCase)
132+
133+
# Only delete "root" new items (those whose parent directory is not also a new item).
134+
# Deleting with -Recurse removes all descendants in one call, avoiding redundant
135+
# Remove-Item calls on already-deleted children.
136+
foreach ($item in $newItemSet) {
137+
$parent = [IO.Path]::GetDirectoryName($item)
138+
if (-not $newItemSet.Contains($parent)) {
139+
& $SafeCommands['Remove-Item'] -Path $item -Force -Recurse -ErrorAction Ignore
140+
}
121141
}
122142
}
123143
}

0 commit comments

Comments
 (0)