Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
import ArgumentParser
import Foundation
@testable import PeelCommandLine
@testable import PeelCore
import Testing
/// Tests what the four cleaning commands (`caches`, `projects`, `duplicates`, and `orphans`) decide to move.
struct FileCommandTests {
private func command<Command: AsyncParsableCommand>(_ arguments: [String]) throws -> Command {
try #require(try PeelCommand.parseAsRoot(arguments) as? Command)
}
private func logs(in directory: borrowing TemporaryDirectory) -> (removals: RemovalLog, refusals: RefusalLog) {
(RemovalLog(url: directory.url.appending(path: "Peel/removals.json")),
RefusalLog(url: directory.url.appending(path: "Peel/refusals.json")))
}
private func service(in directory: borrowing TemporaryDirectory) throws -> TrashService {
let trash = try directory.directory("Trash")
return TrashService(
environment: SearchEnvironment(
homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),
rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
),
moveToTrash: { url in
let destination = trash.appending(path: UUID().uuidString)
try FileManager.default.moveItem(at: url, to: destination)
return destination
}
)
}
private func moved(_ logs: (removals: RemovalLog, refusals: RefusalLog)) async -> [String] {
(await logs.removals.load().records ?? []).map(\.originalURL.lastPathComponent).sorted()
}
// MARK: Developer caches
private func environment(
_ name: String,
id: String,
apps: [String] = [],
locations: [(String, DeveloperEnvironment.ContentKind)],
in directory: borrowing TemporaryDirectory
) throws -> DeveloperEnvironment {
DeveloperEnvironment(
id: id,
name: name,
systemImage: "hammer",
appBundleIdentifiers: apps,
locations: try locations.map { path, kind in
DeveloperEnvironment.Location(
url: try directory.file("home/\(path)/blob", bytes: 30).deletingLastPathComponent(),
kind: kind,
size: 30,
source: "https://example.com/\(path)"
)
}
)
}
@Test func narrowsTheCachesByNameOrIdentifier() throws {
let directory = try TemporaryDirectory()
let brew = try environment("Homebrew", id: "homebrew", locations: [("Library/Caches/Homebrew", .cache)], in: directory)
let cargo = try environment("Rust", id: "rust", locations: [("Library/Caches/cargo", .cache)], in: directory)
#expect(try CachesCommand.chosen(from: [brew, cargo], named: []).map(\.id) == ["homebrew", "rust"])
#expect(try CachesCommand.chosen(from: [brew, cargo], named: ["homebrew"]).map(\.id) == ["homebrew"])
#expect(try CachesCommand.chosen(from: [brew, cargo], named: ["RUST"]).map(\.id) == ["rust"])
#expect(try CachesCommand.chosen(from: [brew, cargo], named: ["Homebrew", "Rust"]).count == 2)
#expect(throws: CommandFailure.self) { try CachesCommand.chosen(from: [brew, cargo], named: ["Nonesuch"]) }
// A name that matches nothing beside one that does is a typo, never a tool with nothing to show.
let typo = #expect(throws: CommandFailure.self) {
try CachesCommand.chosen(from: [brew, cargo], named: ["rust", "hombrew"])
}
let hombrew = Output.quoted("hombrew")
#expect(typo?.description == "No developer caches of \(hombrew) were found. See `peel caches`.")
}
/// Model weights and installed packages are listed and never suggested, so `--remove` leaves them.
@Test func movesOnlyTheCachesItWouldSuggest() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let tool = try environment("Rust", id: "rust", locations: [
("Library/Caches/cargo", .cache),
("Library/Models/llama", .models),
("Library/Envs/venv", .environments),
], in: directory)
try await (command(["caches", "--remove", "-y"]) as CachesCommand)
.clean([tool], using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)
#expect(await moved(logs) == ["cargo"])
#expect(FileManager.default.fileExists(atPath: directory.url.appending(path: "home/Library/Models/llama").path(percentEncoded: false)))
}
@Test func anAppThatRunsHoldsNothingBackWhenNoneOfItsFoldersIsInThePlan() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let open = try environment(
"Finder Tools", id: "finder", apps: ["com.apple.finder"],
locations: [("Library/Application Support/models", .models)], in: directory
)
let closed = try environment("Rust", id: "rust", locations: [("Library/Caches/cargo", .cache)], in: directory)
#expect(open.runningApp == "Finder")
let collected = Output.Collected()
try await Output.$collected.withValue(collected) {
try await (command(["caches", "--remove", "-y"]) as CachesCommand)
.clean(
[open, closed],
using: try service(in: directory),
recordingIn: logs.removals,
refusals: logs.refusals
)
}
#expect(await moved(logs) == ["cargo"])
#expect(!collected.notes.contains("Quit Finder first"))
}
/// Nothing of a tool moves while its app runs, since the app writes in those folders: the Developer page waits,
/// and so does `peel caches`. Finder runs on every Mac, so it stands for an app that is open.
@Test func leavesTheCachesOfAnAppThatRuns() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let open = try environment("Finder Tools", id: "finder", apps: ["com.apple.finder"], locations: [("Library/Caches/finder-tool", .cache)], in: directory)
let closed = try environment("Rust", id: "rust", locations: [("Library/Caches/cargo", .cache)], in: directory)
#expect(open.runningApp == "Finder")
#expect(closed.runningApp == nil)
let collected = Output.Collected()
try await Output.$collected.withValue(collected) {
try await (command(["caches", "--remove", "-y"]) as CachesCommand)
.clean(
[open, closed],
using: try service(in: directory),
recordingIn: logs.removals,
refusals: logs.refusals
)
}
#expect(await moved(logs) == ["cargo"])
#expect(collected.notes.contains("Quit Finder first"))
#expect(FileManager.default.fileExists(atPath: directory.url.appending(path: "home/Library/Caches/finder-tool").path(percentEncoded: false)))
let alone = Output.Collected()
await #expect(throws: CommandFailure.self) {
try await Output.$collected.withValue(alone) {
try await (command(["caches", "--remove", "-y"]) as CachesCommand).clean(
[open], using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals
)
}
}
#expect(!alone.notes.contains("Quit Finder first"), "the error says it, once")
}
@Test func aDryRunOnCachesMovesNothing() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let tool = try environment("Rust", id: "rust", locations: [("Library/Caches/cargo", .cache)], in: directory)
try await (command(["caches", "--remove", "--dry-run"]) as CachesCommand)
.clean([tool], using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)
#expect(await moved(logs).isEmpty)
#expect(FileManager.default.fileExists(atPath: directory.url.appending(path: "home/Library/Caches/cargo").path(percentEncoded: false)))
}
// MARK: Build artifacts
@Test func movesOnlyTheBuildArtifactsItWouldSuggest() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let project = try directory.directory("home/Developer/App")
func artifact(_ name: String, lastActivity: Date) throws -> ProjectArtifact {
ProjectArtifact(
url: try directory.file("home/Developer/App/\(name)/blob", bytes: 20).deletingLastPathComponent(),
project: project,
name: name,
tool: "Xcode",
size: 20,
lastActivity: lastActivity,
hasGenericName: false,
isEnvironment: false
)
}
// A project untouched for longer than `recentlyActive` is suggested; one changed today is not.
let stale = try artifact("DerivedData", lastActivity: .now.addingTimeInterval(-ProjectArtifacts.recentlyActive * 2))
let fresh = try artifact("build", lastActivity: .now)
let developer = project.deletingLastPathComponent().path(percentEncoded: false)
let collected = Output.Collected()
try await Output.$collected.withValue(collected) {
try await (command(["projects", developer, "--remove", "-y"]) as ProjectsCommand)
.clean(
[stale, fresh],
using: try service(in: directory),
recordingIn: logs.removals,
refusals: logs.refusals
)
}
#expect(await moved(logs) == ["DerivedData"])
#expect(FileManager.default.fileExists(atPath: fresh.url.path(percentEncoded: false)))
#expect(collected.notes.contains("App/build stays: changed in the last 7 days"))
let onlyFresh = Output.Collected()
try await Output.$collected.withValue(onlyFresh) {
try await (command(["projects", developer, "--remove", "-y"]) as ProjectsCommand)
.clean([fresh], using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)
}
#expect(onlyFresh.output.contains("Nothing here is safe to suggest."))
#expect(onlyFresh.notes.contains("App/build stays: changed in the last 7 days"))
}
// MARK: Duplicates
/// So `--remove` never moves a small copy the app would not list, such as a license kept in several folders.
@Test func duplicatesLooksForTheCopiesTheAppLooksFor() throws {
let folders = [URL(filePath: "/Users/Shared", directoryHint: .isDirectory)]
let standard = try (command(["duplicates"]) as DuplicatesCommand).options(for: folders)
let everySize = try (command(["duplicates", "--min-size", "0"]) as DuplicatesCommand).options(for: folders)
let help = DuplicatesCommand.helpMessage(columns: 300)
#expect(standard == DuplicateScanOptions(folders: folders))
#expect(standard.minimumSize == DuplicateScanOptions.defaultMinimumSize)
#expect(everySize.minimumSize == 1)
#expect(help.contains("or 0 for every size. Without it, 100KB, as in the Peel app."))
#expect(ByteSize(argument: "100KB")?.bytes == DuplicateScanOptions.defaultMinimumSize)
}
/// One copy of every group is always kept, whether the group is of folders or of files.
@Test func keepsOneCopyOfEveryDuplicateGroup() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let contents = Data((0..<4_000).map { _ in UInt8.random(in: 0...255) })
for folder in ["home/Documents/Trip", "home/Pictures/Trip"] {
try directory.file("\(folder)/photo.jpg", contents: contents)
}
try directory.file("home/Documents/lonely.bin", contents: Data(repeating: 7, count: 4_000))
try directory.file("home/Documents/lonely copy.bin", contents: Data(repeating: 7, count: 4_000))
let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
let scan = try await DuplicateFinder(homeDirectory: home).scan(.everySize(in: [home]))
let keptFolder = try #require(scan.folderGroups.first?.folders.first?.url)
let keptFile = try #require(scan.groups.first?.files.first?.url)
try await (command(["duplicates", "--remove", "-y"]) as DuplicatesCommand)
.clean(scan, using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)
#expect(await moved(logs) == ["Trip", "lonely copy.bin"])
#expect(FileManager.default.fileExists(atPath: keptFolder.path(percentEncoded: false)))
#expect(FileManager.default.fileExists(atPath: keptFile.path(percentEncoded: false)))
}
@Test func aDryRunOnDuplicatesMovesNothing() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let contents = Data((0..<4_000).map { _ in UInt8.random(in: 0...255) })
try directory.file("home/Documents/a.bin", contents: contents)
try directory.file("home/Documents/a copy.bin", contents: contents)
let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
let scan = try await DuplicateFinder(homeDirectory: home).scan(.everySize(in: [home]))
try await (command(["duplicates", "--remove", "--dry-run"]) as DuplicatesCommand)
.clean(scan, using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)
#expect(await moved(logs).isEmpty)
#expect(FileManager.default.fileExists(atPath: directory.url.appending(path: "home/Documents/a copy.bin").path(percentEncoded: false)))
}
/// The plan says which copy of each group stays before it lists the copies that move: where the kept copy is
/// is what the decision rests on.
@Test func thePlanNamesTheCopyEachGroupKeeps() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let contents = Data((0..<4_000).map { _ in UInt8.random(in: 0...255) })
try directory.file("home/Documents/a.bin", contents: contents)
try directory.file("home/Documents/a copy.bin", contents: contents)
let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
let scan = try await DuplicateFinder(homeDirectory: home).scan(.everySize(in: [home]))
let kept = try #require(scan.groups.first?.files.first?.url)
let collected = Output.Collected()
try await Output.$collected.withValue(collected) {
try await (command(["duplicates", "--remove", "--dry-run"]) as DuplicatesCommand)
.clean(scan, using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)
}
let lines = collected.output.split(separator: "\n").map(String.init)
let keptLine = try #require(lines.firstIndex { $0.hasPrefix("keep") && $0.hasSuffix(Output.path(kept)) })
let movingLine = try #require(lines.firstIndex { !$0.hasPrefix("keep") && $0.hasSuffix("a copy.bin") })
#expect(keptLine < movingLine)
}
// MARK: Orphaned files
private func orphan(
_ name: String,
in directory: borrowing TemporaryDirectory,
heldBack: HoldBack? = nil,
requiresPrivileges: Bool = false
) throws -> OrphanItem {
OrphanItem(
url: try directory.file("home/Library/Application Support/\(name)/blob", bytes: 10).deletingLastPathComponent(),
kind: .applicationSupport,
size: 10,
modificationDate: .now,
requiresPrivileges: requiresPrivileges,
heldBack: heldBack
)
}
private func scanner(in directory: borrowing TemporaryDirectory) -> OrphanScanner {
OrphanScanner(
environment: SearchEnvironment(
homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),
rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
),
isRegisteredApp: { _ in false }
)
}
@Test func refusesAGroupItDoesNotHave() async throws {
let directory = try TemporaryDirectory()
let scan = OrphanScan(groups: [], unreadableLocations: [])
await #expect(throws: CommandFailure.self) {
try await (command(["orphans", "--remove", "com.example.gone", "-y"]) as OrphansCommand)
.clean(
"com.example.gone", in: scan, apps: [], remembered: [], scanner: scanner(in: directory),
using: try service(in: directory)
)
}
}
/// Only the named group moves, and within it only what Peel does not leave alone.
@Test func movesOneNamedGroupAndLeavesTheRest() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let wanted = OrphanGroup(identifier: "com.example.gone", items: [
try orphan("com.example.gone", in: directory),
try orphan("com.example.gone.documents", in: directory, heldBack: .holdsDocuments),
])
let other = OrphanGroup(identifier: "com.example.other", items: [try orphan("com.example.other", in: directory)])
let scan = OrphanScan(groups: [wanted, other], unreadableLocations: [])
try await (command(["orphans", "--remove", "COM.EXAMPLE.GONE", "-y"]) as OrphansCommand)
.clean(
"COM.EXAMPLE.GONE",
in: scan,
apps: [],
remembered: [],
scanner: scanner(in: directory),
using: try service(in: directory),
recordingIn: logs.removals,
refusals: logs.refusals
)
#expect(await moved(logs) == ["com.example.gone"])
#expect(FileManager.default.fileExists(atPath: wanted.items[1].url.path(percentEncoded: false)))
#expect(FileManager.default.fileExists(atPath: other.items[0].url.path(percentEncoded: false)))
}
@Test func thePlanOfAnUnsureGroupSaysWhy() {
var group = OrphanGroup(identifier: "com.example.gone", items: [])
#expect(OrphansCommand.unsureNote(for: group).isEmpty)
group.confidence = OrphanConfidence(level: .unsure, reasons: [.running("Example")])
#expect(OrphansCommand.unsureNote(for: group) == ["unsure: \(group.confidence.summary)"])
}
@Test func namesTheRemovalAsTheListNamesTheGroup() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
var group = OrphanGroup(identifier: "com.example.gone", items: [try orphan("com.example.gone", in: directory)])
group.rememberedApp = RememberedApp(
bundleIdentifier: "com.example.gone", name: "Gone", teamIdentifier: nil, lastSeen: .now,
lastPath: "/Applications/Gone.app"
)
let scan = OrphanScan(groups: [group], unreadableLocations: [])
try await (command(["orphans", "--remove", "com.example.gone", "-y"]) as OrphansCommand).clean(
"com.example.gone", in: scan, apps: [], remembered: [], scanner: scanner(in: directory),
using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals
)
#expect(await logs.removals.load().records?.map(\.source) == ["Gone"])
}
/// The command line never uses the helper, so what needs administrator access stays, is recorded as refused,
/// and, since nothing else moved, the command exits 1.
@Test func leavesWhatNeedsAdministratorAccessAndSaysSo() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let group = OrphanGroup(identifier: "com.example.gone", items: [
try orphan("com.example.gone", in: directory, requiresPrivileges: true),
])
let scan = OrphanScan(groups: [group], unreadableLocations: [])
let service = try service(in: directory)
await #expect(throws: ExitCode.failure) {
try await (command(["orphans", "--remove", "com.example.gone", "-y"]) as OrphansCommand).clean(
"com.example.gone", in: scan, apps: [], remembered: [], scanner: scanner(in: directory), using: service,
recordingIn: logs.removals, refusals: logs.refusals
)
}
#expect(await moved(logs).isEmpty)
#expect(await logs.refusals.load().records?.map(\.reason) == ["needs-helper"])
#expect(FileManager.default.fileExists(atPath: group.items[0].url.path(percentEncoded: false)))
}
/// When Peel leaves every file of the group alone, there is nothing to ask about and nothing is recorded as
/// refused.
@Test func saysSoWhenTheWholeGroupIsLeftAlone() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let group = OrphanGroup(identifier: "com.example.gone", items: [
try orphan("com.example.gone", in: directory, heldBack: .holdsALibrary),
])
let scan = OrphanScan(groups: [group], unreadableLocations: [])
let collected = Output.Collected()
try await Output.$collected.withValue(collected) {
try await (command(["orphans", "--remove", "com.example.gone", "-y"]) as OrphansCommand)
.clean(
"com.example.gone",
in: scan,
apps: [],
remembered: [],
scanner: scanner(in: directory),
using: try service(in: directory),
recordingIn: logs.removals,
refusals: logs.refusals
)
}
#expect(await moved(logs).isEmpty)
#expect(await logs.refusals.load().records?.isEmpty == true)
#expect(FileManager.default.fileExists(atPath: group.items[0].url.path(percentEncoded: false)))
#expect(collected.notes == "\(Output.path(group.items[0].url)) stays: holds a photo, music, or video library\n")
}
/// A folder with a wallet or a repository inside is moved only when chosen by hand in the app, so naming its
/// group moves the rest, says why it stays, and records no refusal, since nobody asked for it on its own.
@Test func leavesWhatIsHeldBackAndSaysWhy() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let group = OrphanGroup(identifier: "com.example.gone", items: [
try orphan("com.example.gone", in: directory),
try orphan("com.example.gone.wallet", in: directory, heldBack: .holdsAWallet),
])
let scan = OrphanScan(groups: [group], unreadableLocations: [])
let collected = Output.Collected()
try await Output.$collected.withValue(collected) {
try await (command(["orphans", "--remove", "com.example.gone", "-y"]) as OrphansCommand)
.clean(
"com.example.gone",
in: scan,
apps: [],
remembered: [],
scanner: scanner(in: directory),
using: try service(in: directory),
recordingIn: logs.removals,
refusals: logs.refusals
)
}
#expect(await moved(logs) == ["com.example.gone"])
#expect(await logs.refusals.load().records?.isEmpty == true)
#expect(FileManager.default.fileExists(atPath: group.items[1].url.path(percentEncoded: false)))
#expect(collected.notes == "\(Output.path(group.items[1].url)) stays: holds a wallet or a signing key\n")
}
// MARK: What the listings say
/// The note is the other half of `isRecommended`: a folder that is kept must say why, and one that is
/// suggested must not claim to be kept.
@Test func everyKeptFolderSaysWhyAndEverySuggestedOneDoesNot() throws {
let project = URL(filePath: "/Users/me/Developer/App", directoryHint: .isDirectory)
func artifact(
_ name: String,
size: Int64? = 20,
lastActivity: Date? = .now.addingTimeInterval(-ProjectArtifacts.recentlyActive * 2),
certain: Bool = true,
generic: Bool = false,
environment: Bool = false,
heldBack: HoldBack? = nil
) -> ProjectArtifact {
var artifact = ProjectArtifact(
url: project.appending(path: name),
project: project,
name: name,
tool: "Xcode",
size: size,
lastActivity: lastActivity,
hasGenericName: generic,
isEnvironment: environment,
heldBack: heldBack
)
artifact.lastActivityIsCertain = certain
return artifact
}
let cases: [(ProjectArtifact, String)] = [
(artifact("DerivedData"), "suggested"),
(artifact("fresh", lastActivity: .now), "changed in the last 7 days, kept"),
(artifact("huge", certain: false), "too large to tell when it last changed, kept"),
(artifact("venv", environment: true), "installed packages, kept"),
(artifact("build", generic: true), "a common folder name, kept"),
(artifact("slow", size: nil, heldBack: .notMeasured), "not measured in time, kept"),
(artifact("Carthage", heldBack: .holdsRepository), "holds a repository, kept"),
(artifact(".venv", certain: false, environment: true), "installed packages, kept"),
(artifact("target", lastActivity: .now, generic: true), "a common folder name, kept"),
]
for (artifact, note) in cases {
#expect(ProjectsCommand.note(for: artifact) == note)
#expect(artifact.isRecommended == (note == "suggested"), "\(artifact.name) says \(note)")
}
#expect(ProjectsCommand.rows(for: cases.map(\.0)).map(\.count) == cases.map { _ in 4 })
#expect(ProjectsCommand.rows(for: cases.map(\.0))[0] == ["20 bytes", "/Users/me/Developer/App/DerivedData", "Xcode", "suggested"])
let json = try Output.jsonText(ProjectsCommand.report(for: ProjectArtifacts.Scan(artifacts: cases.map(\.0))))
let report = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
let records = try #require(report["artifacts"] as? [[String: Any]])
#expect(records.map { $0["reason"] as? String ?? "suggested" } == cases.map {
$0.1 == "suggested" ? "suggested" : String($0.1.dropLast(", kept".count))
})
#expect(records[0]["reason"] is NSNull)
}
/// The first copy is the one Peel suggests keeping, and it is the only row marked.
@Test func marksOnlyTheCopyItSuggestsKeeping() async throws {
let directory = try TemporaryDirectory()
let contents = Data((0..<4_000).map { _ in UInt8.random(in: 0...255) })
try directory.file("home/Documents/a.bin", contents: contents)
try directory.file("home/Documents/a copy.bin", contents: contents)
try directory.file("home/Pictures/a.bin", contents: contents)
let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
let scan = try await DuplicateFinder(homeDirectory: home).scan(.everySize(in: [home]))
let group = try #require(scan.groups.first)
let rows = DuplicatesCommand.rows(for: group)
#expect(rows.count == 3)
#expect(rows.map(\.first) == ["keep", "", ""])
#expect(rows[0][1] == Output.path(group.files[0].url))
#expect(DuplicatesCommand.heading(for: group).hasPrefix("3 copies of 4 kB, "))
}
/// A copy in a folder that syncs to other devices is listed as one that stays, and never moved; the JSON names
/// it apart from the copies that may move.
@Test(.everySyncAppOnThisMac) func listsACopyThatSyncsAsOneThatStays() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let contents = Data((0..<4_000).map { _ in UInt8.random(in: 0...255) })
try directory.directory("home/Synced/.stfolder")
try directory.file("home/Synced/a.bin", contents: contents)
try directory.file("home/Documents/a.bin", contents: contents)
try directory.file("home/Documents/a copy.bin", contents: contents)
let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
let scan = try await DuplicateFinder(homeDirectory: home).scan(.everySize(in: [home]))
let group = try #require(scan.groups.first)
let synced = try #require(group.files.first { $0.heldBack == .inTheCloud })
let rows = DuplicatesCommand.rows(for: group)
#expect(rows.first { $0[1] == Output.path(synced.url) }?[0] == "stays")
#expect(rows.map { $0[0] }.sorted() == ["", "keep", "stays"])
let json = try Output.jsonText(DuplicatesCommand.found(in: scan))
let found = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
let record = try #require((found["files"] as? [[String: Any]])?.first)
#expect(record["synced"] as? [String] == [Output.path(synced.url)])
#expect((record["files"] as? [String])?.count == 2)
try await (command(["duplicates", "--remove", "-y"]) as DuplicatesCommand)
.clean(scan, using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)
#expect(await moved(logs) == ["a copy.bin"])
#expect(FileManager.default.fileExists(atPath: synced.url.path(percentEncoded: false)))
}
@Test func movesEveryOtherCopyWhenOneStaysForWhatTheOthersLack() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let contents = Data((0..<4_000).map { _ in UInt8.random(in: 0...255) })
var tagged = try directory.file("home/Documents/a.bin", contents: contents)
try directory.file("home/Pictures/a.bin", contents: contents)
var red = URLResourceValues()
red.tagNames = ["Red"]
try tagged.setResourceValues(red)
let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
let scan = try await DuplicateFinder(homeDirectory: home).scan(.everySize(in: [home]))
let group = try #require(scan.groups.first)
#expect(DuplicatesCommand.rows(for: group).map { $0[0] }.sorted() == ["", "stays"])
#expect(DuplicatesCommand.notes(for: scan).contains(
"1 copy has Finder tags, a Finder comment, or a resource fork the others lack, so Peel lists it as a copy that stays and never moves it."
))
let json = try Output.jsonText(DuplicatesCommand.found(in: scan))
let found = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
let record = try #require((found["files"] as? [[String: Any]])?.first)
#expect(record["stays"] as? [String] == [Output.path(tagged)])
#expect(record["synced"] as? [String] == [])
try await (command(["duplicates", "--remove", "-y"]) as DuplicatesCommand)
.clean(scan, using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)
#expect(await moved(logs) == ["a.bin"])
#expect(FileManager.default.fileExists(atPath: tagged.path(percentEncoded: false)))
}
@Test func saysHowManyCopiesOfAFolderAndHowBigItIs() async throws {
let directory = try TemporaryDirectory()
let contents = Data((0..<4_000).map { _ in UInt8.random(in: 0...255) })
for folder in ["home/Documents/Trip", "home/Pictures/Trip"] {
try directory.file("\(folder)/photo.jpg", contents: contents)
}
let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
let scan = try await DuplicateFinder(homeDirectory: home).scan(.everySize(in: [home]))
let group = try #require(scan.folderGroups.first)
#expect(DuplicatesCommand.heading(for: group).hasPrefix("2 copies of a folder of 1 file, 4 kB, "))
#expect(DuplicatesCommand.rows(for: group.folders.map(\.url)).map(\.first) == ["keep", ""])
}
/// An orphan group says what Peel makes of it, and never in a way that reads as a recommendation.
@Test func saysWhatItMakesOfAnOrphanGroup() throws {
let directory = try TemporaryDirectory()
var group = OrphanGroup(identifier: "com.example.gone", items: [try orphan("com.example.gone", in: directory)])
group.confidence = OrphanConfidence(level: .certain, reasons: [.nothingClaimsIt])
#expect(OrphansCommand.heading(for: group).hasPrefix("com.example.gone 10 bytes certain: "))
#expect(OrphansCommand.rows(for: group) == [["10 bytes", Output.path(group.items[0].url)]])
}
/// The list says which files `--remove` leaves where they are, and why.
@Test func saysWhichOrphanedFilesStayAndWhy() throws {
let directory = try TemporaryDirectory()
let group = OrphanGroup(identifier: "com.example.gone", items: [
try orphan("com.example.gone", in: directory),
try orphan("com.example.gone.wallet", in: directory, heldBack: .holdsAWallet),
try orphan("com.example.gone.photos", in: directory, heldBack: .holdsALibrary),
])
#expect(OrphansCommand.rows(for: group) == [
["10 bytes", Output.path(group.items[0].url)],
["10 bytes", Output.path(group.items[1].url), "stays: holds a wallet or a signing key"],
["10 bytes", Output.path(group.items[2].url), "stays: holds a photo, music, or video library"],
])
#expect(OrphansCommand.heading(for: group).hasPrefix("com.example.gone 10 bytes "), "the files that stay counted")
}
/// `peel orphans --json` says why `--remove` leaves each file it leaves, and which folders macOS kept Peel out of.
@Test func theOrphansListSaysWhatStaysAndWhereItCouldNotLook() throws {
let directory = try TemporaryDirectory()
let group = OrphanGroup(identifier: "com.example.gone", items: [
try orphan("com.example.gone", in: directory),
try orphan("com.example.gone.wallet", in: directory, heldBack: .holdsAWallet),
])
let unread = SearchLocation(kind: .containers, url: URL(filePath: "/Users/me/Library/Containers", directoryHint: .isDirectory))
var scan = OrphanScan(groups: [group], unreadableLocations: [unread], needsFullDiskAccess: true)
scan.cutShortLocations = [unread]
let json = try Output.jsonText(OrphansCommand.report(for: scan))
let report = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
let listed = try #require((report["groups"] as? [[String: Any]])?.first)
let files = try #require(listed["files"] as? [[String: Any]])
#expect(files[0]["heldBack"] is NSNull)
#expect(files[1]["heldBack"] as? String == "holdsAWallet")
#expect(listed["size"] as? Int == 20)
#expect(listed["movable"] as? Int == 10, "what --remove would move")
#expect(report["unreadableLocations"] as? [String] == ["/Users/me/Library/Containers"])
#expect(report["cutShortLocations"] as? [String] == ["/Users/me/Library/Containers"])
#expect(report["needsFullDiskAccess"] as? Bool == true)
}
@Test func saysAKernelExtensionLeavesTheKernelOnlyWhenTheMacRestarts() throws {
let directory = try TemporaryDirectory()
let driver = try orphan("Example.kext", in: directory, heldBack: .beyondTheHelper, requiresPrivileges: true)
let other = try orphan("com.example.gone", in: directory, heldBack: .beyondTheHelper, requiresPrivileges: true)
var scan = OrphanScan(groups: [], unreadableLocations: [])
scan.forAnAdministrator = [AdministratorItem(item: other, apps: ["Gone"])]
#expect(driver.url.isKernelExtension && !other.url.isKernelExtension)
#expect(!OrphansCommand.notes(for: scan, ownersUnreadable: false, onAppleSilicon: false)
.contains(OrphansCommand.kernelExtensions))
scan.forAnAdministrator.append(AdministratorItem(item: driver, apps: ["Gone"]))
#expect(OrphansCommand.notes(for: scan, ownersUnreadable: false, onAppleSilicon: false).last
== OrphansCommand.kernelExtensions)
}
@Test func saysOnAppleSiliconHowToSetTheStartupDisksSecurityBackAfterAKernelExtension() throws {
let directory = try TemporaryDirectory()
let driver = try orphan("Example.kext", in: directory, heldBack: .beyondTheHelper, requiresPrivileges: true)
let other = try orphan("com.example.gone", in: directory, heldBack: .beyondTheHelper, requiresPrivileges: true)
var scan = OrphanScan(groups: [], unreadableLocations: [])
scan.forAnAdministrator = [AdministratorItem(item: other, apps: ["Gone"])]
#expect(!OrphansCommand.notes(for: scan, ownersUnreadable: false, onAppleSilicon: true)
.contains(OrphansCommand.reducedSecurity))
scan.forAnAdministrator.append(AdministratorItem(item: driver, apps: ["Gone"]))
#expect(OrphansCommand.notes(for: scan, ownersUnreadable: false, onAppleSilicon: true).suffix(2)
== [OrphansCommand.kernelExtensions, OrphansCommand.reducedSecurity])
#expect(!OrphansCommand.notes(for: scan, ownersUnreadable: false, onAppleSilicon: false)
.contains(OrphansCommand.reducedSecurity))
}
@Test func listsApartWhatOnlyAnAdministratorCanMove() throws {
let directory = try TemporaryDirectory()
let item = try orphan("com.example.gone", in: directory, heldBack: .beyondTheHelper, requiresPrivileges: true)
let left = try orphan("com.example.left", in: directory, heldBack: .beyondTheHelper, requiresPrivileges: true)
let hinted = try orphan("com.example.hint", in: directory, heldBack: .beyondTheHelper, requiresPrivileges: true)
let scan = OrphanScan(
groups: [],
unreadableLocations: [],
forAnAdministrator: [
AdministratorItem(item: item, apps: ["Gone"]),
AdministratorItem(item: left, apps: ["Left"], claim: .init(reason: .bundleIdentifier, confidence: .certain)),
AdministratorItem(item: hinted, apps: ["Synth"], claim: .init(reason: .vendorPrefix, confidence: .possible)),
]
)
#expect(OrphansCommand.administratorHeading(for: scan) == "Needs an administrator 30 bytes")
#expect(OrphansCommand.administratorRows(for: scan) == [
["10 bytes", Output.path(item.url), "found for Gone"],
["10 bytes", Output.path(left.url), "found for Left, bundle identifier"],
["10 bytes", Output.path(hinted.url), "found for Synth, developer, review: possible match"],
])
#expect(OrphansCommand.notes(for: scan, ownersUnreadable: false) == [OrphansCommand.byHand])
#expect(OrphansCommand.notes(for: scan, ownersUnreadable: true).first?.hasPrefix(
"Peel can't read the list of orphaned files you said belong to an app or a command-line tool, so it lists them too."
) == true)
let json = try Output.jsonText(OrphansCommand.report(for: scan))
let report = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
let listed = try #require(report["forAnAdministrator"] as? [[String: Any]])
#expect(listed.first?["path"] as? String == Output.path(item.url))
#expect(listed.first?["size"] as? Int == 10)
#expect(listed.first?["apps"] as? [String] == ["Gone"])
#expect(listed.first?["reason"] is NSNull)
#expect(listed.first?["confidence"] is NSNull)
#expect(listed.last?["reason"] as? String == "vendorPrefix")
#expect(listed.last?["confidence"] as? String == "possible")
}
@Test func theOrphansListSaysWhereItStoppedLookingInsideFolders() {
let caches = SearchLocation(kind: .caches, url: URL(filePath: "/Users/me/Library/Caches", directoryHint: .isDirectory))
var scan = OrphanScan(groups: [], unreadableLocations: [caches], needsFullDiskAccess: true)
scan.cutShortLocations = [caches]
let notes = OrphansCommand.notes(for: scan, ownersUnreadable: false)
#expect(notes == [
"Peel couldn't look inside /Users/me/Library/Caches, so something may be there that isn't listed. Give your terminal app Full Disk Access in System Settings to read the folders macOS protects.",
"There are more folders in /Users/me/Library/Caches than Peel looks inside, so an orphaned file may be in a folder Peel didn't reach.",
])
}
@Test func orphansListsNothingWhileAnAppFolderCannotBeRead() {
let studio = URL(filePath: "/Volumes/Studio/Apps", directoryHint: .isDirectory)
#expect(OrphansCommand.refusal(for: AppScan(apps: [], unreadable: [], needsFullDiskAccess: false)) == nil)
let refusal = OrphansCommand.refusal(for: AppScan(apps: [], unreadable: [studio], needsFullDiskAccess: false))
#expect(refusal?.description == "Peel couldn't read /Volumes/Studio/Apps, so it can't tell which apps are installed. Nothing is listed, since the files of an app it can't see would look orphaned.")
let locked = OrphansCommand.refusal(for: AppScan(apps: [], unreadable: [studio], needsFullDiskAccess: true))
#expect(locked?.description.hasSuffix(" Give your terminal app Full Disk Access in System Settings to read the folders macOS protects.") == true)
let many = (1...60).map { URL(filePath: "/Volumes/Old/f\($0)x", directoryHint: .isDirectory) }
let said = OrphansCommand.refusal(for: AppScan(apps: [], unreadable: many, needsFullDiskAccess: false))?
.description
#expect(said?.hasPrefix("Peel couldn't read /Volumes/Old/f1x, /Volumes/Old/f2x, /Volumes/Old/f3x, /Volumes/Old/f4x, and 56 more folders, so") == true)
let list = AppScan(apps: [], unreadable: [], needsFullDiskAccess: false, chosenFolders: nil)
#expect(OrphansCommand.refusal(for: list)?.description == "Peel couldn't read its list of app folders, so it can't tell which apps are installed. Nothing is listed, since the files of an app it can't see would look orphaned. Start the list over in Settings > General > App Folders.")
let damaged = AppScan(apps: [], chosenFolders: nil, whyListOfFoldersUnreadable: .damaged)
#expect(OrphansCommand.refusal(for: damaged)?.description.hasSuffix("App Folders. The file's contents aren't in a form Peel can read.") == true)
}
/// A chosen folder Peel didn't look in, such as a repository, is said, so an empty answer is not read as none.
@Test func saysWhichFoldersItDidNotLookIn() {
let skipped = URL(filePath: "/Users/me/Projects/app", directoryHint: .isDirectory)
let scan = DuplicateScan(
groups: [], unreadableLocations: [], skippedLocations: [.init(url: skipped, reason: .insideARepository)]
)
let notes = DuplicatesCommand.notes(for: scan)
#expect(notes.contains {
$0 == "Peel didn't look in /Users/me/Projects/app: it is a repository, or sits inside one, and Peel leaves repositories alone."
})
}
@Test(.everySyncAppOnThisMac) func namesTheAppThatSyncsTheCopiesItLeavesAlone() async throws {
let directory = try TemporaryDirectory()
let contents = Data((0..<3_000).map { _ in UInt8.random(in: 0...255) })
try directory.directory("home/.stfolder")
try directory.file("home/Desktop/a.bin", contents: contents)
try directory.file("home/Documents/a.bin", contents: contents)
let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
let scan = try await DuplicateFinder(homeDirectory: home).scan(
.everySize(in: ["Desktop", "Documents"].map { home.appending(path: $0, directoryHint: .isDirectory) })
)
let marker = Output.path(home.appending(path: ".stfolder"))
#expect(DuplicatesCommand.notes(for: scan).contains(
"Syncthing syncs some of them to your other devices (its marker is \(marker))."
))
}
@Test func refusesEachFolderItCantScanWithItsReason() throws {
let finder = "/System/Library/CoreServices/Finder.app"
let caches = FileManager.default.homeDirectoryForCurrentUser.appending(path: "Library/Caches")
let error = #expect(throws: (any Error).self) {
try PeelCommand.parseAsRoot(["duplicates", "/Applications", finder, caches.path(percentEncoded: false)])
}
let message = PeelCommand.fullMessage(for: try #require(error), columns: 300)
#expect(message.contains("/Applications: it is outside your home folder, /Users/Shared, and the disks in /Volumes"))
#expect(message.contains("\(finder): it is an app or another package, or inside one, and what is inside belongs to it"))
#expect(message.contains("Library/Caches: it is your Library, or a folder in it, where apps keep their data"))
}
@Test func saysWhenAnOrphanGroupWasModifiedAndWhyItMatters() {
let date = Date(timeIntervalSince1970: 1_792_315_250)
let recent = OrphanConfidence(level: .unsure, reasons: [.writtenRecently(date)]).summary
let later = OrphanConfidence(level: .unsure, reasons: [.writtenAfterItLeft(name: "Example", written: date)]).summary
#expect(recent == "modified on \(Output.day(date)), so something may still use these files")
#expect(later == "modified on \(Output.day(date)), after Peel last saw Example installed, so something may still use these files")
#expect(OrphanConfidence(level: .certain, reasons: [.untouched(months: 7)]).summary == "not modified in 7 months")
}
@Test func namesWhatIsRunningUnderAnOrphanGroupsIdentifier() {
let running = OrphanConfidence(level: .unsure, reasons: [.running("Example Helper")]).summary
#expect(running == "Example Helper is running now, so these may still be in use")
}
@Test func namesTheFolderThatKeepsAProjectSearchOut() throws {
let directory = try TemporaryDirectory()
let installed = try directory.directory("Code/app/node_modules/org-example-dep")
let hidden = try directory.directory("Tool/.editor/extensions")
let error = #expect(throws: (any Error).self) {
try PeelCommand.parseAsRoot([
"projects", installed.path(percentEncoded: false), hidden.path(percentEncoded: false),
])
}
let message = PeelCommand.fullMessage(for: try #require(error), columns: 400)
#expect(message.contains("org-example-dep: Peel doesn't look for projects in node_modules or anything inside it, since npm fills it with what it installs"))
#expect(message.contains("extensions: Peel doesn't look for projects in .editor or anything inside it, since apps and tools keep their own files in hidden folders"))
}
@Test(.everySyncAppOnThisMac) func saysThereIsNothingToMoveWhenEveryOtherCopySyncs() async throws {
let directory = try TemporaryDirectory()
let logs = logs(in: directory)
let contents = Data((0..<4_000).map { _ in UInt8.random(in: 0...255) })
try directory.directory("home/Synced/.stfolder")
try directory.file("home/Synced/a.bin", contents: contents)
try directory.file("home/Documents/a.bin", contents: contents)
let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
let scan = try await DuplicateFinder(homeDirectory: home).scan(.everySize(in: [home]))
let collected = Output.Collected()
try await Output.$collected.withValue(collected) {
try await (command(["duplicates", "--remove", "--dry-run"]) as DuplicatesCommand)
.clean(scan, using: try service(in: directory), recordingIn: logs.removals, refusals: logs.refusals)
}
#expect(scan.groups.count == 1)
#expect(collected.output == "Nothing to move: every other copy syncs to your other devices.\n")
}
@Test func duplicatesComparesNothingWhileTheExclusionsCantBeRead() {
let saved = URL(filePath: "/Users/me/Library/Application Support/Peel/exclusions.json")
let refusal = DuplicatesCommand.refusal(for: .unreadable(because: nil), savedAt: saved)
#expect(refusal?.description.hasPrefix(
"Peel couldn't read your exclusions at /Users/me/Library/Application Support/Peel/exclusions.json, so it compares nothing"
) == true)
#expect(DuplicatesCommand.refusal(for: .none, savedAt: saved) == nil)
}
/// `peel duplicates --json` names the folders it couldn't read and the chosen folders it didn't look in.
@Test func theDuplicatesReportSaysWhereItCouldNotLook() throws {
let scan = DuplicateScan(
groups: [],
unreadableLocations: [URL(filePath: "/Users/me/Locked", directoryHint: .isDirectory)],
skippedLocations: [
.init(url: URL(filePath: "/Users/me/Projects/app", directoryHint: .isDirectory), reason: .insideARepository),
]
)
let json = try Output.jsonText(DuplicatesCommand.found(in: scan))
let found = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
#expect(found["unreadableLocations"] as? [String] == ["/Users/me/Locked"])
#expect(found["skippedLocations"] as? [String] == ["/Users/me/Projects/app"])
#expect(found["setAside"] as? [[String: String]] == [[
"path": "/Users/me/Projects/app",
"reason": "it is a repository, or sits inside one, and Peel leaves repositories alone",
]])
}
@Test func aRemovalFromTwoProjectsOfTheSameNameIsNotNamedForOne() {
let artifacts = ["/Users/me/Developer/acme/web", "/Users/me/Developer/globex/web"].map { project in
ProjectArtifact(
url: URL(filePath: project + "/node_modules", directoryHint: .isDirectory),
project: URL(filePath: project, directoryHint: .isDirectory),
name: "node_modules",
tool: "npm",
size: 10,
lastActivity: nil,
hasGenericName: false,
isEnvironment: false
)
}
#expect(ProjectsCommand.source(of: artifacts) == ("Build artifacts", "tool"))
#expect(ProjectsCommand.source(of: [artifacts[0], artifacts[0]]) == ("web", nil))
}
/// A chosen folder macOS kept Peel out of is said whatever the output, so an empty answer is not read as none.
@Test func saysWhenItCouldNotLookInAChosenFolder() throws {
let locked = URL(filePath: "/Users/me/Library/Safari", directoryHint: .isDirectory)
let scan = ProjectArtifacts.Scan(
artifacts: [], wasCutShort: true, unreadableLocations: [locked], needsFullDiskAccess: true
)
#expect(ProjectsCommand.notes(for: scan) == [
"Peel couldn't look inside /Users/me/Library/Safari, so something may be there that isn't listed. Give your terminal app Full Disk Access in System Settings to read the folders macOS protects.",
"There were more folders than Peel looks at in one go, so this list isn't all of them.",
])
let app = URL(filePath: "/Users/me/Code/app", directoryHint: .isDirectory)
let closed = ProjectArtifacts.Scan(unreadableLocations: [app])
#expect(ProjectsCommand.notes(for: closed) == [
"Peel couldn't look inside /Users/me/Code/app, so something may be there that isn't listed.",
])
let json = try Output.jsonText(ProjectsCommand.report(for: scan))
let report = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
#expect(report["unreadableLocations"] as? [String] == ["/Users/me/Library/Safari"])
#expect(report["cutShort"] as? Bool == true)
}
@Test func namesEachChosenFolderTheScanDidNotSearch() throws {
let unplugged = URL(filePath: "/Volumes/Disk/Projects", directoryHint: .isDirectory)
let scan = ProjectArtifacts.Scan(refusedRoots: [(unplugged, .unreachable(.diskNotConnected("Disk")))])
#expect(ProjectsCommand.notes(for: scan) == ["/Volumes/Disk/Projects: it is on Disk, a disk that isn't connected now"])
let json = try Output.jsonText(ProjectsCommand.report(for: scan))
let report = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
#expect(report["skippedLocations"] as? [String] == ["/Volumes/Disk/Projects"])
#expect(report["cutShort"] as? Bool == false)
}
/// `peel caches --json` says which folders `--remove` would take.
@Test func theCachesListSaysWhatRemoveWouldTake() throws {
let directory = try TemporaryDirectory()
let tool = try environment("Rust", id: "rust", locations: [
("Library/Caches/cargo", .cache),
("Library/Models/llama", .models),
], in: directory)
let json = try Output.jsonText(CachesCommand.records(for: [tool]))
let records = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [[String: Any]])
let locations = try #require(records.first?["locations"] as? [[String: Any]])
#expect(locations[0]["suggested"] as? Bool == true)
#expect(locations[1]["suggested"] as? Bool == false)
}
@Test func namesEachToolSoACommandCanAskForItAlone() throws {
let directory = try TemporaryDirectory()
let one = try environment("Chat", id: "electron.org.example.one", locations: [("Library/one", .cache)], in: directory)
let two = try environment("Chat", id: "electron.org.example.two", locations: [("Library/two", .cache)], in: directory)
let rust = try environment("Rust", id: "rust", locations: [("Library/Caches/cargo", .cache)], in: directory)
let json = try Output.jsonText(CachesCommand.records(for: [one, two, rust]))
let records = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [[String: Any]])
#expect(records.map { $0["id"] as? String } == ["electron.org.example.one", "electron.org.example.two", "rust"])
#expect(CachesCommand.title(of: one, among: [one, two, rust]) == "Chat (electron.org.example.one)")
#expect(CachesCommand.title(of: rust, among: [one, two, rust]) == "Rust")
}
/// A script reading `peel caches --json` gets, for each folder, where its tool documents it.
@Test func tellsWhereEachCacheIsDocumented() throws {
let directory = try TemporaryDirectory()
let tool = try environment("Rust", id: "rust", locations: [("Library/Caches/cargo", .cache)], in: directory)
let json = try Output.jsonText(CachesCommand.records(for: [tool]))
#expect(json.contains("\"source\" : \"https://example.com/Library/Caches/cargo\""))
}
@Test func saysEveryCacheLocationWithItsKind() throws {
let directory = try TemporaryDirectory()
let tool = try environment("Rust", id: "rust", locations: [
("Library/Caches/cargo", .cache),
("Library/Models/llama", .models),
], in: directory)
let rows = CachesCommand.rows(for: tool)
#expect(rows.count == 2)
#expect(rows[0] == ["30 bytes", Output.path(tool.locations[0].url), "cache", "suggested"])
#expect(rows[1][2] == "models")
#expect(rows[1][3] == "kept by default")
}
@Test func saysWhyEachCacheStaysByTheRuleThatSuggestsIt() throws {
let directory = try TemporaryDirectory()
let tool = try environment("Rust", id: "rust", locations: [
("Library/Caches/cargo", .cache), ("Library/Caches/wallet", .cache), ("Library/Caches/closed", .cache),
("Library/Caches/other", .cache), ("Library/Caches/xcode", .buildData), ("Library/Models/llama", .models),
("Library/Caches/specs", .downloads),
], in: directory)
var locations = tool.locations
locations[1].heldBack = .holdsAWallet
locations[2] = DeveloperEnvironment.Location(
url: locations[2].url, kind: .cache, size: nil, source: locations[2].source, couldNotBeRead: true,
closedByPermissions: true
)
locations[3].isTheTools = false
locations[4].workspace = DeveloperEnvironment.Workspace(name: "App", lastUsed: .now)
locations[6].isTheTools = false
locations[6].heldBack = .holdsRepository
let held = DeveloperEnvironment(
id: tool.id, name: tool.name, systemImage: tool.systemImage, appBundleIdentifiers: [], locations: locations
)
#expect(held.locations.map(CachesCommand.note(for:)) == [
"suggested", "holds a wallet or a signing key, kept", "its permissions keep Peel out, kept",
"nothing shows the tool made it, kept", "its workspace was opened in the last 7 days, kept",
"kept by default", "holds a repository, kept",
])
#expect(held.locations.allSatisfy { ($0.isRecommended) == (CachesCommand.note(for: $0) == "suggested") })
let json = try Output.jsonText(CachesCommand.records(for: [held]))
let records = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [[String: Any]])
let written = try #require(records.first?["locations"] as? [[String: Any]])
#expect(written[0]["reason"] is NSNull && written[0]["heldBack"] is NSNull)
#expect(written[1]["heldBack"] as? String == "holdsAWallet")
#expect(written[1]["reason"] as? String == "holds a wallet or a signing key")
#expect(written[2]["heldBack"] as? String == "closedByPermissions")
#expect(CachesCommand.staying(in: [held]).count == 6)
#expect(CachesCommand.staying(in: [held])[0].hasSuffix("wallet stays: holds a wallet or a signing key"))
#expect(CachesCommand.notes(for: [held]) == [
"Peel couldn't look inside \(Output.plain(Output.path(locations[2].url))), so something may be there that isn't listed.",
])
}
}