diff --git a/Modules/LeafDirectoryDiscovery.ps1 b/Modules/LeafDirectoryDiscovery.ps1 index e53afc7..16135c5 100644 --- a/Modules/LeafDirectoryDiscovery.ps1 +++ b/Modules/LeafDirectoryDiscovery.ps1 @@ -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 @@ -238,7 +236,7 @@ function New-ZippableLeafDirProvider { -ExcludeStagingDirs $ExcludeStagingDirs -ForceRezip $ForceRezip if ($null -ne $candidate) { return $candidate } - $dirStack.Push($childPath) + $state.NextDir = $childPath } }.GetNewClosure() } diff --git a/Modules/Logging.ps1 b/Modules/Logging.ps1 index ca38950..1908013 100644 --- a/Modules/Logging.ps1 +++ b/Modules/Logging.ps1 @@ -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 { @@ -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 } @@ -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. @@ -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. diff --git a/_Harness/LeafDirectoryDiscovery.Harness.ps1 b/_Harness/LeafDirectoryDiscovery.Harness.ps1 index 856218d..b6d6d65 100644 --- a/_Harness/LeafDirectoryDiscovery.Harness.ps1 +++ b/_Harness/LeafDirectoryDiscovery.Harness.ps1 @@ -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. # ============================================================================== @@ -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) { @@ -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 diff --git a/_Harness/Lint.Harness.ps1 b/_Harness/Lint.Harness.ps1 index d5b795a..44a15aa 100644 --- a/_Harness/Lint.Harness.ps1 +++ b/_Harness/Lint.Harness.ps1 @@ -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.' } diff --git a/_Harness/Logging.Harness.ps1 b/_Harness/Logging.Harness.ps1 index 4d59b8d..64ad721 100644 --- a/_Harness/Logging.Harness.ps1 +++ b/_Harness/Logging.Harness.ps1 @@ -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 @@ -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 "" # ============================================================================== diff --git a/module-descriptions.md b/module-descriptions.md index 12d6865..f576221 100644 --- a/module-descriptions.md +++ b/module-descriptions.md @@ -136,7 +136,7 @@ Console and log-file output for the whole tool. It picks the log file names for | `Write-Log` | Logs one message at `Info`, `Warn`, `Error` or `Summary`. `-ForceConsole` shows it on the console even with Clean Console Output on. In a worker runspace it queues the message instead of writing. Runs in workers. | | `Initialize-LogPaths` | Hashes the target path (SHA-256 of the lower-cased path; the first 10 hex characters go in file names) and sets the log file names in the script directory. Full logging: one `Conversion Log - - .log` per run. Otherwise fixed-name `Summary`, `Errors` and `Warnings` files per target (Summary skipped if disabled). | | `Initialize-LogMutex` | Creates the named system-wide mutex `JxlLogMutex_` that guards the log files. Takes `-PathHash` for callers (such as workers) that don't have the main thread's hash. | -| `Start-LogRun` / `Complete-LogRun` | Bracket one run on the main thread. Start writes a `=== Run: ===` header into the Errors and Warnings files and remembers their earlier content; Complete moves this run's new lines above that content so the newest run is on top. Both do nothing in full-logging mode. | +| `Start-LogRun` / `Complete-LogRun` | Bracket one run on the main thread. Start remembers the Errors and Warnings files' earlier content and readies a `=== Run: ===` header, which is written with the run's first line in each file; Complete moves this run's new lines above that content so the newest run is on top. Both do nothing in full-logging mode. | | `Write-SummaryLog` | Prepends one `=== Run ... === / === End of run ===` block to the Summary file. | | `Flush-ConsoleQueue` | Main thread only. Drains the worker queue: writes each item to the run's log files, then to the console. | | `Initialize-CleanConsoleOutput` | Sets whether `Write-Log` skips console echo for ordinary messages. | @@ -155,7 +155,7 @@ Console and log-file output for the whole tool. It picks the log file names for - Console colours: `Error` red, `Warn` yellow, `Summary` cyan, `Info` default. - All file writes go through `Invoke-MutexGuardedWrite`, which waits up to 10 seconds for the mutex. An abandoned mutex (previous holder died) counts as acquired. If the wait times out, the write is skipped and a warning is printed straight to the console rather than writing unguarded, since `Write-SummaryLog` and `Complete-LogRun` read and rewrite whole files. - A failed log write (locked file, antivirus, cloud sync) is never fatal. `Write-LogWriteFailureWarning` prints one console warning per file per run and the run carries on. -- Errors and Warnings files accumulate across runs, newest on top. `Start-LogRun` reads the file's existing text and appends the run header; `Complete-LogRun` later rewrites the file as this run's lines followed by the earlier text. If the file no longer starts with the earlier text, it is left as it is. Log files are UTF-8. +- Errors and Warnings files accumulate across runs, newest on top. `Start-LogRun` reads the file's existing text; the run header goes in with the run's first line in that file, so a run with nothing to report creates no file and leaves an existing one alone. `Complete-LogRun` later rewrites the file as this run's lines followed by the earlier text. If the file no longer starts with the earlier text, it is left as it is. Log files are UTF-8. - Messages about log problems (`Start-LogRun`, `Complete-LogRun`, `Write-SummaryLog`, the mutex timeout, write failures) go straight to the console and never through `Write-Log`, because `Write-Log` would write to the same file that just failed. **Things to watch out for** @@ -393,7 +393,7 @@ Finds the folders the tool works on: "leaf" chapter folders that should be zippe | Function | What it does | |---|---| | `Get-ZippableLeafDirs` | Eager scan under a path. Returns a `List[hashtable]` of `@{ Dir; ZipOut }` for every folder that should be zipped. Throws if the path doesn't exist. | -| `New-ZippableLeafDirProvider` | Same scan, but incremental: returns a scriptblock that yields one candidate per call and `$null` when finished, so zipping can start before a large tree is fully scanned. Throws if the path doesn't exist. | +| `New-ZippableLeafDirProvider` | Same scan, but incremental: returns a scriptblock that yields one candidate per call and `$null` when finished, so zipping can start before a large tree is fully scanned. Folders come out in the order the file system lists them, each subfolder walked to its end before the next one (alphabetical on NTFS). Throws if the path doesn't exist. | | `Test-ZippableLeafDirCandidate` | The decision for one folder: returns `@{ Dir; ZipOut }` if it should be zipped, otherwise `$null`. A folder whose only qualifying files are named `cover.*` is not a candidate (it's a series folder holding its cover), so Zip Folders never zips one. Shared by both scans above. | | `New-SeriesProvider` | Returns a scriptblock that yields one series folder (`DirectoryInfo`) per call, lazily, and `$null` at the end. Descends into category folders (see below). | | `Test-SeriesCategoryFolder` | True if a folder is a category folder (it holds series, not chapter content). |