Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 15 additions & 17 deletions Modules/LeafDirectoryDiscovery.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -190,41 +190,39 @@ function New-ZippableLeafDirProvider {
throw ("New-ZippableLeafDirProvider: -ScanPath does not exist or is not a directory: '" + $ScanPath + "'")
}

$dirStack = [System.Collections.Generic.Stack[string]]::new()
$dirStack.Push($ScanPath)
$state = @{ CurrentEnumerator = $null }
# One open enumerator per folder level. A subfolder is walked to its end
# before the next sibling, so folders come out in listing order.
$enumeratorStack = [System.Collections.Generic.Stack[object]]::new()
$state = @{ NextDir = $ScanPath }

return {
while ($true) {
if ($null -eq $state.CurrentEnumerator) {
if ($dirStack.Count -eq 0) { return $null }
$currentDir = $dirStack.Pop()
if ($null -ne $state.NextDir) {
$currentDir = $state.NextDir
$state.NextDir = $null
try {
$state.CurrentEnumerator = [System.IO.Directory]::EnumerateDirectories($currentDir).GetEnumerator()
$enumeratorStack.Push([System.IO.Directory]::EnumerateDirectories($currentDir).GetEnumerator())
} catch {
Write-Log ("Could not enumerate '" + $currentDir + "' during leaf-directory scan - skipping it, continuing with the rest of the tree: " + $_) -Level Warn
$state.CurrentEnumerator = $null
continue
}
}
if ($enumeratorStack.Count -eq 0) { return $null }

$top = $enumeratorStack.Peek()
$hasNext = $false
try {
$hasNext = $state.CurrentEnumerator.MoveNext()
$hasNext = $top.MoveNext()
} catch {
Write-Log ("Leaf-directory scan hit an error partway through a directory - skipping the rest of it, continuing with the rest of the tree: " + $_) -Level Warn
$state.CurrentEnumerator.Dispose()
$state.CurrentEnumerator = $null
continue
}

if (-not $hasNext) {
$state.CurrentEnumerator.Dispose()
$state.CurrentEnumerator = $null
$top.Dispose()
$null = $enumeratorStack.Pop()
continue
}

$childPath = $state.CurrentEnumerator.Current
$childPath = $top.Current

$dirInfo = [System.IO.DirectoryInfo]::new($childPath)
# Reparse-point guard - DOCUMENTED
Expand All @@ -238,7 +236,7 @@ function New-ZippableLeafDirProvider {
-ExcludeStagingDirs $ExcludeStagingDirs -ForceRezip $ForceRezip
if ($null -ne $candidate) { return $candidate }

$dirStack.Push($childPath)
$state.NextDir = $childPath
}
}.GetNewClosure()
}
Expand Down
21 changes: 17 additions & 4 deletions Modules/Logging.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ $script:SummaryFileEnabled = $true
$script:CleanConsoleOutputEnabled = $false
$script:logErrorPriorContent = ""
$script:logWarnPriorContent = ""
$script:logRunHeaderPending = $null # log file path -> this run's header, until the run's first line in that file
$script:logWriteFailureWarned = $null # log files already warned about this run - see Write-LogWriteFailureWarning

function Initialize-LogPaths {
Expand Down Expand Up @@ -59,29 +60,33 @@ function Initialize-LogPaths {

function Start-LogRun {
$script:logWriteFailureWarned = $null
$script:logRunHeaderPending = $null
if ($script:FullLogging) { return }

$runHeader = "=== Run: " + (Get-Date -Format "yyyy-MM-dd HHmmss") + " ==="
$script:logRunHeaderPending = @{}
foreach ($target in @(
@{ FilePath = $script:logErrorFile; PriorVar = 'logErrorPriorContent' },
@{ FilePath = $script:logWarnFile; PriorVar = 'logWarnPriorContent' }
)) {
if ([string]::IsNullOrEmpty($target.FilePath)) { continue }
$script:logRunHeaderPending[$target.FilePath] = $runHeader
try {
$prior = if (Test-Path -LiteralPath $target.FilePath) { [System.IO.File]::ReadAllText($target.FilePath) } else { "" }
Set-Variable -Scope Script -Name $target.PriorVar -Value $prior
Invoke-MutexGuardedWrite { $runHeader | Out-File -FilePath $target.FilePath -Append -Encoding UTF8 }
} catch {
# Report straight to the console rather than through Write-Log:
# Write-Log would route a Warn back
# into this same locked file and throw again, uncaught.
$warnLine = Format-LogLine -Message ("Could not start a new run header in '" + $target.FilePath + "' - it may be locked or otherwise inaccessible. This run's own entries will still be appended, just without a run separator: " + $_) -Level "Warn"
$warnLine = Format-LogLine -Message ("Could not read '" + $target.FilePath + "' at the start of the run - it may be locked or otherwise inaccessible. This run's own entries will still be added to it, but may stay at the bottom instead of moving to the top: " + $_) -Level "Warn"
try { Write-LogLineToHost -Line $warnLine -Level "Warn" } catch { }
}
}
}

function Complete-LogRun {
# A line logged between runs doesn't belong under this run's header.
$script:logRunHeaderPending = $null
foreach ($target in @(
@{ FilePath = $script:logErrorFile; Prior = $script:logErrorPriorContent },
@{ FilePath = $script:logWarnFile; Prior = $script:logWarnPriorContent }
Expand All @@ -92,7 +97,9 @@ function Complete-LogRun {
$current = [System.IO.File]::ReadAllText($target.FilePath)
if ($current.StartsWith($target.Prior, [System.StringComparison]::Ordinal)) {
$thisRunContent = $current.Substring($target.Prior.Length)
[System.IO.File]::WriteAllText($target.FilePath, ($thisRunContent + $target.Prior), [System.Text.Encoding]::UTF8)
if ($thisRunContent.Length -gt 0) {
[System.IO.File]::WriteAllText($target.FilePath, ($thisRunContent + $target.Prior), [System.Text.Encoding]::UTF8)
}
}
# else: content no longer starts with what Start-LogRun captured
# (shouldn't happen) - leave it untouched rather than guess.
Expand Down Expand Up @@ -183,9 +190,15 @@ function Write-LogLineToHost {
function Write-LogLineToFile {
param([string]$FilePath, [string]$Line)
if ([string]::IsNullOrEmpty($FilePath)) { return }
$text = $Line + [System.Environment]::NewLine
$pendingHeaders = $script:logRunHeaderPending
if ($null -ne $pendingHeaders -and $pendingHeaders.ContainsKey($FilePath)) {
$text = $pendingHeaders[$FilePath] + [System.Environment]::NewLine + $text
}
Invoke-MutexGuardedWrite {
try {
[System.IO.File]::AppendAllText($FilePath, $Line + [System.Environment]::NewLine, [System.Text.Encoding]::UTF8)
[System.IO.File]::AppendAllText($FilePath, $text, [System.Text.Encoding]::UTF8)
if ($null -ne $pendingHeaders) { $pendingHeaders.Remove($FilePath) }
} catch {
# Never fatal - losing a log line must not take the run down.
# Warned once per file per run.
Expand Down
45 changes: 34 additions & 11 deletions _Harness/LeafDirectoryDiscovery.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -362,15 +362,15 @@ Write-Host ""

# ==============================================================================
# Scenario N2: a directory the provider just returned as a
# candidate must NOT be on $dirStack - it's a true leaf (Test-
# candidate must NOT be walked into afterwards - it's a true leaf (Test-
# ZippableLeafDirCandidate returns $null the moment it finds a
# subdirectory), so pushing it would be pointless, and worse in mode 4: the
# subdirectory), so that would be pointless, and worse in mode 4: the
# caller (Invoke-ZipOnlyPipeline) zips that SAME candidate and deletes
# the folder before this provider's next call. The stack being LIFO
# means the provider would then pop the now-deleted path and
# EnumerateDirectories would throw, logging a bogus "Could not enumerate -
# skipping it" Warn for a perfectly normal deletion - on every chapter,
# every default (-DeleteFolders $true) mode-4 run. This scenario
# the folder, usually before the provider would get back to it.
# EnumerateDirectories would throw on the now-deleted path, logging a
# bogus "Could not enumerate - skipping it" Warn for a perfectly normal
# deletion - on every chapter, every default (-DeleteFolders $true) mode-4
# run. This scenario
# reproduces the exact production condition: return a candidate, delete
# it (simulating the worker), call again - no Warn should be logged.
# ==============================================================================
Expand All @@ -387,10 +387,8 @@ $firstN2 = & $providerN2
Test-Assert ($null -ne $firstN2) "sanity check: the first candidate was returned"
# Simulate the mode-3 worker's own zip-then-delete of the returned candidate.
Remove-Item -LiteralPath $firstN2.Dir.FullName -Recurse -Force
# Drain the provider fully (matching Scenario N's own pattern) - the bug
# only surfaces once the stack is later POPPED back down to the deleted
# entry (LIFO), which doesn't happen until the tree is otherwise exhausted,
# not on the very next call.
# Drain the provider fully (matching Scenario N's own pattern), since the
# provider could come back to the deleted folder on any later call.
$resultsN2 = [System.Collections.Generic.List[string]]::new()
$callCountN2 = 0
while ($true) {
Expand Down Expand Up @@ -447,6 +445,31 @@ Test-Assert ($touchedO.Count -eq 2) ("both leaf directories were actually dispat
Test-Assert ($touchedO -contains $leaf1O -and $touchedO -contains $leaf2O) "both the specific expected directories were dispatched"
Write-Host ""

# ==============================================================================
# Scenario N3: the provider hands out folders in the order the file system
# lists them (alphabetical on NTFS) at every level - series, the volumes
# inside a series, and chapters - with a leaf sitting next to a series
# taking its own place in that order.
# ==============================================================================
Write-Host "=== Scenario N3: New-ZippableLeafDirProvider returns folders in order ===" -ForegroundColor Cyan
$rootN3 = New-Dir "scenario-n3"
foreach ($rel in @("A Series\Chapter 1", "A Series\Chapter 2", "B One-Shot", "C Series\Volume 1\Chapter 1", "C Series\Volume 2\Chapter 1", "D Series\Chapter 1")) {
New-FileIn -DirPath (New-Dir ("scenario-n3\" + $rel)) -Name "page1.jpg" | Out-Null
}
$providerN3 = New-ZippableLeafDirProvider -ScanPath $rootN3 -QualifyingExtensions $imgExts
$orderN3 = [System.Collections.Generic.List[string]]::new()
$callCountN3 = 0
while ($true) {
$callCountN3++
$next = & $providerN3
if ($null -eq $next) { break }
$orderN3.Add($next.Dir.FullName.Substring($rootN3.Length + 1))
if ($callCountN3 -gt 100) { throw "Scenario N3: provider did not terminate after 100 calls - possible infinite loop." }
}
$expectedN3 = "A Series\Chapter 1|A Series\Chapter 2|B One-Shot|C Series\Volume 1\Chapter 1|C Series\Volume 2\Chapter 1|D Series\Chapter 1"
Test-Assert (($orderN3 -join "|") -eq $expectedN3) ("series, volumes and chapters come out in order (got: " + ($orderN3 -join "|") + ")")
Write-Host ""

# ==============================================================================
# Scenario P: lightweight empirical signal (not a strict proof) that the
# incremental provider's first call returns without needing to finish
Expand Down
3 changes: 3 additions & 0 deletions _Harness/Lint.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ $script:LintScriptVarAllowed = @(
@{ Function = 'Write-LogLineToRunFiles'
Variables = @('FullLogging', 'logFile', 'logErrorFile', 'logWarnFile')
Why = 'Only called from Write-Log past its worker early-return and from Flush-ConsoleQueue (main thread). Listed in Get-LoggingSharedFunctionNames only because Rule 5 walks Write-Log''s callees statically.' }
@{ Function = 'Write-LogLineToFile'
Variables = @('logRunHeaderPending')
Why = 'Only called from Write-LogLineToRunFiles (main thread, see above). Same Rule 5 static-listing reason.' }
@{ Function = 'Invoke-MutexGuardedWrite'
Variables = @('logMutex')
Why = 'Only reached via Write-LogLineToRunFiles (main thread, see above) inside a worker''s propagated set. Same Rule 5 static-listing reason.' }
Expand Down
58 changes: 53 additions & 5 deletions _Harness/Logging.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,10 @@ Write-Host ""
# matching Write-SummaryLog's own append behavior,
# instead of being cleared at the start of every run: a previous run's
# own Error/Warn content survives a fresh Initialize-LogPaths call
# against the same target, and a "=== Run: ... ===" header is appended
# to mark where the new run's own content starts (via Start-LogRun,
# called separately from Initialize-LogPaths).
# against the same target, and a "=== Run: ... ===" header marks where
# the new run's own content starts (set up by Start-LogRun, called
# separately from Initialize-LogPaths, and written with the run's first
# line in that file).
# ==============================================================================
Write-Host "=== Scenario B: Initialize-LogPaths, split-log mode, previous run's content survives ===" -ForegroundColor Cyan
Reset-LoggingState
Expand All @@ -116,8 +117,55 @@ $bErrorContent = Get-Content -LiteralPath $priorErrorPath -Raw
$bWarnContent = Get-Content -LiteralPath $priorWarnPath -Raw
Test-Assert ($bErrorContent -like "*prior run's error content*") "prior run's error content survived - NOT deleted"
Test-Assert ($bWarnContent -like "*prior run's warn content*") "prior run's warn content survived - NOT deleted"
Test-Assert ($bErrorContent -like "*=== Run: *") "a run-separator header was appended to the Errors file"
Test-Assert ($bWarnContent -like "*=== Run: *") "a run-separator header was appended to the Warnings file"
Test-Assert ($bErrorContent -notlike "*=== Run: *") "no run header in the Errors file before this run has logged an error"
Test-Assert ($bWarnContent -notlike "*=== Run: *") "no run header in the Warnings file before this run has logged a warning"
Write-Log "b's own error" -Level Error
Write-Log "b's own second error" -Level Error
$bErrorLines = @(Get-Content -LiteralPath $priorErrorPath)
Test-Assert ($bErrorLines.Count -eq 4 -and $bErrorLines[1] -like "=== Run: *" -and $bErrorLines[2] -like "*b's own error*" -and $bErrorLines[3] -like "*b's own second error*") ("the run header is written once, right before the run's first error (got: " + ($bErrorLines -join " / ") + ")")
Test-Assert ((Get-Content -LiteralPath $priorWarnPath -Raw) -eq $bWarnContent) "an error leaves the Warnings file alone"
Write-Host ""

# ==============================================================================
# Scenario B2: a run with no warnings or errors leaves no Errors/Warnings
# file behind (and doesn't touch an existing one), and a run with only
# warnings creates only the Warnings file.
# ==============================================================================
Write-Host "=== Scenario B2: no Errors/Warnings file unless there's something to put in it ===" -ForegroundColor Cyan
Reset-LoggingState
Initialize-LogPaths -TargetPath "C:\B2\Path" -FullLogging $false -ScriptDir $scratchDir
Start-LogRun
Write-Log "b2 info" -Level Info
Complete-LogRun
Test-Assert (-not (Test-Path -LiteralPath $script:logErrorFile)) "a clean run creates no Errors file"
Test-Assert (-not (Test-Path -LiteralPath $script:logWarnFile)) "a clean run creates no Warnings file"

Write-Log "b2 warning between runs" -Level Warn
$b2BetweenRuns = @(Get-Content -LiteralPath $script:logWarnFile)
Test-Assert ($b2BetweenRuns.Count -eq 1) ("a warning logged after the run finished doesn't get that run's header (got " + $b2BetweenRuns.Count + " lines)")

Start-LogRun
Write-Log "b2 warning" -Level Warn
Complete-LogRun
Test-Assert (-not (Test-Path -LiteralPath $script:logErrorFile)) "a run with only warnings creates no Errors file"
$b2WarnLines = @(Get-Content -LiteralPath $script:logWarnFile)
Test-Assert ($b2WarnLines.Count -eq 3 -and $b2WarnLines[0] -like "=== Run: *" -and $b2WarnLines[1] -like "*b2 warning" -and $b2WarnLines[2] -like "*between runs*") ("the warning run's header and line are on top (got: " + ($b2WarnLines -join " / ") + ")")

$b2Old = [System.DateTime]::UtcNow.AddDays(-1)
[System.IO.File]::SetLastWriteTimeUtc($script:logWarnFile, $b2Old)
Start-LogRun
Complete-LogRun
Test-Assert ([System.IO.File]::GetLastWriteTimeUtc($script:logWarnFile) -eq $b2Old) "a clean run doesn't touch an existing Warnings file"

Reset-LoggingState
Initialize-LogPaths -TargetPath "C:\B2\Locked" -FullLogging $false -ScriptDir $scratchDir
Initialize-LogMutex
Start-LogRun
$b2Lock = [System.IO.File]::Open($script:logErrorFile, [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
try { Write-Log "b2 lost error" -Level Error } finally { $b2Lock.Close() }
Write-Log "b2 kept error" -Level Error
$b2ErrLines = @(Get-Content -LiteralPath $script:logErrorFile)
Test-Assert ($b2ErrLines.Count -eq 2 -and $b2ErrLines[0] -like "=== Run: *" -and $b2ErrLines[1] -like "*b2 kept error*") ("a failed first write keeps the header for the next line that does get written (got: " + ($b2ErrLines -join " / ") + ")")
Write-Host ""

# ==============================================================================
Expand Down
Loading
Loading