Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

iCloud Drive lists what removing each download frees

Țugui Dragoș5742082cea01
diff --git a/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift b/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift
index 9d355500..44c5e5d6 100644
--- a/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift
@@ -10,6 +10,8 @@ public struct CloudFile: Sendable, Hashable, Identifiable {
public let name: String
/// The folder under `Mobile Documents` it belongs to, in readable form: "iCloud Drive", "Pages".
public let container: String
+ /// What removing the local copy frees: less than the file's length when it is stored compressed, and nothing
+ /// when a clone shares its blocks.
public let size: Int64
public let modified: Date?
@@ -41,7 +43,7 @@ public struct CloudRefusal: Sendable, Hashable, Identifiable {
}
public enum CloudStorage {
- /// Below this a file isn't worth a row in a list about space.
+ /// A file that frees less than this isn't worth a row in a list about space.
public static let minimumSize: Int64 = 1_000_000
/// The most files listed. The cap counts listed files, not every entry walked, so a walk through many small
/// files still reaches the big ones after them.
@@ -66,7 +68,7 @@ public enum CloudStorage {
/// The resource keys read for each file, by the scan and again by `free(_:)`.
static let keys: Set<URLResourceKey> = [
- .isRegularFileKey, .fileSizeKey, .contentModificationDateKey, .ubiquitousItemDownloadingStatusKey,
+ .isRegularFileKey, .contentModificationDateKey, .ubiquitousItemDownloadingStatusKey,
.ubiquitousItemIsUploadedKey, .ubiquitousItemIsUploadingKey, .ubiquitousItemHasUnresolvedConflictsKey,
.ubiquitousItemIsSyncPausedKey, .ubiquitousItemUploadingErrorKey,
]
@@ -144,7 +146,7 @@ public enum CloudStorage {
/// Walks iCloud Drive and adds each file worth freeing to `collector`. Stops at `deadline` as well as when
/// `isGivenUp` says so, because the timer behind `isGivenUp` runs on another thread and can fire late on a
- /// busy Mac.
+ /// busy Mac. Only iCloud can say a file is safely there, so a test says it through `isSafe`.
static func collect(
home: URL,
minimumSize: Int64,
@@ -152,6 +154,7 @@ public enum CloudStorage {
into collector: Collector,
deadline: ContinuousClock.Instant,
countingFor scan: ScanCount?,
+ isSafe: (URLResourceValues) -> Bool = isSafeToFree(_:),
unless isGivenUp: () -> Bool
) {
let root = home.appending(path: "Library/Mobile Documents", directoryHint: .isDirectory)
@@ -180,9 +183,14 @@ public enum CloudStorage {
return
}
scan?.add(1)
- guard let values = try? url.resourceValues(forKeys: keys), values.isRegularFile == true else { continue }
- let size = Int64(values.fileSize ?? 0)
- guard size >= minimumSize, !exclusions.excludes(url), isSafeToFree(values) else { continue }
+ guard
+ let values = try? url.resourceValues(forKeys: keys),
+ values.isRegularFile == true,
+ !exclusions.excludes(url),
+ isSafe(values)
+ else { continue }
+ let size = ReclaimableSpace.of(url)
+ guard size >= minimumSize else { continue }
let file = CloudFile(
url: url,
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift
index 5519c270..971ad446 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift
@@ -62,6 +62,39 @@ struct CloudStorageTests {
#expect(Set(scan.files.map(\.id)).count == scan.files.count)
}
+ /// A row's size is what removing the download frees, never the length the file claims: a file stored
+ /// compressed takes fewer blocks than its length, and a clone shares its blocks, so removing it frees nothing.
+ /// Only iCloud can say a file is safely there, so the test says it for these.
+ @Test func aFilesSizeIsWhatRemovingItsDownloadFrees() throws {
+ let directory = try TemporaryDirectory()
+ let drive = "Library/Mobile Documents/com~apple~CloudDocs"
+ let plain = try directory.file("\(drive)/plain.bin", bytes: 3_000_000)
+ let compressed = try directory.compressedTextFile("\(drive)/compressed.txt")
+ let original = try directory.file("\(drive)/original.bin", bytes: 2_000_000)
+ let clone = original.deletingLastPathComponent().appending(path: "clone.bin")
+ #expect(clonefile(original.path(percentEncoded: false), clone.path(percentEncoded: false), 0) == 0)
+
+ let collector = CloudStorage.Collector()
+ CloudStorage.collect(
+ home: directory.url,
+ minimumSize: 1,
+ exclusions: .none,
+ into: collector,
+ deadline: .now + .seconds(20),
+ countingFor: nil,
+ isSafe: { _ in true },
+ unless: { false }
+ )
+ let sizes = Dictionary(uniqueKeysWithValues: collector.collected.files.map { ($0.name, $0.size) })
+
+ #expect(sizes["plain.bin"] == ReclaimableSpace.of(plain))
+ #expect((sizes["plain.bin"] ?? 0) >= 3_000_000)
+ #expect(sizes["compressed.txt"] == ReclaimableSpace.of(compressed))
+ #expect((sizes["compressed.txt"] ?? .max) < 240_000, "the compressed file was weighed by its length")
+ #expect(sizes["original.bin"] == nil, "a file whose blocks a clone shares frees nothing")
+ #expect(sizes["clone.bin"] == nil, "a clone frees nothing")
+ }
+
@Test func leavesAFolderWithoutICloudAlone() async throws {
let directory = try TemporaryDirectory()
try directory.file("Library/Mobile Documents/com~apple~CloudDocs/plain.txt", bytes: 4_000_000)
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift
index 0d2a4178..056d4f63 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift
@@ -390,7 +390,7 @@ struct DuplicateFinderTests {
@Test func aCompressedFileIsWeighedByItsLength() async throws {
let directory = try TemporaryDirectory()
for name in ["home/Documents/notes.txt", "home/Desktop/notes.txt"] {
- let copy = try compressedText(at: directory.url.appending(path: name))
+ let copy = try directory.compressedTextFile(name)
#expect(ReclaimableSpace.allocated(copy) < 100_000)
}
@@ -404,7 +404,7 @@ struct DuplicateFinderTests {
/// is counted as freeing nothing.
@Test func aCompressedCopyFreesItsBlocksUntilItIsCloned() throws {
let directory = try TemporaryDirectory()
- let compressed = try compressedText(at: directory.url.appending(path: "compressed.txt"))
+ let compressed = try directory.compressedTextFile("compressed.txt")
#expect(ReclaimableSpace.allocated(compressed) > 0)
#expect(ReclaimableSpace.of(compressed) == ReclaimableSpace.allocated(compressed))
@@ -413,19 +413,6 @@ struct DuplicateFinderTests {
#expect(ReclaimableSpace.of(compressed) == 0)
#expect(ReclaimableSpace.of(clone) == 0)
}
-
- /// Writes 240 KB of text to `url`, compressed into its resource fork by `ditto`, and returns `url`.
- private func compressedText(at url: URL) throws -> URL {
- let source = url.deletingLastPathComponent().appending(path: ".source-\(url.lastPathComponent)")
- try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
- try Data(String(repeating: "hello world ", count: 20_000).utf8).write(to: source)
- let ditto = try Process.run(URL(filePath: "/usr/bin/ditto"), arguments: ["--hfsCompression", source.path, url.path])
- ditto.waitUntilExit()
- try FileManager.default.removeItem(at: source)
- var info = stat()
- #expect(lstat(url.path(percentEncoded: false), &info) == 0 && info.st_flags & UInt32(UF_COMPRESSED) != 0)
- return url
- }
}
struct DuplicateRemovalTests {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TemporaryDirectory.swift b/Packages/PeelCore/Tests/PeelCoreTests/TemporaryDirectory.swift
index b6d01532..7cc4ba5d 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/TemporaryDirectory.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/TemporaryDirectory.swift
@@ -35,6 +35,23 @@ struct TemporaryDirectory: ~Copyable {
return directoryURL
}
+ /// Writes 240 KB of text at `path`, compressed into its resource fork by `ditto`, as macOS compresses a file.
+ @discardableResult
+ func compressedTextFile(_ path: String) throws -> URL {
+ let fileURL = url.appending(path: path)
+ let source = fileURL.deletingLastPathComponent().appending(path: ".source-\(fileURL.lastPathComponent)")
+ try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(String(repeating: "hello world ", count: 20_000).utf8).write(to: source)
+ let ditto = try Process.run(URL(filePath: "/usr/bin/ditto"), arguments: ["--hfsCompression", source.path, fileURL.path])
+ ditto.waitUntilExit()
+ try FileManager.default.removeItem(at: source)
+ var info = stat()
+ guard lstat(fileURL.path(percentEncoded: false), &info) == 0, info.st_flags & UInt32(UF_COMPRESSED) != 0 else {
+ throw CocoaError(.fileWriteUnknown, userInfo: [NSFilePathErrorKey: fileURL.path])
+ }
+ return fileURL
+ }
+
func setPermissions(_ permissions: Int, of path: String) throws {
try FileManager.default.setAttributes([.posixPermissions: permissions], ofItemAtPath: url.appending(path: path).path(percentEncoded: false))
}