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
114 changes: 62 additions & 52 deletions Modules/LeafDirectoryDiscovery.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,19 @@ function Test-ZippableLeafDirCandidate {
}
} catch { }

if ($existingZipsHere.Count -gt 0) {
Write-Log ("SKIPPING '" + $Dir.FullName + "' as a zip candidate: contains " + $existingZipsHere.Count + " existing .zip file(s) directly inside it - likely a container folder left behind after its subfolders were individually zipped, not a genuine leaf. Not zipping to avoid archiving those .zip files into a wrapper.") -Level Warn
return $null
}
if ($qualifyingFiles.Count -eq 0) { return $null }
# A folder whose only images are cover.* is a series folder holding its
# cover, not a chapter.
$hasPage = $false
foreach ($f in $qualifyingFiles) {
if ([System.IO.Path]::GetFileNameWithoutExtension($f.Name) -ine 'cover') { $hasPage = $true; break }
}

if ($existingZipsHere.Count -gt 0) {
# Without pages this is a finished series, normal on every later run.
$skipLevel = if ($hasPage) { "Warn" } else { "Info" }
Write-Log ("SKIPPING '" + $Dir.FullName + "' as a zip candidate: contains " + $existingZipsHere.Count + " existing .zip file(s) directly inside it - likely a container folder left behind after its subfolders were individually zipped, not a genuine leaf. Not zipping to avoid archiving those .zip files into a wrapper.") -Level $skipLevel
return $null
}
if (-not $hasPage) { return $null }

$zipOut = [System.IO.Path]::Combine($Dir.Parent.FullName, $Dir.Name + ".zip")
Expand Down Expand Up @@ -123,54 +125,61 @@ function Get-ZippableLeafDirs {
throw ("Get-ZippableLeafDirs: -ScanPath does not exist or is not a directory: '" + $ScanPath + "'")
}

$results = [System.Collections.Generic.List[hashtable]]::new()
$dirStack = [System.Collections.Generic.Stack[string]]::new()
$dirStack.Push($ScanPath)

