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.

Judge an installer by where it says it was downloaded from

Țugui Dragoșd15181d849c5
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 4a65d3b8..62abc900 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -388,14 +388,15 @@ macOS asks the user to approve it once. It talks to the app over XPC.
are open (`movableNow`). An area only its own app or tool should empty is explained, with that app's or tool's own
step.
- **Installers and Backups.** `Installers.scan` looks in Downloads, Desktop, Documents, Public, and `/Users/Shared`,
- and in the folders directly inside them, for disk images, packages, archives that hold an app or an installer (a
- zip is looked into), downloads a browser never finished, and device firmware, then at the macOS installers there and
- in `/Applications`, the updates Sparkle, Squirrel, and electron-updater keep until they install them, the packages
- apps keep in Application Support, and, with Full Disk Access, the device backups, which it only lists. What is smaller
+ and in the folders directly inside them, for disk images, packages, archives that hold an app or an installer (a zip
+ is looked into), downloads a browser never finished, and device firmware, then at the macOS installers there and in
+ `/Applications`, the updates Sparkle, Squirrel, and electron-updater keep until they install them, the packages apps
+ keep in Application Support, and, with Full Disk Access, the device backups, which it only lists. What is smaller
than `minimumSize` isn't listed, a backup whatever its size. What it suggests can be downloaded again: an installed
- app's installer, one in Downloads, a macOS installer, firmware, a browser's unfinished download a day after its last
- change, and an update whose app is closed. The rest is held back, such as what changed in the last day, what a
- program has open or is mounted, what syncs to other devices, and what is in `/Users/Shared`.
+ app's installer, one that says where it was downloaded from (`DownloadOrigins`), a macOS installer, firmware, a
+ browser's unfinished download a day after its last change, and an update whose app is closed. The rest is held back,
+ such as an installer that arrived in the last hour, what changed in the last day, what a program has open or is
+ mounted, what syncs to other devices, and what is in `/Users/Shared`.
- **Developer.** `DeveloperCaches.definitions` names each tool's folders, under the home folder, the account's cache
folder, or its temporary folder, each with what it holds (`ContentKind`) and where the tool documents it, a page or
a file in its repository at a commit, which the tests hold. Only what one tool owns outright is listed: no toolchain
diff --git a/GUIDE.md b/GUIDE.md
index 7d4d13aa..b0e0cb3f 100644
--- a/GUIDE.md
+++ b/GUIDE.md
@@ -121,19 +121,19 @@ Space shows what fills your disk, area by area, and what each area is.
other devices too: beside a copy on this Mac it is marked Stays, and a group whose every copy syncs is listed under
Synced to Other Devices. A chosen folder Peel doesn't scan, such as a repository, is named with why, in Scan Settings
and with the result.
-- **Installers and Backups:** disk images and packages in Downloads, Desktop, Documents, Public, and Shared, and in the
- folders directly inside them, where installers are usually left, with archives there that hold an app or an installer.
- It also lists packages an app keeps in Application Support, macOS installers, device firmware, downloads never
- finished, and updates apps downloaded and keep until they install them. Your iPhone and iPad backups are listed with
- their size once Peel has Full Disk Access, and never moved. Nothing is selected for you, and Select Recommended takes
- only what you can download again, such as an installed app's installer, any installer in Downloads, a macOS installer,
- device firmware, a download a browser never finished once it hasn't changed for a day, or an update whose app is
- closed. It passes by an encrypted disk image, an installer elsewhere that is no installed app's, a package
- an app keeps for itself, a download that changed in the last day, a `.part` file no browser left, which a torrent
- client or another program that resumes downloads may still finish, an update whose app is open, and anything in
- Shared, open in a program, open as a disk image, or syncing to your other devices. 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.
+- **Installers and Backups:** disk images and packages in Downloads, Desktop, Documents, Public, and Shared, and in
+ the folders directly inside them, where installers are usually left, with archives there that hold an app or an
+ installer. It also lists packages an app keeps in Application Support, macOS installers, device firmware, downloads
+ never finished, and updates apps downloaded and keep until they install them. Your iPhone and iPad backups are
+ listed with their size once Peel has Full Disk Access, and never moved. Nothing is selected for you, and Select
+ Recommended takes only what you can download again, such as an installed app's installer, one that says where it was
+ downloaded from, a macOS installer, device firmware, a download a browser never finished once it hasn't changed for
+ a day, or an update whose app is closed. It passes by an encrypted disk image, an installer that is no installed
+ app's and doesn't say where it came from, one that arrived or changed in the last hour, a package an app keeps for
+ itself, a download that changed in the last day, a `.part` file no browser left, which a torrent client or another
+ program that resumes downloads may still finish, an update whose app is open, and anything in Shared, open in a
+ program, open as a disk image, or syncing to your other devices. 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
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index 208cafbb..fb016e34 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -104153,6 +104153,113 @@
}
}
},
+ "Not selected: this arrived or changed in the last hour, so you may be installing from it now." : {
+ "comment" : "The note beside an installer in Installers and Backups that was downloaded, copied, or moved into its folder, or changed, in the last hour.",
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Nevybráno: tento soubor sem za poslední hodinu přibyl nebo se změnil, takže z něj možná právě instalujete."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Nicht ausgewählt: Dieses Objekt ist innerhalb der letzten Stunde hinzugekommen oder wurde geändert, daher installierst du möglicherweise gerade etwas damit."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Sin seleccionar: ha llegado o ha cambiado en la última hora, así que puede que estés instalando desde él ahora mismo."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Non sélectionné : cet élément est arrivé ou a changé au cours de la dernière heure, et vous l’utilisez peut-être pour une installation en ce moment."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Non selezionato: è arrivato o è cambiato nell’ultima ora, quindi potresti starlo usando per un’installazione in corso."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "未選択: 過去1時間以内に追加または変更されたため、現在これを使ってインストールしている可能性があります。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "선택되지 않음: 이 파일은 지난 1시간 사이에 추가되거나 변경되었으므로, 지금 이 파일로 설치하는 중일 수 있습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Niet geselecteerd: dit is in het afgelopen uur binnengekomen of gewijzigd, dus misschien ben je er nu mee aan het installeren."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Nie zaznaczono: ten plik pojawił się lub został zmieniony w ciągu ostatniej godziny, więc być może właśnie z niego instalujesz."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Não selecionado: este item chegou ou foi alterado na última hora, então talvez você esteja instalando algo a partir dele agora."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Neselectat: acest articol a ajuns aici sau s‑a modificat în ultima oră, așa că este posibil să instalați din el chiar acum."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Не выбрано: этот файл появился или изменился за последний час, поэтому, возможно, Вы сейчас что-то из него устанавливаете."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Inte markerad: den här filen har kommit hit eller ändrats under den senaste timmen, så du kanske installerar från den just nu."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Seçilmedi: bu dosya son bir saat içinde geldi veya değişti, bu nedenle şu anda ondan yükleme yapıyor olabilirsiniz."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Не вибрано: цей файл зʼявився або змінився за останню годину, тож, можливо, ви саме зараз із нього інсталюєте."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "未选择:此文件是在过去一小时内添加或更改的,因此你可能正在使用它进行安装。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "未選取:此項目在過去一小時內出現或有變更,因此你可能正在用它進行安裝。"
+ }
+ }
+ }
+ },
"Not selected: this changed in the last day, so it may still be downloading." : {
"localizations" : {
"cs" : {
@@ -105319,108 +105426,109 @@
}
}
},
- "Not selected: this isn’t in Downloads and isn’t an installed app’s installer, so it may be yours rather than something you can download again." : {
+ "Not selected: this isn’t an installed app’s installer and nothing shows where it was downloaded from, so it may be your only copy." : {
+ "comment" : "The note beside an installer in Installers and Backups that is no installed app's and carries no address it was downloaded from, as a browser writes on a download. Such a file may have been copied from a disk and exist nowhere else.",
"localizations" : {
"cs" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Nevybráno: tento soubor není ve složce Stahování a není to instalátor nainstalované aplikace, takže může být váš vlastní, a ne něco, co si můžete znovu stáhnout."
+ "value" : "Nevybráno: tento soubor není instalátor nainstalované aplikace a nic neukazuje, odkud byl stažen, takže může být vaší jedinou kopií."
}
},
"de" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Nicht ausgewählt: Dieses Objekt liegt nicht in „Downloads“ und ist nicht der Installer einer installierten App, daher ist es möglicherweise deines und nicht etwas, das du erneut laden kannst."
+ "value" : "Nicht ausgewählt: Dieses Objekt ist nicht der Installer einer installierten App, und nichts zeigt, woher es geladen wurde, daher ist es möglicherweise deine einzige Kopie."
}
},
"es" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Sin seleccionar: no está en Descargas ni es el instalador de una app instalada, así que puede que sea tuyo y no algo que puedas volver a descargar."
+ "value" : "Sin seleccionar: no es el instalador de una app instalada y nada indica de dónde se descargó, así que puede que sea tu única copia."
}
},
"fr" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Non sélectionné : ce fichier ne se trouve pas dans le dossier Téléchargements et n’est pas le programme d’installation d’une app installée ; il s’agit donc peut-être de l’un de vos fichiers, et non de quelque chose que vous pouvez télécharger à nouveau."
+ "value" : "Non sélectionné : ce fichier n’est pas le programme d’installation d’une app installée et rien n’indique d’où il a été téléchargé ; il s’agit donc peut-être de votre seule copie."
}
},
"it" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Non selezionato: non si trova nella cartella Download e non è l’installer di un’app installata, quindi potrebbe essere un tuo file anziché qualcosa che puoi scaricare di nuovo."
+ "value" : "Non selezionato: non è l’installer di un’app installata e nulla indica da dove è stato scaricato, quindi potrebbe essere la tua unica copia."
}
},
"ja" : {
"stringUnit" : {
"state" : "translated",
- "value" : "未選択: これは“ダウンロード”フォルダになく、インストール済みのアプリのインストーラでもないため、再ダウンロードできるものではなく、自分のファイルである可能性があります。"
+ "value" : "未選択: これはインストール済みのアプリのインストーラではなく、どこからダウンロードされたかを示す情報もないため、唯一のコピーである可能性があります。"
}
},
"ko" : {
"stringUnit" : {
"state" : "translated",
- "value" : "선택되지 않음: 이 파일은 다운로드 폴더에 있지 않고 설치된 앱의 설치 프로그램도 아니므로, 다시 다운로드할 수 있는 항목이 아니라 사용자의 파일일 수 있습니다."
+ "value" : "선택되지 않음: 이 파일은 설치된 앱의 설치 프로그램이 아니며 어디에서 다운로드되었는지 보여 주는 정보도 없으므로, 사용자의 유일한 복사본일 수 있습니다."
}
},
"nl" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Niet geselecteerd: dit staat niet in de map Downloads en is geen installatieprogramma van een geïnstalleerde app, dus het is misschien van jou en niet iets wat je opnieuw kunt downloaden."
+ "value" : "Niet geselecteerd: dit is geen installatieprogramma van een geïnstalleerde app en niets geeft aan waar het vandaan is gedownload, dus het is misschien je enige kopie."
}
},
"pl" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Nie zaznaczono: ten plik nie jest w folderze Pobrane rzeczy ani nie jest instalatorem zainstalowanej aplikacji, więc może to być Twój plik, a nie coś, co możesz pobrać ponownie."
+ "value" : "Nie zaznaczono: ten plik nie jest instalatorem zainstalowanej aplikacji i nic nie wskazuje, skąd został pobrany, więc może to być Twoja jedyna kopia."
}
},
"pt" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Não selecionado: este item não está em Downloads e não é o instalador de um app instalado, então pode ser seu, e não algo que você possa baixar de novo."
+ "value" : "Não selecionado: este item não é o instalador de um app instalado e nada indica de onde ele foi baixado, então pode ser a sua única cópia."
}
},
"ro" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Neselectat: acest fișier nu se află în Descărcări și nu este programul de instalare al unei aplicații instalate, așa că ar putea fi al dvs., nu ceva ce puteți descărca din nou."
+ "value" : "Neselectat: acest fișier nu este programul de instalare al unei aplicații instalate și nimic nu arată de unde a fost descărcat, așa că ar putea fi singura dvs. copie."
}
},
"ru" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Не выбрано: этот файл находится не в папке «Загрузки» и не является установщиком ни одного из установленных приложений, поэтому он может быть Вашим собственным, а не тем, что можно загрузить снова."
+ "value" : "Не выбрано: этот файл не является установщиком ни одного из установленных приложений, и ничто не указывает, откуда он был загружен, поэтому, возможно, это Ваша единственная копия."
}
},
"sv" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Inte markerad: den här filen ligger inte i Hämtade filer och är inte installeraren för en installerad app, så den kan vara din egen snarare än något som du kan hämta igen."
+ "value" : "Inte markerad: den här filen är inte installeraren för en installerad app och inget visar var den hämtades från, så den kan vara din enda kopia."
}
},
"tr" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Seçilmedi: bu dosya İndirilenler klasöründe değil ve yüklü bir uygulamanın yükleyicisi de değil, bu nedenle yeniden indirebileceğiniz bir şey yerine size ait bir dosya olabilir."
+ "value" : "Seçilmedi: bu dosya yüklü bir uygulamanın yükleyicisi değil ve nereden indirildiğini gösteren hiçbir şey yok, bu nedenle tek kopyanız olabilir."
}
},
"uk" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Не вибрано: цей файл не міститься в папці «Викачане» й не є інсталятором інстальованої програми, тож, можливо, він ваш, а не з тих, що можна викачати знову."
+ "value" : "Не вибрано: цей файл не є інсталятором інстальованої програми, і ніщо не вказує, звідки його викачано, тож, можливо, це ваша єдина копія."
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "未选择:此文件不在“下载”文件夹中,也不是已安装App的安装器,因此可能是你自己的文件,而不是可以重新下载的内容。"
+ "value" : "未选择:此文件不是已安装App的安装器,也没有任何信息表明它是从哪里下载的,因此它可能是你仅有的副本。"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
- "value" : "未選取:此項目不在「下載項目」中,也不是已安裝App的安裝程式,因此可能是你自己的,而不是你可以重新下載的項目。"
+ "value" : "未選取:此項目不是已安裝App的安裝程式,也沒有任何資訊顯示它是從哪裡下載的,因此它可能是你僅有的副本。"
}
}
}
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
index 3b3215cb..8e5def6e 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
@@ -396,12 +396,13 @@ extension HoldBack {
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"
+ case .arrivedRecently: "arrived or changed in the last hour, so it may be in use"
case .mayStillBeResumed: "a program that resumes downloads, such as a torrent client, may still finish it"
case .writtenRecently: "written to in the last 15 minutes, so a program may still be using it"
case .serverStillListens: "a server still listens on the port it is named for and keeps its uploads here"
case .keptByAnApp: "in an app's folder in Application Support, and the app may still need it"
case .appIsRunning: "its app is running and may install this update when it quits"
- case .mayBeTheOnlyCopy: "outside Downloads and no installed app's installer, so it may be yours, not a download"
+ case .mayBeTheOnlyCopy: "no installed app's installer and no sign of where it was downloaded from"
case .encryptedImage: "an encrypted disk image, which holds what you put in it"
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/DownloadOrigins.swift b/Packages/PeelCore/Sources/PeelCore/Apps/DownloadOrigins.swift
index c5e563ff..fa67c10b 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/DownloadOrigins.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/DownloadOrigins.swift
@@ -1,14 +1,18 @@
public import Foundation
import SQLite3
-/// Where an app was downloaded from, as macOS recorded it: the address a browser writes on the file itself
-/// (`com.apple.metadata:kMDItemWhereFroms`), or else the download that the app's quarantine record points to in
-/// Launch Services' quarantine database. An app copied out of a downloaded disk image carries such a record. The
+/// Where an app or a file was downloaded from, as macOS recorded it: the address a browser writes on the file itself
+/// (`com.apple.metadata:kMDItemWhereFroms`), or else the download that its quarantine record points to in Launch
+/// Services' quarantine database. An app copied out of a downloaded disk image carries such a record. The
/// database belongs to the user, is outside TCC, and is opened read-only. Only a web address is kept, and only up
/// to its path: a signed download link carries a token after it, and an inventory is meant to be read elsewhere.
public struct DownloadOrigins: Sendable {
public static var onThisMac: DownloadOrigins {
- DownloadOrigins(events: URL.homeDirectory.appending(path: "Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2"))
+ inHome(.homeDirectory)
+ }
+
+ static func inHome(_ home: URL) -> DownloadOrigins {
+ DownloadOrigins(events: home.appending(path: "Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2"))
}
let events: URL
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
index 6a4b7abc..6df17cb6 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
@@ -140,6 +140,8 @@ public enum HoldBack: String, Sendable, Hashable {
case attachedDiskImage
/// A download that changed within the last day, which may still be going.
case changedRecently
+ /// An installer that arrived in its folder or changed in the last hour, which the person may be installing from.
+ case arrivedRecently
/// A `.part` file no browser left, which a program that resumes downloads, such as a torrent client, may still
/// finish.
case mayStillBeResumed
@@ -153,7 +155,7 @@ public enum HoldBack: String, Sendable, Hashable {
case packageLeftMore
/// An update whose app is running, which may install it when it quits.
case appIsRunning
- /// An installer outside Downloads that is no installed app's, which may be the person's own rather than a download.
+ /// An installer that is no installed app's and says nowhere where it was downloaded from: it may be the only copy.
case mayBeTheOnlyCopy
/// An encrypted disk image, which holds what the person put in it.
case encryptedImage
diff --git a/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift b/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift
index 05b2ec0f..995d7507 100644
--- a/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift
@@ -118,6 +118,8 @@ public enum Installers {
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
+ /// An installer that arrived or changed within this time may be the one the person is installing from now.
+ static let justArrived: TimeInterval = 60 * 60
@concurrent
public static func scan(
@@ -154,19 +156,16 @@ public enum Installers {
var items: [InstallerItem] = []
var unreadable: [URL] = []
let places = ["Downloads", "Desktop", "Documents", "Public"].map {
- Folder(
- url: home.appending(path: $0, directoryHint: .isDirectory),
- isSharedWithEveryone: false,
- holdsDownloads: $0 == "Downloads"
- )
+ Folder(url: home.appending(path: $0, directoryHint: .isDirectory), isSharedWithEveryone: false)
} + [Folder(url: root.appending(path: "Users/Shared", directoryHint: .isDirectory), isSharedWithEveryone: true)]
+ let origins = DownloadOrigins.inHome(home).reader()
var folders: [Folder] = []
// A scan its page left asks nothing more: reading a folder macOS guards puts up macOS's question again.
for place in places {
guard !Task.isCancelled else { break }
if canList(place.url) == .missing { unreadable.append(place.url) }
folders += [place] + subfolders(of: place.url).map {
- Folder(url: $0, isSharedWithEveryone: place.isSharedWithEveryone, holdsDownloads: place.holdsDownloads)
+ Folder(url: $0, isSharedWithEveryone: place.isSharedWithEveryone)
}
}
@@ -194,10 +193,10 @@ public enum Installers {
let installer = appInstaller(
at: url, size: size, heldBack: heldBack, installedApps: installedApps, named: inside
)
- items.append(unlessItCanBeDownloadedAgain(installer, in: folder))
+ items.append(unlessItMayStillBeNeeded(installer, origins: origins))
} else if isInstaller {
let installer = appInstaller(at: url, size: size, heldBack: heldBack, installedApps: installedApps)
- items.append(unlessItCanBeDownloadedAgain(installer, in: folder))
+ items.append(unlessItMayStillBeNeeded(installer, origins: origins))
} else {
items.append(firmware(at: url, size: size, heldBack: heldBack))
}
@@ -257,12 +256,10 @@ public enum Installers {
)
}
- /// A folder the scan looks in, whether it belongs to every account on this Mac rather than to this one, and
- /// whether it is Downloads or a folder inside it.
+ /// A folder the scan looks in, and whether it belongs to every account on this Mac rather than to this one.
struct Folder {
let url: URL
let isSharedWithEveryone: Bool
- var holdsDownloads = false
}
/// The folders directly inside `place` that the scan looks in too, where a browser or a chat app keeps its
@@ -290,19 +287,31 @@ public enum Installers {
return folder.isSharedWithEveryone ? .sharedWithEveryone : nil
}
- /// Holds back an app installer that may not be downloaded again: one outside Downloads that is no installed app's
- /// may be the person's own image, and an encrypted disk image holds what they put in it.
- private static func unlessItCanBeDownloadedAgain(_ installer: InstallerItem, in folder: Folder) -> InstallerItem {
+ /// Holds back an app installer the person may still need: an encrypted disk image holds what they put in it, one
+ /// that is no installed app's and says nowhere where it was downloaded from may be the only copy, and one that
+ /// arrived or changed within `justArrived` may be the one they are installing from.
+ private static func unlessItMayStillBeNeeded(
+ _ installer: InstallerItem, origins: DownloadOrigins.Reader
+ ) -> InstallerItem {
guard installer.heldBack == nil else { return installer }
var installer = installer
if isEncryptedImage(installer.url) {
installer.heldBack = .encryptedImage
- } else if installer.installedApp == nil, !folder.holdsDownloads {
+ } else if installer.installedApp == nil, origins.address(of: installer.url) == nil {
installer.heldBack = .mayBeTheOnlyCopy
+ } else if arrivedRecently(installer.url) {
+ installer.heldBack = .arrivedRecently
}
return installer
}
+ /// Whether `url` arrived in its folder or changed within `justArrived`, or when that can't be told.
+ private static func arrivedRecently(_ url: URL) -> Bool {
+ let values = try? url.resourceValues(forKeys: [.contentModificationDateKey, .addedToDirectoryDateKey])
+ let latest = [values?.contentModificationDate, values?.addedToDirectoryDate].compactMap(\.self).max()
+ return latest.map { Date.now.timeIntervalSince($0) < justArrived } ?? true
+ }
+
/// Whether `url` is an encrypted disk image: one that `hdiutil create -encryption` makes begins with `encrcdsa`.
static func isEncryptedImage(_ url: URL) -> Bool {
url.pathExtension.lowercased() == "dmg" && BoundedRead.prefix(of: url, count: 8) == Data("encrcdsa".utf8)
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift
index 6012c3b7..29b7083d 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift
@@ -177,15 +177,21 @@ struct InstallersTests {
#expect(installers.allSatisfy { !$0.isReadOnly })
}
+ /// An installer can be downloaded again when it is an installed app's, or when it says where it was downloaded
+ /// from, wherever it is kept. One that says nothing may be the only copy, in Downloads too.
@Test func recommendsOnlyAnInstallerThatCanBeDownloadedAgain() async throws {
let directory = try TemporaryDirectory()
let unknown = try directory.file("Downloads/Unknown-1.dmg", bytes: 400_000)
+ let fromTheWeb = try directory.file("Documents/FromTheWeb-2.dmg", bytes: 400_000)
+ let copied = try directory.file("Downloads/Copied-3.pkg", bytes: 400_000)
let known = try directory.file("Documents/VisualStudioCode-1.99.0.dmg", bytes: 400_000)
let photos = try directory.file("Documents/Photos 2019.dmg", bytes: 400_000)
let backup = try directory.file("Desktop/Backup.iso", bytes: 400_000)
let secrets = try directory.directory("Downloads").appending(path: "Secrets.dmg")
try makeEncryptedImage(at: secrets)
try directory.directory("Applications")
+ for url in [unknown, fromTheWeb] { try downloaded(url) }
+ for url in [copied, known, photos, backup, secrets] { try age(url, changedHoursAgo: 2, addedHoursAgo: 2) }
let scan = await Installers.scan(
installedApps: [app("Visual Studio Code", bundleIdentifier: "com.microsoft.VSCode")],
@@ -196,15 +202,69 @@ struct InstallersTests {
let heldBack = Dictionary(uniqueKeysWithValues: scan.items.map { ($0.name, $0.heldBack) })
#expect(heldBack["Unknown-1.dmg"] == .some(nil))
+ #expect(heldBack["FromTheWeb-2.dmg"] == .some(nil))
+ #expect(heldBack["Copied-3.pkg"] == .mayBeTheOnlyCopy)
#expect(heldBack["VisualStudioCode-1.99.0.dmg"] == .some(nil))
#expect(heldBack["Photos 2019.dmg"] == .mayBeTheOnlyCopy)
#expect(heldBack["Backup.iso"] == .mayBeTheOnlyCopy)
#expect(heldBack["Secrets.dmg"] == .encryptedImage)
let rows = scan.items.selectableRows(canUseHelper: false)
#expect(Set(rows.recommended.map { PathPattern.comparablePath(of: $0) })
- == Set([unknown, known].map { PathPattern.comparablePath(of: $0) }))
+ == Set([unknown, fromTheWeb, known].map { PathPattern.comparablePath(of: $0) }))
#expect(Set(rows.notRecommendedAdded(by: []).map { PathPattern.comparablePath(of: $0) })
- == Set([photos, backup, secrets].map { PathPattern.comparablePath(of: $0) }))
+ == Set([copied, photos, backup, secrets].map { PathPattern.comparablePath(of: $0) }))
+ }
+
+ /// An installer that arrived in its folder or changed in the last hour may be the one being installed from now.
+ @Test func holdsBackAnInstallerThatJustArrived() async throws {
+ let directory = try TemporaryDirectory()
+ let fresh = try directory.file("Downloads/Fresh-1.dmg", bytes: 400_000)
+ let moved = try directory.file("Documents/Moved-2.dmg", bytes: 400_000)
+ let old = try directory.file("Downloads/Old-3.dmg", bytes: 400_000)
+ try directory.directory("Applications")
+ for url in [fresh, moved, old] {
+ try whereFrom(url, "https://example.com/\(url.lastPathComponent)")
+ }
+ try age(moved, changedHoursAgo: 2, addedHoursAgo: 0)
+ try age(old, changedHoursAgo: 2, addedHoursAgo: 2)
+
+ let scan = await Installers.scan(
+ installedApps: [], home: directory.url, root: directory.url, minimumSize: 100_000
+ )
+
+ let heldBack = Dictionary(uniqueKeysWithValues: scan.items.map { ($0.name, $0.heldBack) })
+ #expect(heldBack["Fresh-1.dmg"] == .arrivedRecently)
+ #expect(heldBack["Moved-2.dmg"] == .arrivedRecently)
+ #expect(heldBack["Old-3.dmg"] == .some(nil))
+ }
+
+ /// Marks `url` as downloaded from the web, as a browser does, two hours ago.
+ private func downloaded(_ url: URL) throws {
+ try whereFrom(url, "https://example.com/\(url.lastPathComponent)")
+ try age(url, changedHoursAgo: 2, addedHoursAgo: 2)
+ }
+
+ /// Writes the address a browser writes on a download, as a binary property list of addresses.
+ private func whereFrom(_ url: URL, _ address: String) throws {
+ let data = try PropertyListSerialization.data(fromPropertyList: [address], format: .binary, options: 0)
+ let result = data.withUnsafeBytes { bytes in
+ setxattr(url.path(percentEncoded: false), "com.apple.metadata:kMDItemWhereFroms", bytes.baseAddress,
+ data.count, 0, 0)
+ }
+ try #require(result == 0)
+ }
+
+ /// Dates `url` as changed and as added to its folder so many hours ago (`setattrlist(2)` sets the second).
+ private func age(_ url: URL, changedHoursAgo changed: Double, addedHoursAgo added: Double) throws {
+ let path = url.path(percentEncoded: false)
+ try FileManager.default.setAttributes(
+ [.modificationDate: Date.now.addingTimeInterval(-changed * 3_600)], ofItemAtPath: path
+ )
+ var list = attrlist()
+ list.bitmapcount = u_short(ATTR_BIT_MAP_COUNT)
+ list.commonattr = attrgroup_t(ATTR_CMN_ADDEDTIME)
+ var time = timespec(tv_sec: Int(Date.now.addingTimeInterval(-added * 3_600).timeIntervalSince1970), tv_nsec: 0)
+ try #require(setattrlist(path, &list, &time, MemoryLayout<timespec>.size, 0) == 0)
}
private func makeEncryptedImage(at url: URL) throws {
@@ -239,7 +299,7 @@ struct InstallersTests {
/// A repository, a project, a package, and a link are never looked into: what is in them is work or is theirs.
@Test func looksOneFolderDownInEveryPlaceInstallersAreLeft() async throws {
let directory = try TemporaryDirectory()
- try directory.file("Downloads/Chat Desktop/Tool-1.dmg", bytes: 400_000)
+ try downloaded(try directory.file("Downloads/Chat Desktop/Tool-1.dmg", bytes: 400_000))
try directory.file("Public/Drop Box/Other-2.pkg", bytes: 400_000)
try directory.file("Users/Shared/Old-3.dmg", bytes: 400_000)
try directory.file("Downloads/a/b/Deep-4.dmg", bytes: 400_000)
@@ -309,7 +369,7 @@ struct InstallersTests {
try directory.file("Documents/Tool-2.dmg", bytes: 400_000)
try directory.directory("Documents/Install macOS Tahoe.app/Contents")
try directory.file("Documents/Install macOS Tahoe.app/Contents/MacOS/app", bytes: 400_000)
- try directory.file("Downloads/Other-3.dmg", bytes: 400_000)
+ try downloaded(try directory.file("Downloads/Other-3.dmg", bytes: 400_000))
let documents = PathPattern.comparablePath(of: directory.url.appending(path: "Documents"))
let scan = await Installers.scan(
@@ -354,7 +414,7 @@ struct InstallersTests {
let directory = try TemporaryDirectory()
try directory.directory("Documents/.stfolder")
try directory.file("Documents/Tool-2.dmg", bytes: 400_000)
- try directory.file("Downloads/Other-3.dmg", bytes: 400_000)
+ try downloaded(try directory.file("Downloads/Other-3.dmg", bytes: 400_000))
let scan = await Installers.scan(
installedApps: [], home: directory.url, root: directory.url, exclusions: .none, minimumSize: 100_000,
@@ -561,7 +621,7 @@ struct InstallersTests {
@Test func aDownloadAProgramStillHasOpenIsLeftForThePersonToChoose() async throws {
let directory = try TemporaryDirectory()
let downloading = try directory.file("Downloads/Tool-1.dmg", bytes: 400_000)
- try directory.file("Downloads/Other-2.dmg", bytes: 400_000)
+ try downloaded(try directory.file("Downloads/Other-2.dmg", bytes: 400_000))
try directory.directory("Applications")
let writer = try FileHandle(forWritingTo: downloading)
defer { try? writer.close() }
@@ -644,7 +704,7 @@ struct InstallersTests {
let directory = try TemporaryDirectory()
try directory.directory("Applications")
let image = try AttachedImage(at: directory.url.appending(path: "Downloads/Tool.dmg"))
- try directory.file("Downloads/Other.dmg", bytes: 400_000)
+ try downloaded(try directory.file("Downloads/Other.dmg", bytes: 400_000))
let scan = await Installers.scan(
installedApps: [], home: directory.url, root: directory.url, minimumSize: 100_000
diff --git a/Peel/Views/Presentation.swift b/Peel/Views/Presentation.swift
index cf9e6d04..c3c2396c 100644
--- a/Peel/Views/Presentation.swift
+++ b/Peel/Views/Presentation.swift
@@ -412,6 +412,8 @@ extension HoldBack {
"Not selected: this disk image is open right now. Eject it first."
case .changedRecently:
"Not selected: this changed in the last day, so it may still be downloading."
+ case .arrivedRecently:
+ "Not selected: this arrived or changed in the last hour, so you may be installing from it now."
case .mayStillBeResumed:
"Not selected: a program that resumes downloads, such as a torrent client, may still finish this."
case .writtenRecently:
@@ -423,7 +425,7 @@ extension HoldBack {
case .appIsRunning:
"Not selected: the app is running and may install this update when it quits."
case .mayBeTheOnlyCopy:
- "Not selected: this isn’t in Downloads and isn’t an installed app’s installer, so it may be yours rather than something you can download again."
+ "Not selected: this isn’t an installed app’s installer and nothing shows where it was downloaded from, so it may be your only copy."
case .encryptedImage:
"Not selected: an encrypted disk image holds what you put in it."
}
diff --git a/SAFETY.md b/SAFETY.md
index 6f0aced3..1b7390f8 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -413,8 +413,9 @@ Never selected for you, even when found:
- A file a program has open right now, and a disk image that is open right now.
- An installer package an app keeps in Application Support, which the app may still need, and an update whose app is
running, which may install it when the app quits.
-- An encrypted disk image, and a disk image, package, or archive outside Downloads that isn't an installed app's
- installer, which may be your own rather than something you can download again.
+- An encrypted disk image, a disk image, package, or archive that isn't an installed app's installer and doesn't say
+ where it was downloaded from, in Downloads too, which may be your only copy, and one that arrived or changed in the
+ last hour, which you may be installing from.
- A build folder Git tracks files in, and a folder an installer package made that now holds what something else put
there, which may be another program's files or yours.