Files
plak/Sources/PlakCore/Page/PagePruning.swift
T
2026-11-25 07:14:49 +01:00

40 lines
1.7 KiB
Swift

import Foundation
extension PageFile {
/// The number of days a block stays in the page after its created date.
public static let keptDays = 14
/// The page without the blocks created more than `keptDays` calendar days before `now`, and without undated blocks.
///
/// A fenced block is one line, so it goes or stays whole. The blank lines above a removed block go with it.
public func pruned(now: Date, timeZone: TimeZone = .current) -> PageFile {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
guard let cutoff = calendar.date(byAdding: .day, value: -Self.keptDays, to: now) else { return self }
let blocks = self.blocks
let keeps = blocks.map { block in dates[block.lowerBound].map { $0 >= cutoff } ?? false }
guard keeps.contains(false) else { return self }
guard let first = blocks.first, let last = blocks.last, keeps.contains(true) else { return PageFile() }
var keptLines = Array(lines[..<first.lowerBound])
var keptDates: [Int: Date] = [:]
var hasBlock = false
for (index, block) in blocks.enumerated() where keeps[index] {
if hasBlock { keptLines += lines[blocks[index - 1].upperBound..<block.lowerBound] }
keptDates[keptLines.count] = dates[block.lowerBound]
keptLines += lines[block]
hasBlock = true
}
keptLines += lines[last.upperBound...]
return PageFile(lines: keptLines, dates: keptDates)
}
/// The paths of every image line, as `images/<name>`.
public var imagePaths: Set<String> {
Set(lines.compactMap { line in
if case let .image(path) = line { return path }
return nil
})
}
}