while ($dirStack.Count -gt 0) {
$currentDir = $dirStack.Pop()
$enumerator = $null
try {
$enumerator = [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
continue
}
$results = [System.Collections.Generic.List[hashtable]]::new()
# One open enumerator per folder level. A subfolder is walked to its end
# before the next sibling, so folders come out in listing order.
# DOCUMENTED DUPLICATE of New-ZippableLeafDirProvider's walk below - keep both in sync.
$enumeratorStack = [System.Collections.Generic.Stack[object]]::new()
$nextDir = $ScanPath

try {
while ($true) {
$hasNext = $false
try {
while ($true) {
if ($null -ne $nextDir) {
$currentDir = $nextDir
$nextDir = $null
try {
$hasNext = $enumerator.MoveNext()
$enumeratorStack.Push(@{ Path = $currentDir; Enumerator = [System.IO.Directory]::EnumerateDirectories($currentDir).GetEnumerator() })
} catch {
Write-Log ("Leaf-directory scan hit an error partway through '" + $currentDir + "' - skipping the rest of it, continuing with the rest of the tree: " + $_) -Level Warn
break
}
if (-not $hasNext) { break }

$childPath = $enumerator.Current
$dirInfo = [System.IO.DirectoryInfo]::new($childPath)
# Reparse-point guard - see
# Get-FilesRecursiveSafe above for the failure mode
# (a self-pointing junction produces 64
# duplicate candidates for the same physical folder).
# Skipped entirely, not just excluded from recursion - a
# junction/symlink isn't real content this location owns,
# so it's neither a leaf candidate nor safe to descend
# into. DOCUMENTED DUPLICATE, keep in sync with the other
# four copies in this file.
if (($dirInfo.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { continue }
$candidate = Test-ZippableLeafDirCandidate -Dir $dirInfo -QualifyingExtensions $QualifyingExtensions `
-ExcludeStagingDirs $ExcludeStagingDirs -ForceRezip $ForceRezip
if ($null -ne $candidate) {
$results.Add($candidate)
} else {
$dirStack.Push($childPath)
Write-Log ("Could not enumerate '" + $currentDir + "' during leaf-directory scan - skipping it, continuing with the rest of the tree: " + $_) -Level Warn
}
}
} finally {
$enumerator.Dispose()
if ($enumeratorStack.Count -eq 0) { break }

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

$childPath = $top.Enumerator.Current
$dirInfo = [System.IO.DirectoryInfo]::new($childPath)
# Reparse-point guard - see
# Get-FilesRecursiveSafe above for the failure mode
# (a self-pointing junction produces 64
# duplicate candidates for the same physical folder).
# Skipped entirely, not just excluded from recursion - a
# junction/symlink isn't real content this location owns,
# so it's neither a leaf candidate nor safe to descend
# into. DOCUMENTED DUPLICATE, keep in sync with the other
# four copies in this file.
if (($dirInfo.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { continue }
$candidate = Test-ZippableLeafDirCandidate -Dir $dirInfo -QualifyingExtensions $QualifyingExtensions `
-ExcludeStagingDirs $ExcludeStagingDirs -ForceRezip $ForceRezip
if ($null -ne $candidate) {
$results.Add($candidate)
} else {
$nextDir = $childPath
}
}
} finally {
foreach ($e in $enumeratorStack) { $e.Enumerator.Dispose() }
}

return ,$results
Expand All @@ -192,6 +201,7 @@ function New-ZippableLeafDirProvider {

# One open enumerator per folder level. A subfolder is walked to its end
# before the next sibling, so folders come out in listing order.
# DOCUMENTED DUPLICATE of Get-ZippableLeafDirs's walk above - keep both in sync.
$enumeratorStack = [System.Collections.Generic.Stack[object]]::new()
$state = @{ NextDir = $ScanPath }

Expand All @@ -201,7 +211,7 @@ function New-ZippableLeafDirProvider {
$currentDir = $state.NextDir
$state.NextDir = $null
try {
$enumeratorStack.Push([System.IO.Directory]::EnumerateDirectories($currentDir).GetEnumerator())
$enumeratorStack.Push(@{ Path = $currentDir; Enumerator = [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
}
Expand All @@ -211,18 +221,18 @@ function New-ZippableLeafDirProvider {
$top = $enumeratorStack.Peek()
$hasNext = $false
try {
$hasNext = $top.MoveNext()
$hasNext = $top.Enumerator.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
Write-Log ("Leaf-directory scan hit an error partway through '" + $top.Path + "' - skipping the rest of it, continuing with the rest of the tree: " + $_) -Level Warn
}

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

$childPath = $top.Current
$childPath = $top.Enumerator.Current

$dirInfo = [System.IO.DirectoryInfo]::new($childPath)
# Reparse-point guard - DOCUMENTED
Expand Down
2 changes: 1 addition & 1 deletion Modules/ZipPipeline.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ function Invoke-ZipOnlyPipeline {
if ($totals.Aborted) {
Write-Log "Zip-only: aborted before any leaf directory was found." -Level Warn
} else {
Write-Log "Zip-only: no qualifying leaf directories found." -Level Warn
Write-Log "Zip-only: no qualifying leaf directories found."
}
return $totals
}
Expand Down
28 changes: 25 additions & 3 deletions _Harness/LeafDirectoryDiscovery.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@ $ErrorActionPreference = "Stop"
# its own inline copies, so all four need a stub defined BEFORE it's
# dot-sourced, same as Write-Log below.
$script:logMessages = [System.Collections.Generic.List[string]]::new()
$script:logLeveled = [System.Collections.Generic.List[string]]::new()
function Write-Log {
param([string]$Message, [string]$Level = "Info")
$script:logMessages.Add($Message)
$script:logLeveled.Add("[" + $Level + "] " + $Message)
Write-Host (" [log:" + $Level + "] " + $Message) -ForegroundColor DarkGray
}
function Test-AbortSignal { return $false } # Scenario O never triggers an abort
Expand Down Expand Up @@ -113,7 +115,9 @@ Write-Host ""

# ==============================================================================
# Scenario C: former-container guard - a leaf-shaped dir containing an
# existing .zip (and no qualifying files) is skipped, with a Warn log.
# existing .zip (and no qualifying files) is skipped, with an Info log: that's
# a series whose chapters are all zipped, normal on every later run. With
# page images loose next to the .zip it's a Warn - those won't be zipped.
# ==============================================================================
Write-Host "=== Scenario C: former-container guard (basic) ===" -ForegroundColor Cyan
$rootC = New-Dir "scenario-c"
Expand All @@ -123,7 +127,19 @@ $script:logMessages.Clear()

$resultC = Get-ZippableLeafDirs -ScanPath $rootC -QualifyingExtensions $imgExts
Test-Assert ($resultC.Count -eq 0) "a folder containing only a .zip is not treated as a zip candidate"
Test-Assert (($script:logMessages | Where-Object { $_ -like "*SKIPPING*existing .zip*" }).Count -eq 1) "a Warn-level skip message was logged explaining why"
Test-Assert (($script:logMessages | Where-Object { $_ -like "*SKIPPING*existing .zip*" }).Count -eq 1) "a skip message was logged explaining why"
Test-Assert (@($script:logLeveled | Where-Object { $_ -like "*Old Chapter*existing .zip*" -and $_ -notlike "``[Info``]*" }).Count -eq 0) "a finished series is logged at Info, not as a warning"

$dirC2 = New-Dir "scenario-c\Finished With Cover"
New-FileIn -DirPath $dirC2 -Name "Chapter 1.zip" | Out-Null
New-FileIn -DirPath $dirC2 -Name "cover.jpg" | Out-Null
$dirC3 = New-Dir "scenario-c\Loose Pages"
New-FileIn -DirPath $dirC3 -Name "Chapter 1.zip" | Out-Null
New-FileIn -DirPath $dirC3 -Name "page1.jpg" | Out-Null
$resultC2 = Get-ZippableLeafDirs -ScanPath $rootC -QualifyingExtensions $imgExts
Test-Assert ($resultC2.Count -eq 0) "neither is a zip candidate"
Test-Assert (@($script:logLeveled | Where-Object { $_ -like "``[Info``]*Finished With Cover*existing .zip*" }).Count -eq 1) "a finished series with only its cover next to the zips is logged at Info"
Test-Assert (@($script:logLeveled | Where-Object { $_ -like "``[Warn``]*Loose Pages*existing .zip*" }).Count -eq 1) "page images loose next to a .zip still get a warning"
Write-Host ""

# ==============================================================================
Expand Down Expand Up @@ -446,7 +462,7 @@ Test-Assert ($touchedO -contains $leaf1O -and $touchedO -contains $leaf2O) "both
Write-Host ""

# ==============================================================================
# Scenario N3: the provider hands out folders in the order the file system
# Scenario N3: both scans hand 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.
Expand All @@ -468,6 +484,12 @@ while ($true) {
}
$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 "|") + ")")
$batchN3 = Get-ZippableLeafDirs -ScanPath $rootN3 -QualifyingExtensions $imgExts
$batchOrderN3 = @($batchN3 | ForEach-Object { $_.Dir.FullName.Substring($rootN3.Length + 1) }) -join "|"
Test-Assert ($batchOrderN3 -eq $expectedN3) ("the batch scan gives the same order (got: " + $batchOrderN3 + ")")
$volumesN3 = Get-SeriesChapters -SeriesPath (Join-Path $rootN3 "C Series") -QualifyingExtensions $imgExts
$volumeOrderN3 = @($volumesN3 | ForEach-Object { $_.Dir.Parent.Name }) -join "|"
Test-Assert ($volumeOrderN3 -eq "Volume 1|Volume 2") ("so a series' chapters are in volume order (got: " + $volumeOrderN3 + ")")
Write-Host ""

# ==============================================================================
Expand Down
14 changes: 11 additions & 3 deletions _Harness/ZipPipeline.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -199,13 +199,21 @@ if (Test-Path -LiteralPath $zipA3) {
Write-Host ""

# ==============================================================================
# Scenario B: no qualifying leaf directories - all totals stay zero, a
# clear warning is logged, no error.
# Scenario B: no qualifying leaf directories - all totals stay zero, an
# Info line says so, and nothing goes to the Warnings or Errors log (it's
# what a re-run on a finished library looks like).
# ==============================================================================
Write-Host "=== Scenario B: no candidates found ===" -ForegroundColor Cyan
$rootB = New-Dir "scenario-b-empty"

$totalsB = Invoke-ZipOnlyPipeline -Path $rootB -MaxParallel 2 -PermanentDelete $true
New-FileIn -DirPath (New-Dir "scenario-b-empty\Finished Series") -Name "Chapter 1.zip" | Out-Null
$warnLengthB = if (Test-Path -LiteralPath $script:logWarnFile) { (Get-Item -LiteralPath $script:logWarnFile).Length } else { 0 }
$totalsB = $null
$outputB = @(& { $script:totalsB = Invoke-ZipOnlyPipeline -Path $rootB -MaxParallel 2 -PermanentDelete $true } 6>&1 | ForEach-Object { "$_" })
$totalsB = $script:totalsB
$warnLengthAfterB = if (Test-Path -LiteralPath $script:logWarnFile) { (Get-Item -LiteralPath $script:logWarnFile).Length } else { 0 }
Test-Assert (@($outputB | Where-Object { $_ -like "*``[Info``] Zip-only: no qualifying leaf directories found." }).Count -eq 1) "the run says it found nothing to zip"
Test-Assert ($warnLengthAfterB -eq $warnLengthB) "a finished series adds nothing to the Warnings log"
Test-Assert ($totalsB.CandidateCount -eq 0) "0 candidates found in an empty tree"
Test-Assert ($totalsB.ZippedSuccess -eq 0 -and $totalsB.ZippedFail -eq 0) "no zip attempts were made"
Write-Host ""
Expand Down
6 changes: 3 additions & 3 deletions module-descriptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -392,9 +392,9 @@ 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. 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. |
| `Get-ZippableLeafDirs` | Eager scan under a path. Returns a `List[hashtable]` of `@{ Dir; ZipOut }` for every folder that should be zipped, 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. |
| `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 same order as above. 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. A folder with a `.zip` directly in it is never a candidate either: that's logged at Info for a finished series (no page images), and as a warning when page images sit next to the `.zip`. 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). |
| `Get-SeriesChapters` | Runs `Get-ZippableLeafDirs` on one series and returns its chapters; on failure it logs a warning and returns an empty list. |
Expand Down
Loading