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.

Find the downloads Safari never finished

Țugui Dragoș6de7811cabb7
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index a53fa776..5f69ebba 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -34587,108 +34587,108 @@
}
}
},
- "Downloads a browser never finished, still under the name it gives a file until the download ends: .crdownload for Chrome and the browsers built on Chromium, .part for Firefox." : {
+ "Downloads a browser never finished, still under the name it gives a file until the download ends: .crdownload for Chrome and the browsers built on Chromium, .part for Firefox, and .download for Safari." : {
"localizations" : {
"cs" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Stahování, která prohlížeč nikdy nedokončil a která stále nesou název, jaký souboru dává do konce stahování: .crdownload pro Chrome a prohlížeče založené na projektu Chromium, .part pro Firefox."
+ "value" : "Stahování, která prohlížeč nikdy nedokončil a která stále nesou název, jaký souboru dává do konce stahování: .crdownload pro Chrome a prohlížeče založené na projektu Chromium, .part pro Firefox a .download pro Safari."
}
},
"de" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Downloads, die ein Browser nie abgeschlossen hat, noch unter dem Namen, den er einer Datei bis zum Ende des Downloads gibt: .crdownload für Chrome und die auf Chromium basierenden Browser, .part für Firefox."
+ "value" : "Downloads, die ein Browser nie abgeschlossen hat, noch unter dem Namen, den er einer Datei bis zum Ende des Downloads gibt: .crdownload für Chrome und die auf Chromium basierenden Browser, .part für Firefox und .download für Safari."
}
},
"es" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Descargas que un navegador nunca terminó, aún con el nombre que da a un archivo hasta que acaba la descarga: .crdownload en Chrome y en los navegadores basados en Chromium, .part en Firefox."
+ "value" : "Descargas que un navegador nunca terminó, aún con el nombre que da a un archivo hasta que acaba la descarga: .crdownload en Chrome y en los navegadores basados en Chromium, .part en Firefox y .download en Safari."
}
},
"fr" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Les téléchargements qu’un navigateur n’a jamais terminés, encore sous le nom qu’il donne à un fichier jusqu’à la fin du téléchargement : .crdownload pour Chrome et les navigateurs basés sur Chromium, .part pour Firefox."
+ "value" : "Les téléchargements qu’un navigateur n’a jamais terminés, encore sous le nom qu’il donne à un fichier jusqu’à la fin du téléchargement : .crdownload pour Chrome et les navigateurs basés sur Chromium, .part pour Firefox et .download pour Safari."
}
},
"it" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Download che un browser non ha mai completato, ancora con il nome che dà al file finché il download non termina: .crdownload per Chrome e i browser basati su Chromium, .part per Firefox."
+ "value" : "Download che un browser non ha mai completato, ancora con il nome che dà al file finché il download non termina: .crdownload per Chrome e i browser basati su Chromium, .part per Firefox e .download per Safari."
}
},
"ja" : {
"stringUnit" : {
"state" : "translated",
- "value" : "ブラウザが完了しなかったダウンロードです。ダウンロードが終わるまでブラウザがファイルに付ける名前のまま残っています。Chromeと、Chromiumをベースにしたブラウザでは.crdownload、Firefoxでは.partです。"
+ "value" : "ブラウザが完了しなかったダウンロードです。ダウンロードが終わるまでブラウザがファイルに付ける名前のまま残っています。Chromeと、Chromiumをベースにしたブラウザでは.crdownload、Firefoxでは.part、Safariでは.downloadです。"
}
},
"ko" : {
"stringUnit" : {
"state" : "translated",
- "value" : "브라우저가 완료하지 못한 다운로드로, 다운로드가 끝날 때까지 브라우저가 파일에 붙이는 이름이 아직 그대로 남아 있습니다. Chrome 및 Chromium 기반 브라우저는 .crdownload, Firefox는 .part입니다."
+ "value" : "브라우저가 완료하지 못한 다운로드로, 다운로드가 끝날 때까지 브라우저가 파일에 붙이는 이름이 아직 그대로 남아 있습니다. Chrome 및 Chromium 기반 브라우저는 .crdownload, Firefox는 .part, Safari는 .download입니다."
}
},
"nl" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Downloads die een browser nooit heeft voltooid, nog onder de naam die de browser een bestand geeft tot de download klaar is: .crdownload voor Chrome en de browsers die op Chromium zijn gebouwd, .part voor Firefox."
+ "value" : "Downloads die een browser nooit heeft voltooid, nog onder de naam die de browser een bestand geeft tot de download klaar is: .crdownload voor Chrome en de browsers die op Chromium zijn gebouwd, .part voor Firefox en .download voor Safari."
}
},
"pl" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Pliki, których przeglądarka nigdy nie skończyła pobierać, wciąż pod nazwą, jaką nadaje plikowi do końca pobierania: .crdownload w Chrome i przeglądarkach opartych na Chromium, .part w przeglądarce Firefox."
+ "value" : "Pliki, których przeglądarka nigdy nie skończyła pobierać, wciąż pod nazwą, jaką nadaje plikowi do końca pobierania: .crdownload w Chrome i przeglądarkach opartych na Chromium, .part w przeglądarce Firefox i .download w Safari."
}
},
"pt" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Downloads que um navegador nunca concluiu, ainda com o nome que ele dá a um arquivo até o fim do download: .crdownload no Chrome e nos navegadores baseados no Chromium, .part no Firefox."
+ "value" : "Downloads que um navegador nunca concluiu, ainda com o nome que ele dá a um arquivo até o fim do download: .crdownload no Chrome e nos navegadores baseados no Chromium, .part no Firefox e .download no Safari."
}
},
"ro" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Descărcări pe care un browser nu le‑a terminat, încă sub numele pe care îl dă unui fișier până la încheierea descărcării: .crdownload pentru Chrome și browserele bazate pe Chromium, .part pentru Firefox."
+ "value" : "Descărcări pe care un browser nu le‑a terminat, încă sub numele pe care îl dă unui fișier până la încheierea descărcării: .crdownload pentru Chrome și browserele bazate pe Chromium, .part pentru Firefox și .download pentru Safari."
}
},
"ru" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Загрузки, которые браузер так и не завершил. У таких файлов все еще временное имя, которое браузер дает файлу до окончания загрузки: .crdownload в Chrome и браузерах на основе Chromium, .part в Firefox."
+ "value" : "Загрузки, которые браузер так и не завершил. У таких файлов все еще временное имя, которое браузер дает файлу до окончания загрузки: .crdownload в Chrome и браузерах на основе Chromium, .part в Firefox и .download в Safari."
}
},
"sv" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Hämtningar som en webbläsare aldrig slutförde, fortfarande under det namn den ger en fil tills hämtningen är klar: .crdownload för Chrome och webbläsarna som bygger på Chromium, .part för Firefox."
+ "value" : "Hämtningar som en webbläsare aldrig slutförde, fortfarande under det namn den ger en fil tills hämtningen är klar: .crdownload för Chrome och webbläsarna som bygger på Chromium, .part för Firefox och .download för Safari."
}
},
"tr" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Bir tarayıcının hiç tamamlamadığı indirmeler; indirme bitene kadar dosyaya verdiği adı hâlâ taşırlar: Chrome ve Chromium tabanlı tarayıcılar için .crdownload, Firefox için .part."
+ "value" : "Bir tarayıcının hiç tamamlamadığı indirmeler; indirme bitene kadar dosyaya verdiği adı hâlâ taşırlar: Chrome ve Chromium tabanlı tarayıcılar için .crdownload, Firefox için .part ve Safari için .download."
}
},
"uk" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Викачування, яких браузер так і не завершив. Файл досі має назву, яку браузер дає йому, доки викачування не закінчиться: .crdownload у Chrome і браузерах на основі Chromium, .part у Firefox."
+ "value" : "Викачування, яких браузер так і не завершив. Файл досі має назву, яку браузер дає йому, доки викачування не закінчиться: .crdownload у Chrome і браузерах на основі Chromium, .part у Firefox і .download у Safari."
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "浏览器未完成的下载,仍使用浏览器在下载结束前为文件指定的名称:Chrome及基于Chromium的浏览器为.crdownload,Firefox为.part。"
+ "value" : "浏览器未完成的下载,仍使用浏览器在下载结束前为文件指定的名称:Chrome及基于Chromium的浏览器为.crdownload,Firefox为.part,Safari浏览器为.download。"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
- "value" : "瀏覽器未完成的下載項目,在下載結束前仍使用瀏覽器為檔案取的名稱:Chrome及以Chromium為基礎的瀏覽器使用.crdownload,Firefox使用.part。"
+ "value" : "瀏覽器未完成的下載項目,在下載結束前仍使用瀏覽器為檔案取的名稱:Chrome及以Chromium為基礎的瀏覽器使用.crdownload,Firefox使用.part,Safari使用.download。"
}
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift b/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift
index caabeab1..452f376e 100644
--- a/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift
@@ -84,9 +84,10 @@ public enum Installers {
static let installerExtensions: Set<String> = ["dmg", "iso", "pkg", "mpkg", "xip"]
static let firmwareExtensions: Set<String> = ["ipsw"]
/// What a browser adds to a download's name until it ends: Chromium's `.crdownload`
- /// (`chrome/browser/download/download_target_determiner.cc`) and Firefox's `.part`
- /// (`netwerk/base/nsIBackgroundFileSaver.idl`).
- static let incompleteDownloadExtensions: Set<String> = ["crdownload", "part"]
+ /// (`chrome/browser/download/download_target_determiner.cc`), Firefox's `.part`
+ /// (`netwerk/base/nsIBackgroundFileSaver.idl`), and Safari's `.download`, a package its Info.plist declares as the
+ /// "Safari download" document type, with the file being written inside.
+ static let incompleteDownloadExtensions: Set<String> = ["crdownload", "part", "download"]
/// A download that changed within this time may still be going, whatever holds it open.
static let stillDownloading: TimeInterval = 24 * 60 * 60
@@ -147,11 +148,13 @@ public enum Installers {
guard isInstaller || isArchive || isIncomplete || firmwareExtensions.contains(suffix),
!exclusions.excludes(url), !exclusions.holds(url), !Task.isCancelled
else { continue }
- let (size, seen) = await measured(url, by: measure)
+ let (size, seen, newestInside) = await measured(url, by: measure)
guard isWorthARow(size, minimumSize) else { continue }
let heldBack = heldBack(url, seen: seen, in: folder, isInTheCloud: isInTheCloud, openFiles: openFiles)
if isIncomplete {
- items.append(incompleteDownload(at: url, size: size, heldBack: heldBack))
+ items.append(
+ incompleteDownload(at: url, size: size, heldBack: heldBack, newestInside: newestInside)
+ )
} else if isArchive {
guard let inside = installerInside(zip: url) else { continue }
let installer = appInstaller(
@@ -269,13 +272,17 @@ public enum Installers {
url.pathExtension.lowercased() == "dmg" && BoundedRead.prefix(of: url, count: 8) == Data("encrcdsa".utf8)
}
- /// What measuring `url` gave: its size, and why what it saw leaves the item for the person to choose.
+ /// What measuring `url` gave: its size, why what it saw leaves the item for the person to choose, and the newest
+ /// write it saw.
private static func measured(
_ url: URL,
by measure: LeftoverScanner.Measure
- ) async -> (size: Int64?, heldBack: HoldBack?) {
+ ) async -> (size: Int64?, heldBack: HoldBack?, newestChange: Date?) {
let contents = await measure(url)
- return (contents.flatMap { $0.couldNotBeRead ? nil : $0.size }, HoldBack.seen(in: contents))
+ return (
+ contents.flatMap { $0.couldNotBeRead ? nil : $0.size }, HoldBack.seen(in: contents),
+ contents?.newestChange
+ )
}
/// True when `size` reaches `minimumSize`. An unknown size could be any size, so it is kept.
@@ -409,7 +416,7 @@ public enum Installers {
where url.pathExtension.lowercased() == "app" && url.lastPathComponent.hasPrefix("Install macOS") {
guard !Task.isCancelled else { return items }
guard !exclusions.excludes(url), !exclusions.holds(url) else { continue }
- let (size, seen) = await measured(url, by: measure)
+ let (size, seen, _) = await measured(url, by: measure)
guard isWorthARow(size, minimumSize) else { continue }
let version = AppInspector.infoDictionary(
in: url.appending(path: "Contents", directoryHint: .isDirectory)
@@ -445,7 +452,7 @@ public enum Installers {
for url in files(in: folder) where firmwareExtensions.contains(url.pathExtension.lowercased()) {
guard !Task.isCancelled else { return items }
guard !exclusions.excludes(url), !exclusions.holds(url) else { continue }
- let (size, heldBack) = await measured(url, by: measure)
+ let (size, heldBack, _) = await measured(url, by: measure)
guard isWorthARow(size, minimumSize) else { continue }
items.append(firmware(at: url, size: size, heldBack: heldBack))
}
@@ -487,7 +494,7 @@ public enum Installers {
for (url, identifier) in found {
guard !Task.isCancelled else { return items }
guard !exclusions.excludes(url), !exclusions.holds(url) else { continue }
- let (size, seen) = await measured(url, by: measure)
+ let (size, seen, _) = await measured(url, by: measure)
guard isWorthARow(size, minimumSize) else { continue }
let isRunning = !NSRunningApplication.runningApplications(withBundleIdentifier: identifier).isEmpty
items.append(InstallerItem(
@@ -533,7 +540,7 @@ public enum Installers {
continue
}
guard !exclusions.excludes(url), !exclusions.holds(url) else { continue }
- let (size, seen) = await measured(url, by: measure)
+ let (size, seen, _) = await measured(url, by: measure)
guard isWorthARow(size, minimumSize) else { continue }
let place = Folder(url: folder, isSharedWithEveryone: false)
let heldBack = heldBack(url, seen: seen, in: place, isInTheCloud: isInTheCloud, openFiles: openFiles)
@@ -547,9 +554,12 @@ public enum Installers {
}
/// Makes the item for an unfinished download. One that changed within `stillDownloading` may still be going, so
- /// it is left for the person to choose.
- static func incompleteDownload(at url: URL, size: Int64?, heldBack: HoldBack?) -> InstallerItem {
- let changed = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate
+ /// it is left for the person to choose. A package changes when the file growing inside it does (`newestInside`).
+ static func incompleteDownload(
+ at url: URL, size: Int64?, heldBack: HoldBack?, newestInside: Date?
+ ) -> InstallerItem {
+ let own = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate
+ let changed = [own, newestInside].compactMap(\.self).max()
let isRecent = changed.map { Date.now.timeIntervalSince($0) < stillDownloading } ?? true
return InstallerItem(
url: url,
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift
index cde06d44..d4ad3588 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift
@@ -356,6 +356,32 @@ struct InstallersTests {
#expect(items["Archive.zip.part"]?.heldBack == .changedRecently)
}
+ /// Safari keeps a download in a `.download` package until it ends. The package is the unfinished download, and
+ /// the file growing inside it is what says when it last changed.
+ @Test func findsSafarisUnfinishedDownloadsByTheirNewestWrite() async throws {
+ let directory = try TemporaryDirectory()
+ let abandoned = try directory.directory("Downloads/Movie.mov.download")
+ let abandonedFile = try directory.file("Downloads/Movie.mov.download/Movie.mov", bytes: 400_000)
+ let going = try directory.directory("Downloads/Disk.dmg.download")
+ try directory.file("Downloads/Disk.dmg.download/Disk.dmg", bytes: 400_000)
+ try directory.directory("Applications")
+ let old: [FileAttributeKey: Any] = [.modificationDate: Date.now.addingTimeInterval(-3 * 24 * 60 * 60)]
+ for url in [abandonedFile, abandoned, going] {
+ try FileManager.default.setAttributes(old, ofItemAtPath: url.path(percentEncoded: false))
+ }
+
+ let scan = await Installers.scan(
+ installedApps: [], home: directory.url, root: directory.url, exclusions: .none, minimumSize: 100_000,
+ measure: LeftoverScanner.walk, openFiles: OpenFiles(excluding: nil)
+ )
+
+ let items = Dictionary(uniqueKeysWithValues: scan.items.map { ($0.name, $0) })
+ #expect(Set(items.keys) == ["Movie.mov.download", "Disk.dmg.download"])
+ #expect(items.values.allSatisfy { $0.kind == .incompleteDownload && ($0.size ?? 0) >= 400_000 })
+ #expect(items["Movie.mov.download"]?.heldBack == .some(nil))
+ #expect(items["Disk.dmg.download"]?.heldBack == .changedRecently)
+ }
+
@Test func findsPackagesKeptInApplicationSupportAndLeavesThemToChoose() async throws {
let directory = try TemporaryDirectory()
try directory.file("Library/Application Support/org.example.Studio/Updates/Studio-2.4.pkg", bytes: 400_000)
diff --git a/Peel/Model/InstallerLibrary.swift b/Peel/Model/InstallerLibrary.swift
index f5638678..eac11ebb 100644
--- a/Peel/Model/InstallerLibrary.swift
+++ b/Peel/Model/InstallerLibrary.swift
@@ -98,7 +98,7 @@ nonisolated extension InstallerItem.Kind {
case .macOSInstaller: "A full copy of macOS, ready to install. Apple offers the newest release again to any Mac that can run it."
case .firmware: "Firmware for restoring Apple devices, such as an iPhone, an iPad, or a Mac. It is downloaded again when a device needs it."
case .deviceBackup: "Almost all of a device’s data and settings, backed up to this Mac. Peel shows what is here and leaves the rest to Finder."
- case .incompleteDownload: "Downloads a browser never finished, still under the name it gives a file until the download ends: .crdownload for Chrome and the browsers built on Chromium, .part for Firefox."
+ case .incompleteDownload: "Downloads a browser never finished, still under the name it gives a file until the download ends: .crdownload for Chrome and the browsers built on Chromium, .part for Firefox, and .download for Safari."
case .updateDownload: "Updates an app downloaded with Sparkle or Squirrel and keeps in its caches until it installs them. If one is gone, the app downloads it again the next time it updates."
}
}