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
6 changes: 6 additions & 0 deletions Sources/BoostKit/LargeFileEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public final class LargeFileEngine: ObservableObject {
@Published public var selection: Set<String> = []
@Published public private(set) var lastScan: Date?
@Published public private(set) var capped = false
@Published public private(set) var cappedFolders: [String] = []
@Published public private(set) var matches = 0
@Published public private(set) var skippedRecent = 0
@Published public var report: String?
Expand Down Expand Up @@ -85,6 +86,7 @@ public final class LargeFileEngine: ObservableObject {

self.items = result.items
self.capped = result.capped
self.cappedFolders = result.cappedFolders
self.matches = result.matches
self.skippedRecent = result.skippedRecent
// Nothing is ticked for you. These are your own files; opting in
Expand Down Expand Up @@ -140,6 +142,10 @@ public final class LargeFileEngine: ObservableObject {
self.selection.subtract(gone)
self.matches = max(self.items.count, self.matches - r.moved)
self.trashing = false
// The list held only the largest files. When it is now empty but
// more matched, the next ones are still there: look again instead
// of saying there is nothing.
if self.items.isEmpty && self.matches > 0 { self.scan() }
}
}

Expand Down
41 changes: 35 additions & 6 deletions Sources/BoostKit/LargeFileScan.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ public struct LargeFileScanResult: Sendable {
/// True when the walk hit its entry cap before finishing. The list is then
/// incomplete and the UI must say so.
public var capped = false
/// The folders whose share of the walk ran out, so the notice can name
/// exactly what was not fully read.
public var cappedFolders: [String] = []
public var visited = 0
/// Over the size threshold but changed in the last minute, so probably
/// still being written.
Expand Down Expand Up @@ -117,6 +120,16 @@ public enum LargeFileScan {
bundleExtensions.contains((name as NSString).pathExtension.lowercased())
}

/// Where Music and TV keep their media when the library is a plain folder
/// rather than a package. Removing a track from here leaves the app
/// showing it as missing, so these are never listed.
static let appLibraryFolders: Set<String> = ["Media.localized", "iTunes Media"]

/// A folder the scan treats as one opaque item.
static func isOpaqueFolder(_ name: String) -> Bool {
isBundleName(name) || appLibraryFolders.contains(name)
}

private static var fm: FileManager { .default }

// MARK: - Roots
Expand Down Expand Up @@ -151,9 +164,14 @@ public enum LargeFileScan {
/// external disk is not scanned.
public static func isAcceptableRoot(_ url: URL, home: URL? = nil) -> Bool {
guard ProjectScan.isAcceptableRoot(url, home: home) else { return false }
let parts = ProjectScan.canonical(url).pathComponents
let canonical = ProjectScan.canonical(url)
let parts = canonical.pathComponents
if parts.count > 1, parts[1] == "Volumes" { return false }
return true
// A personal folder that is really a link somewhere else, such as
// another user's folder or /private/tmp, is not scanned. It has to
// resolve to somewhere inside your home folder.
let h = ProjectScan.canonical(home ?? fm.homeDirectoryForCurrentUser)
return ProjectScan.isInside(canonical, of: h)
}

private static func isAcceptableHome(_ url: URL) -> Bool {
Expand Down Expand Up @@ -200,17 +218,28 @@ public enum LargeFileScan {
roots.deep.map { (ProjectScan.canonical($0), false) }
+ roots.shallow.map { (ProjectScan.canonical($0), true) }

walk: for (root, shallow) in walks {
for (index, walkRoot) in walks.enumerated() {
let (root, shallow) = walkRoot
if isCancelled() { result.cancelled = true; return result }
// Each folder gets an equal share of what is left, and a folder
// that uses less hands the rest on. One huge Documents tree cannot
// starve Movies, Music and Pictures.
let budget = max(1, (maxEntries - visited) / (walks.count - index))
var rootVisited = 0
guard let e = fm.enumerator(
at: root, includingPropertiesForKeys: keys,
options: [.skipsHiddenFiles, .skipsPackageDescendants]
) else { continue }

for case let url as URL in e {
visited += 1
rootVisited += 1
if visited % 256 == 0, isCancelled() { result.cancelled = true; return result }
if visited > maxEntries { result.capped = true; break walk }
if rootVisited > budget {
result.capped = true
result.cappedFolders.append(root.lastPathComponent)
break
}

guard let v = try? url.resourceValues(forKeys: keySet) else { continue }
if v.isSymbolicLink == true { e.skipDescendants(); continue }
Expand All @@ -223,7 +252,7 @@ public enum LargeFileScan {
if v.isDirectory == true {
// A bundle is one opaque item, and a shallow root never
// goes below its top level.
if shallow || v.isPackage == true || isBundleName(name) { e.skipDescendants() }
if shallow || v.isPackage == true || isOpaqueFolder(name) { e.skipDescendants() }
continue
}
guard v.isRegularFile == true else { continue }
Expand Down Expand Up @@ -342,7 +371,7 @@ public enum LargeFileScan {
}
let below = Array(resolved.pathComponents.dropFirst(root.pathComponents.count))
if below.contains(where: { $0.hasPrefix(".") }) { return .refused("hidden") }
if below.dropLast().contains(where: isBundleName) { return .refused("inside a bundle") }
if below.dropLast().contains(where: isOpaqueFolder) { return .refused("inside a bundle or media library") }

guard let modified = v.contentModificationDate else { return .refused("no date") }
if now.timeIntervalSince(modified) < recentWindow { return .tooRecent }
Expand Down
4 changes: 3 additions & 1 deletion Sources/BoostKit/LargeFileView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,9 @@ struct LargeFileView: View {

@ViewBuilder private var notices: some View {
if engine.capped {
notice("Stopped early because these folders hold a very large number of items. "
let named = engine.cappedFolders.isEmpty ? "these folders"
: engine.cappedFolders.joined(separator: ", ")
notice("Stopped early in \(named) because they hold a very large number of items. "
+ "The list may be incomplete.")
}
if engine.matches > engine.items.count {
Expand Down
2 changes: 1 addition & 1 deletion Sources/BoostKit/MemoryReport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ enum MemoryReport {

if !apps.isEmpty {
lines.append("")
lines.append("Biggest apps")
lines.append("Biggest apps (system and command line processes left out)")
for app in apps { lines.append(" \(app.name) \(fmtBytes(app.bytes))") }
}

Expand Down
12 changes: 12 additions & 0 deletions Sources/BoostKit/Snapshot.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ public enum Snapshot {
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
_ = NSApplication.shared
NSApp.setActivationPolicy(.accessory)
// The render borrows a few settings. They are put back before exit so
// running it on your own Mac does not change your preferences.
let borrowed = ["firstRunDismissed", "projectCutoffDays", "historyRange", "selectedTab"]
let original = borrowed.map { ($0, UserDefaults.standard.object(forKey: $0)) }
func restoreSettings() {
for (key, value) in original {
if let value { UserDefaults.standard.set(value, forKey: key) }
else { UserDefaults.standard.removeObject(forKey: key) }
}
UserDefaults.standard.synchronize()
}
// Screenshots show the app as it looks once the welcome card is gone.
UserDefaults.standard.set(true, forKey: "firstRunDismissed")
UserDefaults.standard.set(30, forKey: "projectCutoffDays")
Expand Down Expand Up @@ -47,6 +58,7 @@ public enum Snapshot {
settle: tab == .memory ? 3.0 : 12.0, to: directory)
}
}
restoreSettings()
exit(0)
}

Expand Down
48 changes: 48 additions & 0 deletions Tests/BoostKitTests/LargeFileScanTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -545,3 +545,51 @@ struct LargeFileRootTests {
#expect(!LargeFileScan.isAcceptableRoot(home, home: home))
}
}

@Suite("Large files: review fixes")
struct LargeFileReviewFixTests {

@Test("Music and TV library folders are never listed", arguments: ["Media.localized", "iTunes Media"])
func appLibrariesSkipped(folder: String) throws {
let root = try makeRoot(); defer { try? fm.removeItem(at: root) }
try makeFile(root.appending(path: "Music/\(folder)/Album/track.m4a"))
let loose = try makeFile(root.appending(path: "Music/loose-recording.wav"))

#expect(paths(scan(root)) == [loose.path])
}

@Test("A file inside a media library is refused at trash time too", arguments: ["Media.localized", "iTunes Media"])
func appLibraryRefusedAtVerify(folder: String) throws {
let root = try makeRoot(); defer { try? fm.removeItem(at: root) }
let track = try makeFile(root.appending(path: "Music/\(folder)/track.m4a"))
let item = LargeFileItem(url: track, bytes: 300 * 1024, lastAccessed: nil,
lastModified: try fm.attributesOfItem(atPath: track.path)[.modificationDate] as? Date)
let verdict = LargeFileScan.verify(item, roots: LargeFileRoots(deep: [root]))
#expect(verdict != .ok)
}

@Test("One huge folder cannot use up the whole budget")
func budgetIsShared() throws {
let first = try makeRoot(); defer { try? fm.removeItem(at: first) }
let second = try makeRoot(); defer { try? fm.removeItem(at: second) }
for i in 0..<60 { try makeFile(first.appending(path: "f\(i).bin"), kbSize: 1) }
let late = try makeFile(second.appending(path: "late.mov"))

let r = LargeFileScan.scan(roots: LargeFileRoots(deep: [first, second]), minBytes: threshold,
maxEntries: 40)
#expect(paths(r) == [late.path])
#expect(r.capped)
#expect(r.cappedFolders == [first.lastPathComponent])
}

@Test("A personal folder that links outside home is not accepted")
func linkOutsideHomeRefused() throws {
let home = try makeRoot(); defer { try? fm.removeItem(at: home) }
let elsewhere = try makeRoot(); defer { try? fm.removeItem(at: elsewhere) }
try fm.createDirectory(at: home.appending(path: "Documents"), withIntermediateDirectories: true)
try fm.createSymbolicLink(at: home.appending(path: "Downloads"), withDestinationURL: elsewhere)

#expect(LargeFileScan.isAcceptableRoot(home.appending(path: "Documents"), home: home))
#expect(!LargeFileScan.isAcceptableRoot(home.appending(path: "Downloads"), home: home))
}
}
2 changes: 1 addition & 1 deletion Tests/BoostKitTests/MemoryReportTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ struct MemoryReportTests {
MemoryReport.App(name: "Claude", bytes: 4 * gb)]
let text = MemoryReport.text(version: "1.3.0", machine: machine, mem: mem(), apps: apps,
pausedCount: 2, history: nil, now: now)
#expect(text.contains("Biggest apps\n Safari 700 MB\n Claude 4.00 GB"))
#expect(text.contains("Biggest apps (system and command line processes left out)\n Safari 700 MB\n Claude 4.00 GB"))
#expect(text.contains("Paused apps: 2"))
#expect(!text.contains("/Users"))
#expect(!text.contains(NSUserName()))
Expand Down
Loading