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
Hold back an iCloud download that Keep Downloaded keeps
Țugui Dragoș8d14bba57c0a
diff --git a/GUIDE.md b/GUIDE.mdindex 191951db..1dd4e014 100644--- a/GUIDE.md+++ b/GUIDE.md@@ -138,13 +138,14 @@ Space shows what fills your disk, area by area, and what each area is.update whose app is open, and anything in Shared, open in a program, open as a disk image, or syncing to your otherdevices. A disk image can also be one you made to keep files in, so look before you select it. An installer,download, or update smaller than 20 MB isn't listed.-- **iCloud Drive:** files already safe in iCloud that are also downloaded to this Mac, as Finder shows them: what is in- iCloud Drive and each app's documents, never an app's own data. Downloads are listed in the folders Finder shows- them in, named as Finder names them, the biggest first, and a folder's checkbox selects every file in it; a file- that would free less than 1 MB isn't listed. Remove Downloads, as in Finder, takes away only the copy on this Mac:- each file stays in iCloud and downloads again when you open it. A download whose space on disk is shared with- another copy on this Mac would free nothing, so it isn't listed, and the page says how many there are. The page- needs Full Disk Access to see what is kept on this Mac.+- **iCloud Drive:** files already safe in iCloud that are also downloaded to this Mac, as Finder shows them: what is+ in iCloud Drive and each app's documents, never an app's own data. Downloads are listed in the folders Finder shows+ them in, named as Finder names them, the biggest first, and a folder's checkbox selects every file in it that Peel+ recommends; a file that would free less than 1 MB isn't listed. Remove Downloads, as in Finder, takes away only the+ copy on this Mac: each file stays in iCloud and downloads again when you open it. A file Keep Downloaded is on for+ in Finder is listed and not selected, since iCloud would download it again at once. A download whose space on disk+ is shared with another copy on this Mac would free nothing, so it isn't listed, and the page says how many there+ are. The page needs Full Disk Access to see what is kept on this Mac.- **Space:** what fills your disk, area by area, and which app or tool each area belongs to.- **File Search:** files by name, kind, or size, and by age along with one of them, in your home folder or across thisMac's disks, not network volumes, found through Spotlight, up to 2,000 at a time, so a folder in System Settings >diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex ff43690d..a7a65727 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -101291,6 +101291,113 @@}}},+ "Not selected: Keep Downloaded is on for it in Finder, so iCloud downloads it again." : {+ "comment" : "The note beside a file in iCloud Drive. Keep Downloaded is the command in Finder's File menu and shortcut menu that keeps a file or folder downloaded on this Mac; use the name your macOS gives it.",+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nevybráno: ve Finderu je u něj zapnutá volba „Zachovat stažené“, takže ho iCloud znovu stáhne."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nicht ausgewählt: „Laden und behalten“ ist für diese Datei im Finder aktiviert, daher lädt iCloud sie erneut."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Sin seleccionar: tiene activado “Conservar en dispositivo” en el Finder, así que iCloud lo vuelve a descargar."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Non sélectionné : « Conserver le téléchargement » est activé pour ce fichier dans le Finder, iCloud le télécharge donc à nouveau."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Non selezionato: nel Finder è attivo “Conserva scaricato” per questo file, quindi iCloud lo scarica di nuovo."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未選択: Finderで“ダウンロード済みを保持”がオンになっているため、iCloudが再びダウンロードします。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "선택되지 않음: Finder에서 이 파일에 ‘다운로드 항목 유지’가 켜져 있으므로 iCloud가 다시 다운로드합니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Niet geselecteerd: 'Bewaar download' staat in Finder aan voor dit bestand, dus iCloud downloadt het opnieuw."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nie zaznaczono: w Finderze jest dla tego pliku włączona opcja „Zachowuj pobrane”, więc iCloud pobierze go ponownie."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Não selecionado: a opção “Manter Downloads” está ativada para ele no Finder, então o iCloud o baixa de novo."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Neselectat: în Finder, opțiunea „Păstrați descărcat” este activată pentru acest fișier, așa că iCloud îl descarcă din nou."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не выбрано: для этого файла в Finder включен параметр «Оставить в загрузках», поэтому iCloud снова его загрузит."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Inte markerad: ”Behåll hämtningar” är aktiverat för den i Finder, så iCloud hämtar den igen."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Seçilmedi: Finder’da bu dosya için “İndirileni Tut” açık, bu yüzden iCloud onu yeniden indirir."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не вибрано: для цього файлу у Finder увімкнено «Не передавати у хмару», тож iCloud знову його викачує."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未选择:它在“访达”中已设为“保留下载”,因此iCloud会重新下载它。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未選取:它已在Finder中設為「保留已下載項目」,因此iCloud會再次下載它。"+ }+ }+ }+ },"Not selected: Mail keeps a copy here of each attachment you open, and one you edited may exist nowhere else." : {"localizations" : {"cs" : {diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swiftindex 66417f36..f5281962 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift@@ -394,6 +394,7 @@ extension HoldBack {case .crashReport: "a crash report, which the app's developer may still ask for"case .inTheCloud: "syncs to your other devices through iCloud or another app, so moving it would remove it from them too"case .keepsWhatTheOthersLack: "has Finder tags, a comment, or a resource fork the other copies don't"+ case .keptDownloaded: "Keep Downloaded is on for it in Finder, so iCloud downloads it again"case .openInAProgram: "open in a program right now, which may still be using it"case .attachedDiskImage: "a disk image open right now; eject it first"case .changedRecently: "changed in the last day, so it may still be downloading"diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swiftindex f9841205..48a2f098 100644--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift@@ -162,6 +162,9 @@ public enum HoldBack: String, Sendable, Hashable {/// A duplicate with Finder tags, a Finder comment, or a resource fork the other copies lack, which moving it/// would lose.case keepsWhatTheOthersLack+ /// A download in iCloud Drive that Keep Downloaded keeps on this Mac, which iCloud downloads again once it is+ /// removed.+ case keptDownloaded/// True when the item cannot be selected at all, rather than only left unselected: the guard or the helper/// would refuse to move it.diff --git a/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift b/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swiftindex 103c6c87..d0be1ac0 100644--- a/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift+++ b/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift@@ -17,8 +17,15 @@ public struct CloudFile: Sendable, Hashable, Identifiable {/// The picture on one of the displays' desktop, which macOS keeps open while it is shown, so its download cannot be/// removed then.public var isDesktopPicture = false+ /// Why Peel doesn't recommend removing this download, or nil.+ public var heldBack: HoldBack?public var id: URL { url }++ /// Whether Select Recommended takes it.+ public var isRecommended: Bool {+ !isDesktopPicture && heldBack == nil+ }}/// What one scan of iCloud Drive found, and whether the scan stopped early or could not read the folder.@@ -242,6 +249,7 @@ public enum CloudStorage {deadline: ContinuousClock.Instant,countingFor scan: ScanCount?,isSafe: (URLResourceValues) -> Bool = isSafeToFree(_:),+ isPinned: (URL) -> Bool = isPinned(_:),isDataless: (URL) -> Bool = FileSize.isDataless(_:),unless isGivenUp: () -> Bool) {@@ -269,8 +277,14 @@ public enum CloudStorage {// The budget is spent, or the page that asked was left or stopped.func stopped() -> Bool { ContinuousClock.now >= deadline || isGivenUp() }+ func key(_ url: URL) -> String {+ let path = url.path(percentEncoded: false)+ return path.count > 1 && path.hasSuffix("/") ? String(path.dropLast()) : path+ }var container = ""var isICloudDrive = false+ // The folders Keep Downloaded is on for, itself or through a folder above.+ var pinnedFolders: Set<String> = []for case let url as URL in enumerator {guard !stopped() else {collector.ranOutOfTime()@@ -292,11 +306,13 @@ public enum CloudStorage {}continue}- guard- let values = try? url.resourceValues(forKeys: keys),- values.isRegularFile == true || values.isPackage == true,- isSafe(values)- else { continue }+ guard let values = try? url.resourceValues(forKeys: keys) else { continue }+ let isInAPinnedFolder = pinnedFolders.contains(key(url.deletingLastPathComponent()))+ guard values.isRegularFile == true || values.isPackage == true else {+ if isInAPinnedFolder || isPinned(url) { pinnedFolders.insert(key(url)) }+ continue+ }+ guard isSafe(values) else { continue }let measured = values.isRegularFile == true? (size: ReclaimableSpace.of(url), taken: ReclaimableSpace.allocated(url),@@ -321,12 +337,28 @@ public enum CloudStorage {container: container,size: measured.size,modified: measured.modified,- isDesktopPicture: pictures.contains(PathPattern.comparablePath(of: url))+ isDesktopPicture: pictures.contains(PathPattern.comparablePath(of: url)),+ heldBack: isInAPinnedFolder || isPinned(url) ? .keptDownloaded : nil)collector.add(file)}}+ /// Whether Keep Downloaded is on for `url` in Finder: FileProvider keeps it as the extended attribute+ /// `com.apple.fileprovider.pinned`, whose stored name carries flags after a `#` (`xattr_name_with_flags(3)`).+ static func isPinned(_ url: URL) -> Bool {+ let path = url.path(percentEncoded: false)+ let size = listxattr(path, nil, 0, XATTR_NOFOLLOW)+ guard size > 0 else { return false }+ var names = [CChar](repeating: 0, count: size)+ guard listxattr(path, &names, size, XATTR_NOFOLLOW) == size else { return false }+ let pinned = "com.apple.fileprovider.pinned"+ return names.split(separator: 0).contains { name in+ let text = String(decoding: name.map { UInt8(bitPattern: $0) }, as: UTF8.self)+ return text == pinned || text.hasPrefix(pinned + "#")+ }+ }+/// Frees the local copies of `files`, one at a time. Each file is checked again first, against `exclusions` as/// they are now as well: the list may have been on screen for hours, and a file edited since then may exist in/// its newest form only on the local disk.diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swiftindex 8ff1445b..fda20972 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CloudStorageTests.swift@@ -195,6 +195,32 @@ struct CloudStorageTests {#expect(sizes["clone.bin"] == nil, "a clone frees nothing")}+ /// Keep Downloaded keeps a file, or every file in a folder, on this Mac whatever happens, and iCloud downloads it+ /// again once its download is removed: such a file is listed and held back. Only FileProvider sets the mark, so+ /// the test says which items carry it.+ @Test func holdsBackWhatKeepDownloadedKeepsOnThisMac() throws {+ let directory = try TemporaryDirectory()+ let drive = "Library/Mobile Documents/com~apple~CloudDocs"+ for path in ["Trip/Plans/route.pdf", "Trip/ticket.pdf", "Map.pdf", "Notes/a.pdf"] {+ try directory.file("\(drive)/\(path)", bytes: 2_000)+ }+ let pinned: Set = ["Trip", "Map.pdf"]++ let collector = CloudStorage.Collector()+ CloudStorage.collect(+ home: directory.url, minimumSize: 1, exclusions: .none, into: collector, deadline: .now + .seconds(20),+ countingFor: nil, isSafe: { _ in true }, isPinned: { pinned.contains($0.lastPathComponent) },+ unless: { false }+ )++ let held = Dictionary(uniqueKeysWithValues: collector.collected.files.map { ($0.name, $0.heldBack) })+ #expect(held["route.pdf"] == .keptDownloaded)+ #expect(held["ticket.pdf"] == .keptDownloaded)+ #expect(held["Map.pdf"] == .keptDownloaded)+ #expect(held["a.pdf"] == .some(nil))+ #expect(collector.collected.files.filter(\.isRecommended).map(\.name) == ["a.pdf"])+ }+/// A folder kept only in the cloud, which no test can make, is named to the walk.@Test func neverLooksIntoAFolderThatLivesOnlyInTheCloud() throws {let directory = try TemporaryDirectory()diff --git a/Peel/Views/Cloud/CloudView.swift b/Peel/Views/Cloud/CloudView.swiftindex de30d9f6..cf60916a 100644--- a/Peel/Views/Cloud/CloudView.swift+++ b/Peel/Views/Cloud/CloudView.swift@@ -257,7 +257,7 @@ struct CloudView: View {SelectableRows(rows: files.map(\.url),selectable: files.map(\.url),- recommended: files.filter { !$0.isDesktopPicture }.map(\.url)+ recommended: files.filter(\.isRecommended).map(\.url))}@@ -325,6 +325,6 @@ extension CloudFile {var note: LocalizedStringResource? {isDesktopPicture? "Not selected: it is the wallpaper, which macOS keeps open while it is shown, so its download can’t be removed now."- : nil+ : heldBack?.explanation}}diff --git a/Peel/Views/Presentation.swift b/Peel/Views/Presentation.swiftindex 2ddc5a55..8dc482c5 100644--- a/Peel/Views/Presentation.swift+++ b/Peel/Views/Presentation.swift@@ -408,6 +408,8 @@ extension HoldBack {"Left alone: this syncs to your other devices through iCloud or another app, and moving it to the Trash would also remove it from them."case .keepsWhatTheOthersLack:"Left alone: this copy has Finder tags, a Finder comment, or a resource fork the others don’t, which moving it would lose."+ case .keptDownloaded:+ "Not selected: Keep Downloaded is on for it in Finder, so iCloud downloads it again."case .openInAProgram:"Not selected: a program has this open right now, and may still be using it."case .attachedDiskImage:diff --git a/PeelTests/CloudNotesTests.swift b/PeelTests/CloudNotesTests.swiftindex e7955da5..9bc79f3a 100644--- a/PeelTests/CloudNotesTests.swift+++ b/PeelTests/CloudNotesTests.swift@@ -19,5 +19,8 @@ struct CloudNotesTests {#expect(!CloudView.hasNoteColumn([Self.download("Notes.pdf")]))#expect(CloudView.hasNoteColumn([Self.download("Notes.pdf"), picture]))#expect(picture.note != nil)+ var kept = Self.download("Trip.pdf")+ kept.heldBack = .keptDownloaded+ #expect(CloudView.hasNoteColumn([kept]))}}