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
Leave a build folder Git tracks to the person in Build Artifacts
Țugui Dragoș561c43bbb801
diff --git a/GUIDE.md b/GUIDE.mdindex 0b3ee360..ccef2eea 100644--- a/GUIDE.md+++ b/GUIDE.md@@ -94,15 +94,16 @@ copied from your devices, model weights, installed packages, what a tool keeps fboxes, Asset Store packages, Godot's export templates), an editor's saved state for a project that no longerexists, and a cache with a wallet, a signing key, or a password database inside. Nothing is selected for you.-**Build Artifacts:** what builds left in the folders you choose, like `node_modules`, `DerivedData`, `target`,-`.nuxt`, `__pycache__`, Unity's `Library`, and any folder its tool tagged as a cache (`CACHEDIR.TAG`), each only-when a file of the tool that makes it proves it. Nothing is selected for you, and Select Recommended passes by a-project changed in the last 7 days, installed packages (a Python environment, `vendor`, Terraform's `.terraform`),-and a folder like `target` whose name says nothing on its own. Until you choose a folder, Peel offers `~/Developer`,-`~/Projects`, `~/Code`, or `~/src` when you have one, and adds it only when you say so. A chosen folder Peel can't-search, such as one on a disk that isn't connected, is named at the top of the page with the reason, never taken for-one with nothing built in it. Peel never searches a hidden folder, a Library, or a folder a tool fills, such as-`node_modules`, where apps and tools keep what they install, so choosing one, or a folder inside one, is refused.+**Build Artifacts:** what builds left in the folders you choose, like `node_modules`, `DerivedData`, `target`, `.nuxt`,+`__pycache__`, Unity's `Library`, and any folder its tool tagged as a cache (`CACHEDIR.TAG`), each only when a file of+the tool that makes it proves it. Nothing is selected for you, and Select Recommended passes by a project changed in the+last 7 days, installed packages (a Python environment, `vendor`, Terraform's `.terraform`), a folder like `target` whose+name says nothing on its own, and a folder Git tracks files in, such as a `Pods` folder kept in the repository, which is+part of the project. Until you choose a folder, Peel offers `~/Developer`, `~/Projects`, `~/Code`, or `~/src` when you+have one, and adds it only when you say so. A chosen folder Peel can't search, such as one on a disk that isn't+connected, is named at the top of the page with the reason, never taken for one with nothing built in it. Peel never+searches a hidden folder, a Library, or a folder a tool fills, such as `node_modules`, where apps and tools keep what+they install, so choosing one, or a folder inside one, is refused.**Space:** what's taking up room, and which app it belongs to. What an app manages itself, such as Xcode'ssimulators, Docker's disk, Rust's toolchains, or Android's NDK versions, Space measures and leaves to that tool,diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex 9f59c046..0ed9c63e 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -87290,6 +87290,112 @@}}},+ "Not selected: Git tracks files in this folder, so it is part of the project. Moving it would show them as deleted in Git." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nevybráno: tato složka obsahuje soubory sledované Gitem, takže je součástí projektu. Jejím přesunutím by se tyto soubory v Gitu zobrazily jako smazané."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nicht ausgewählt: Git versioniert Dateien in diesem Ordner, daher gehört er zum Projekt. Wenn du ihn verschiebst, zeigt Git sie als gelöscht an."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Sin seleccionar: esta carpeta contiene archivos que Git rastrea, así que forma parte del proyecto. Si la trasladas a la papelera, Git los mostrará como borrados."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Non sélectionné : ce dossier contient des fichiers suivis par Git et fait donc partie du projet. Le déplacer les ferait apparaître comme supprimés dans Git."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Non selezionato: questa cartella contiene file tracciati da Git, quindi fa parte del progetto. Se la sposti, Git li mostrerà come eliminati."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未選択: このフォルダにはGitで追跡されているファイルがあるため、プロジェクトの一部です。移動すると、Gitではそれらのファイルが削除されたものとして表示されます。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "선택되지 않음: Git이 이 폴더 안의 파일을 추적하므로 이 폴더는 프로젝트의 일부입니다. 이 폴더를 이동하면 Git에서 해당 파일이 삭제된 것으로 표시됩니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Niet geselecteerd: Git volgt bestanden in deze map, dus de map hoort bij het project. Als je de map verplaatst, toont Git die bestanden als verwijderd."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nie zaznaczono: Git śledzi pliki w tym folderze, więc to część projektu. Jeśli go przeniesiesz, Git pokaże te pliki jako usunięte."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Não selecionado: o Git rastreia arquivos nesta pasta, então ela faz parte do projeto. Movê-la faria com que esses arquivos aparecessem como apagados no Git."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Neselectat: acest dosar conține fișiere urmărite de Git, așa că face parte din proiect. Mutarea lui le‑ar face să apară ca șterse în Git."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не выбрано: Git отслеживает файлы в этой папке, поэтому она является частью проекта. Если ее переместить, Git покажет эти файлы как удаленные."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Inte markerad: Git spårar filer i den här mappen, så den är en del av projektet. Om den flyttades skulle Git visa filerna som borttagna."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Seçilmedi: bu klasörde Git’in izlediği dosyalar var, bu yüzden klasör projenin bir parçası. Taşınırsa, Git bu dosyaları silinmiş olarak gösterir."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не вибрано: Git відстежує файли в цій папці, тож вона є частиною проєкту. Якщо її перемістити, Git показуватиме ці файли як видалені."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未选择:此文件夹中有受Git跟踪的文件,因此它是项目的一部分。移走它会使这些文件在Git中显示为已删除。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未選取:此檔案夾中有受Git追蹤的檔案,因此它是計畫案的一部分。移動它會讓這些檔案在Git中顯示為已刪除。"+ }+ }+ }+ },"Not selected: Mail keeps a copy here of each attachment you open, and one you edited may exist nowhere else." : {"localizations" : {"cs" : {@@ -89516,6 +89622,112 @@}}},+ "Not selected: this folder is in a Git repository whose list of tracked files Peel couldn’t read, so it may be part of the project." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nevybráno: tato složka je v repozitáři Gitu, jehož seznam sledovaných souborů Peel nemohl přečíst, takže může být součástí projektu."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nicht ausgewählt: Dieser Ordner liegt in einem Git-Repository, dessen Liste der versionierten Dateien Peel nicht lesen konnte, daher gehört er möglicherweise zum Projekt."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Sin seleccionar: esta carpeta está en un repositorio de Git del que Peel no ha podido leer la lista de archivos rastreados, así que puede que forme parte del proyecto."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Non sélectionné : ce dossier se trouve dans un dépôt Git dont Peel n’a pas pu lire la liste des fichiers suivis, et peut donc faire partie du projet."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Non selezionato: questa cartella si trova in un repository Git di cui Peel non è riuscito a leggere l’elenco dei file tracciati, quindi potrebbe far parte del progetto."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未選択: このフォルダはGitリポジトリ内にあり、そのリポジトリで追跡されているファイルのリストをPeelが読み取れなかったため、プロジェクトの一部である可能性があります。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "선택되지 않음: 이 폴더는 Git 저장소 안에 있으며, 이 저장소에서 추적되는 파일 목록을 Peel이 읽을 수 없었으므로 프로젝트의 일부일 수 있습니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Niet geselecteerd: deze map staat in een Git-repository waarvan Peel de lijst met gevolgde bestanden niet kon lezen, dus de map hoort misschien bij het project."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nie zaznaczono: ten folder jest w repozytorium Git, w którym Peel nie mógł odczytać listy śledzonych plików, więc może to być część projektu."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Não selecionado: esta pasta está em um repositório Git cuja lista de arquivos rastreados o Peel não conseguiu ler, então ela pode fazer parte do projeto."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Neselectat: acest dosar se află într‑un depozit Git pentru care Peel nu a putut citi lista fișierelor urmărite, așa că ar putea face parte din proiect."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не выбрано: эта папка находится в репозитории Git, список отслеживаемых файлов которого Peel не удалось прочитать, поэтому она может быть частью проекта."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Inte markerad: den här mappen ligger i ett Git-kodförråd där Peel inte kunde läsa listan över spårade filer, så mappen kan vara en del av projektet."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Seçilmedi: bu klasör, Peel’in izlenen dosyaların listesini okuyamadığı bir Git deposunda, bu yüzden projenin bir parçası olabilir."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не вибрано: ця папка міститься в репозиторії Git, список відстежуваних файлів якого Peel не вдалося прочитати, тож вона може бути частиною проєкту."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未选择:此文件夹位于Git代码仓库中,而Peel未能读取该仓库的已跟踪文件列表,因此它可能是项目的一部分。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未選取:此檔案夾位於Git儲存庫中,而Peel無法讀取該儲存庫的已追蹤檔案列表,因此它可能是計畫案的一部分。"+ }+ }+ }+ },"Not selected: this folder took too long to measure, so Peel doesn’t know how big it is or what is inside." : {"localizations" : {"cs" : {diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swiftindex 6f0e5ccf..45427255 100644--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift@@ -311,6 +311,8 @@ extension HoldBack {var summary: String {switch self {case .holdsRepository: "holds a repository"+ case .trackedByGit: "Git tracks files in it"+ case .gitTrackingNotKnown: "in a Git repository whose tracked files couldn't be read"case .sharedWithEveryone: "belongs to everyone on this Mac"case .namedLikeTheApp: "claimed on the app's name alone"case .holdsAnExclusion: "holds something you excluded"diff --git a/Packages/PeelCore/Sources/PeelCore/Developer/GitIndex.swift b/Packages/PeelCore/Sources/PeelCore/Developer/GitIndex.swiftnew file mode 100644index 00000000..7b2f7d50--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Developer/GitIndex.swift@@ -0,0 +1,237 @@+import Darwin+import Foundation+import PeelPrivileged++/// What a Git repository tracks, read from its index as `gitformat-index(5)` describes it. Peel never runs Git inside+/// a project: a repository's own settings can name a program for Git to run.+struct GitIndex: Sendable {+ struct Repository: Sendable, Hashable {+ let top: URL+ let gitDirectory: URL+ }++ private struct Unreadable: Error {}++ /// Every folder that holds a tracked path, a tracked submodule's own folder among them: its names below the+ /// working tree's top, in lowercase.+ private var folders: Set<[String]> = []+ /// The folders a sparse checkout leaves out of the working tree, everything in each of them tracked.+ private var sparseFolders: [[String]] = []++ /// An index larger than this is not read, and what Git tracks there is not known.+ static let maximumSize = 256 * 1_024 * 1_024++ /// The repository whose working tree holds `folder`, found as Git finds it: in `folder` and each folder above,+ /// never past the disk `folder` is on. A `.git` folder counts when it has a `HEAD`, and a `.git` file always+ /// does, since Git stops there even when the folder it names can't be read.+ static func repository(containing folder: URL) -> Repository? {+ let names = PathComponents.of(PathPattern.canonical(folder).path(percentEncoded: false))+ var device: dev_t?+ for count in stride(from: names.count, through: 0, by: -1) {+ let path = "/" + names.prefix(count).joined(separator: "/")+ var info = stat()+ guard stat(path, &info) == 0, device.map({ $0 == info.st_dev }) ?? true else { return nil }+ device = info.st_dev+ let top = URL(filePath: path, directoryHint: .isDirectory)+ if let gitDirectory = gitDirectory(at: top.appending(path: ".git")) {+ return Repository(top: top, gitDirectory: gitDirectory)+ }+ }+ return nil+ }++ private static func gitDirectory(at dotGit: URL) -> URL? {+ var info = stat()+ guard stat(dotGit.path(percentEncoded: false), &info) == 0 else { return nil }+ switch info.st_mode & S_IFMT {+ case S_IFDIR:+ return isGitDirectory(dotGit) ? dotGit : nil+ case S_IFREG:+ guard let data = BoundedRead.data(at: dotGit, maximum: 4_096),+ let text = String(data: data, encoding: .utf8), text.hasPrefix("gitdir: ")+ else { return dotGit }+ let named = String(text.dropFirst("gitdir: ".count)).trimmingCharacters(in: CharacterSet(charactersIn: "\r\n"))+ return named.hasPrefix("/")+ ? URL(filePath: named, directoryHint: .isDirectory)+ : dotGit.deletingLastPathComponent().appending(path: named, directoryHint: .isDirectory)+ default:+ return nil+ }+ }++ private static func isGitDirectory(_ url: URL) -> Bool {+ !url.appending(path: "HEAD").isMissing+ }++ /// What Git tracks in `repository`, or nil when that is not known: a file the index needs can't be read whole,+ /// or it uses a form this reader doesn't know, which `gitformat-index(5)` asks tools to leave alone.+ static func read(_ repository: Repository) -> GitIndex? {+ let git = repository.gitDirectory+ guard isGitDirectory(git) else { return nil }+ let file = git.appending(path: "index")+ if file.isMissing { return GitIndex() }+ guard let length = objectNameLength(in: git), let data = BoundedRead.data(at: file, maximum: maximumSize)+ else { return nil }+ var index = GitIndex()+ do {+ if let shared = try index.add(data, objectNameLength: length) {+ let sharedFile = git.appending(path: "sharedindex.\(shared)")+ guard let sharedData = BoundedRead.data(at: sharedFile, maximum: maximumSize),+ try index.add(sharedData, objectNameLength: length) == nil+ else { return nil }+ }+ } catch {+ return nil+ }+ return index+ }++ /// 32 bytes in a SHA-256 repository (`extensions.objectFormat`), 20 in one that uses SHA-1.+ private static func objectNameLength(in gitDirectory: URL) -> Int? {+ let config = commonDirectory(of: gitDirectory).appending(path: "config")+ if config.isMissing { return 20 }+ guard let data = BoundedRead.data(at: config), let text = String(data: data, encoding: .utf8)+ else { return nil }+ switch ToolSettings.gitValue(of: "objectformat", inSection: "extensions", in: text)?.lowercased() {+ case nil, "sha1": return 20+ case "sha256": return 32+ default: return nil+ }+ }++ /// The repository's own Git folder, which a worktree's names in `commondir`.+ private static func commonDirectory(of gitDirectory: URL) -> URL {+ guard let data = BoundedRead.data(at: gitDirectory.appending(path: "commondir"), maximum: 4_096),+ let named = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),+ !named.isEmpty+ else { return gitDirectory }+ return named.hasPrefix("/")+ ? URL(filePath: named, directoryHint: .isDirectory)+ : gitDirectory.appending(path: named, directoryHint: .isDirectory)+ }++ /// True when Git tracks something at or inside `folder`, or `folder` sits in a folder a sparse checkout leaves+ /// out. Names are compared without case, so a guess holds back more, never less.+ func tracksSomething(atOrInside folder: URL, of repository: Repository) -> Bool {+ let top = PathComponents.of(repository.top.path(percentEncoded: false))+ let names = PathComponents.of(PathPattern.canonical(folder).path(percentEncoded: false))+ guard names.starts(with: top) else { return false }+ let relative = names.dropFirst(top.count).map { $0.lowercased() }+ return folders.contains(relative) || sparseFolders.contains { relative.starts(with: $0) }+ }++ /// Adds the entries of one index file, and returns the name of the shared index a split index lays them over.+ private mutating func add(_ data: Data, objectNameLength: Int) throws -> String? {+ try data.withUnsafeBytes { bytes in try add(bytes, objectNameLength: objectNameLength) }+ }++ private mutating func add(_ bytes: UnsafeRawBufferPointer, objectNameLength: Int) throws -> String? {+ // The index ends with a checksum as long as an object name.+ let end = bytes.count - objectNameLength+ guard end >= 12, bytes.bigEndian32(at: 0) == 0x4449_5243 else { throw Unreadable() }+ let version = bytes.bigEndian32(at: 4)+ guard (2...4).contains(version) else { throw Unreadable() }++ var offset = 12+ var previous: [UInt8] = []+ var previousFolder: ArraySlice<UInt8> = []+ for _ in 0..<bytes.bigEndian32(at: 8) {+ let start = offset+ offset += 40 + objectNameLength + 2+ guard offset <= end else { throw Unreadable() }+ let mode = bytes.bigEndian32(at: start + 24)+ let flags = bytes.bigEndian16(at: offset - 2)+ if flags & 0x4000 != 0 {+ guard version >= 3 else { throw Unreadable() }+ offset += 2+ }+ let path: [UInt8]+ if version == 4 {+ // The name drops this many bytes from the end of the one before it, and adds what follows.+ let (dropped, used) = try Self.variableLengthNumber(in: bytes, at: offset, end: end)+ offset += used+ let nul = try Self.nul(in: bytes, from: offset, end: end)+ guard dropped <= previous.count else { throw Unreadable() }+ path = Array(previous.dropLast(dropped)) + bytes[offset..<nul]+ offset = nul + 1+ } else {+ let nul = try Self.nul(in: bytes, from: offset, end: end)+ path = Array(bytes[offset..<nul])+ // Padded with 1 to 8 NUL bytes to a multiple of eight.+ offset = start + (((nul - start) + 8) & ~7)+ guard offset <= end else { throw Unreadable() }+ }+ let length = Int(flags & 0x0FFF)+ guard length == 0x0FFF ? path.count >= 0x0FFF : path.count == length else { throw Unreadable() }+ previous = path++ let folder = path[..<(path.lastIndex(of: UInt8(ascii: "/")) ?? 0)]+ let kind = mode & 0o170000+ if kind == 0o040000 || kind == 0o160000 || folder != previousFolder {+ add(path: path, isTrackedWhole: kind == 0o040000 || kind == 0o160000, isSparse: kind == 0o040000)+ previousFolder = folder+ }+ }++ var shared: String?+ while offset < end {+ guard end - offset >= 8 else { throw Unreadable() }+ let signature = Array(bytes[offset..<offset + 4])+ let size = Int(bytes.bigEndian32(at: offset + 4))+ let body = offset + 8+ guard size <= end - body else { throw Unreadable() }+ if signature == Array("link".utf8) {+ guard size >= objectNameLength else { throw Unreadable() }+ let name = bytes[body..<body + objectNameLength]+ if name.contains(where: { $0 != 0 }) { shared = name.hexadecimal }+ } else if !(UInt8(ascii: "A")...UInt8(ascii: "Z")).contains(signature[0]), signature != Array("sdir".utf8) {+ // An extension whose name starts in lowercase changes what the entries mean.+ throw Unreadable()+ }+ offset = body + size+ }+ return shared+ }++ private mutating func add(path: [UInt8], isTrackedWhole: Bool, isSparse: Bool) {+ guard !path.isEmpty else { return }+ let names = path.split(separator: UInt8(ascii: "/")).map { String(decoding: $0, as: UTF8.self).lowercased() }+ for count in stride(from: isTrackedWhole ? names.count : names.count - 1, to: 0, by: -1) {+ guard folders.insert(Array(names.prefix(count))).inserted else { break }+ }+ if isSparse { sparseFolders.append(names) }+ }++ /// The number Git's offset encoding writes (`gitformat-pack(5)`), and how many bytes it took.+ private static func variableLengthNumber(+ in bytes: UnsafeRawBufferPointer, at start: Int, end: Int+ ) throws -> (value: Int, length: Int) {+ var offset = start+ guard offset < end else { throw Unreadable() }+ var byte = bytes[offset]+ offset += 1+ var value = Int(byte & 0x7F)+ while byte & 0x80 != 0 {+ guard offset < end, value < Int.max >> 8 else { throw Unreadable() }+ byte = bytes[offset]+ offset += 1+ value = ((value + 1) << 7) | Int(byte & 0x7F)+ }+ return (value, offset - start)+ }++ private static func nul(in bytes: UnsafeRawBufferPointer, from start: Int, end: Int) throws -> Int {+ guard let nul = bytes[start..<end].firstIndex(of: 0) else { throw Unreadable() }+ return nul+ }+}++private extension UnsafeRawBufferPointer {+ func bigEndian32(at offset: Int) -> UInt32 {+ UInt32(bigEndian: loadUnaligned(fromByteOffset: offset, as: UInt32.self))+ }++ func bigEndian16(at offset: Int) -> UInt16 {+ UInt16(bigEndian: loadUnaligned(fromByteOffset: offset, as: UInt16.self))+ }+}diff --git a/Packages/PeelCore/Sources/PeelCore/Developer/ProjectArtifacts.swift b/Packages/PeelCore/Sources/PeelCore/Developer/ProjectArtifacts.swiftindex 0fffd8a2..2a1d6346 100644--- a/Packages/PeelCore/Sources/PeelCore/Developer/ProjectArtifacts.swift+++ b/Packages/PeelCore/Sources/PeelCore/Developer/ProjectArtifacts.swift@@ -476,7 +476,7 @@ public enum ProjectArtifacts {}}return Scan(- artifacts: found.sorted { SizeTotal([$0.size]) > SizeTotal([$1.size]) },+ artifacts: await holdingBackWhatGitTracks(found).sorted { SizeTotal([$0.size]) > SizeTotal([$1.size]) },wasCutShort: wasCutShort,unreadableLocations: unreadable.sorted {PathPattern.comparablePath(of: $0) < PathPattern.comparablePath(of: $1)@@ -487,6 +487,47 @@ public enum ProjectArtifacts {}}+ /// Holds back each artifact Git tracks files in, which is part of the project rather than something a build makes+ /// again, and each in a repository whose index can't be read. What the walk saw inside comes first.+ static func holdingBackWhatGitTracks(_ artifacts: [ProjectArtifact]) async -> [ProjectArtifact] {+ var result = artifacts+ var indexes: [GitIndex.Repository: GitIndex?] = [:]+ let projects = Dictionary(grouping: result.indices.filter { result[$0].heldBack == nil }) { result[$0].project }+ for (project, positions) in projects {+ guard !Task.isCancelled else { break }+ func hold(_ reason: HoldBack, _ held: [Int]) {+ for position in held { result[position].heldBack = reason }+ }+ let found = await SlowRead.answer(within: FileSize.budget) { _ in GitIndex.repository(containing: project) }+ guard let found else {+ hold(.gitTrackingNotKnown, positions)+ continue+ }+ guard let repository = found else { continue }+ let index: GitIndex?+ if let read = indexes[repository] {+ index = read+ } else {+ index = await SlowRead.answer(within: FileSize.budget) { _ in GitIndex.read(repository) } ?? nil+ indexes.updateValue(index, forKey: repository)+ }+ guard let index else {+ hold(.gitTrackingNotKnown, positions)+ continue+ }+ let folders = positions.map { result[$0].url }+ let tracked = await SlowRead.answer(within: FileSize.budget) { _ in+ folders.map { index.tracksSomething(atOrInside: $0, of: repository) }+ }+ guard let tracked else {+ hold(.gitTrackingNotKnown, positions)+ continue+ }+ hold(.trackedByGit, zip(positions, tracked).filter(\.1).map(\.0))+ }+ return result+ }+public enum Refusal: Sendable, Hashable {case tooBroadcase inTheClouddiff --git a/Packages/PeelCore/Sources/PeelCore/Developer/ToolSettings.swift b/Packages/PeelCore/Sources/PeelCore/Developer/ToolSettings.swiftindex 416ad9b3..6222f197 100644--- a/Packages/PeelCore/Sources/PeelCore/Developer/ToolSettings.swift+++ b/Packages/PeelCore/Sources/PeelCore/Developer/ToolSettings.swift@@ -111,28 +111,31 @@ struct ToolSettings: Sendable {/// Where the Git clone in `folder` comes from, as `gitAddress` writes it: the `url` of its `origin` remote.static func cloneAddress(of folder: URL) -> String? {- text(at: folder.appending(path: ".git/config")).flatMap { gitValue(of: "url", inRemote: "origin", in: $0) }+ text(at: folder.appending(path: ".git/config"))+ .flatMap { gitValue(of: "url", inSection: "remote", named: "origin", in: $0) }.map(gitAddress)}// MARK: - The formats- /// The value of `key` in a remote's section of a Git configuration file, as `git-config(1)` describes it: the- /// section's and the key's names without case, the remote's name with it, a value quoted in parts or ending at a- /// comment. The last one counts.- static func gitValue(of key: String, inRemote remote: String, in text: String) -> String? {- var isInTheRemote = false+ /// The value of `key` in a section of a Git configuration file, as `git-config(1)` describes it: the section's+ /// and the key's names without case, a subsection's name (a remote's) with it, a value quoted in parts or ending+ /// at a comment. The last one counts.+ static func gitValue(+ of key: String, inSection section: String, named name: String? = nil, in text: String+ ) -> String? {+ var isInTheSection = falsevar found: String?for line in text.split(whereSeparator: { $0 == "\n" || $0 == "\r" }) {let content = line.trimmingCharacters(in: .whitespaces)if content.isEmpty || content.hasPrefix("#") || content.hasPrefix(";") { continue }if content.hasPrefix("["), content.hasSuffix("]") {let header = content.dropFirst().dropLast().split(separator: " ", maxSplits: 1)- isInTheRemote = header.count == 2 && header[0].lowercased() == "remote"- && header[1].trimmingCharacters(in: .whitespaces) == "\"\(remote)\""+ let subsection = header.count == 2 ? header[1].trimmingCharacters(in: .whitespaces) : nil+ isInTheSection = header.first?.lowercased() == section && subsection == name.map { "\"\($0)\"" }continue}- guard isInTheRemote, let equals = content.firstIndex(of: "="),+ guard isInTheSection, let equals = content.firstIndex(of: "="),content[..<equals].trimmingCharacters(in: .whitespaces).lowercased() == keyelse { continue }found = gitUnquoted(content[content.index(after: equals)...])diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swiftindex 121e7cee..d9889474 100644--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift@@ -38,6 +38,10 @@ public enum MatchConfidence: Int, Sendable, Hashable, Comparable {public enum HoldBack: String, Sendable, Hashable {/// A repository inside, so the folder may carry work that was committed and never pushed anywhere.case holdsRepository+ /// Git tracks files inside, so the folder is part of the project rather than something a build makes again.+ case trackedByGit+ /// Inside a Git repository whose index could not be read, so whether Git tracks files inside is not known.+ case gitTrackingNotKnown/// `/Users/Shared`, which belongs to every account on the Mac rather than to one app.case sharedWithEveryone/// Claimed on nothing but the app's name (or an identifier that is only a word), in the home folder or at thediff --git a/Packages/PeelCore/Tests/PeelCoreTests/GitFixture.swift b/Packages/PeelCore/Tests/PeelCoreTests/GitFixture.swiftnew file mode 100644index 00000000..ee7d4349--- /dev/null+++ b/Packages/PeelCore/Tests/PeelCoreTests/GitFixture.swift@@ -0,0 +1,38 @@+import Foundation+@testable import PeelCore+import PeelPrivileged+import Testing++/// The developer tools' Git, run with a home of its own and none of this Mac's settings, so a repository a test+/// makes is the same on every Mac and no commit asks for a signature.+struct GitFixture {+ let executable: URL+ let home: URL++ init(home: URL) async throws {+ try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)+ executable = try #require(await GitConfig.find(home: home)).executable+ self.home = home+ }++ func run(_ arguments: String..., in folder: URL) async throws {+ let answer = await Subprocess.run(+ executable.path(percentEncoded: false),+ [+ "-c", "user.name=Test", "-c", "[email protected]", "-c", "commit.gpgsign=false",+ "-c", "init.defaultBranch=main", "-C", folder.path(percentEncoded: false),+ ] + arguments,+ environment: [+ "HOME": home.path(percentEncoded: false), "PATH": "/usr/bin:/bin", "GIT_CONFIG_NOSYSTEM": "1",+ ],+ timeout: 60,+ errorsIntoOutput: true+ )+ guard case .success(let output) = answer, output.status == 0 else {+ let said = if case .success(let output) = answer { output.text } else { "" }+ throw CocoaError(.fileWriteUnknown, userInfo: [+ NSLocalizedDescriptionKey: "git \(arguments.joined(separator: " ")): \(said)",+ ])+ }+ }+}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/GitIndexTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/GitIndexTests.swiftnew file mode 100644index 00000000..e83e5f8f--- /dev/null+++ b/Packages/PeelCore/Tests/PeelCoreTests/GitIndexTests.swift@@ -0,0 +1,139 @@+import Foundation+@testable import PeelCore+import Testing++struct GitIndexTests {+ enum Form: String, CaseIterable, Sendable {+ case version2, version3, version4, sha256, splitIndex, separateGitDirectory+ }++ @Test(arguments: Form.allCases)+ func readsWhatGitTracksInEveryIndexItWrites(_ form: Form) async throws {+ let directory = try TemporaryDirectory()+ let project = try makeProject(in: directory)+ let git = try await GitFixture(home: directory.url.appending(path: "home"))+ switch form {+ case .sha256:+ try await git.run("init", "-q", "--object-format=sha256", in: project)+ case .separateGitDirectory:+ let store = directory.url.appending(path: "store").path(percentEncoded: false)+ try await git.run("init", "-q", "--separate-git-dir", store, in: project)+ default:+ try await git.run("init", "-q", in: project)+ }+ if form == .version3 {+ try await git.run("add", "Podfile", "src", in: project)+ try await git.run("add", "-N", "Pods", in: project)+ } else {+ try await git.run("add", "Podfile", "Pods", "src", in: project)+ }+ if form == .version4 { try await git.run("update-index", "--index-version", "4", in: project) }+ if form == .splitIndex { try await git.run("update-index", "--split-index", in: project) }++ let repository = try #require(GitIndex.repository(containing: project))+ let written = try Data(contentsOf: repository.gitDirectory.appending(path: "index"))+ #expect(written.dropFirst(7).first == (form == .version3 ? 3 : form == .version4 ? 4 : 2))+ let store = repository.gitDirectory.path(percentEncoded: false)+ let shared = try FileManager.default.contentsOfDirectory(atPath: store)+ #expect(shared.contains { $0.hasPrefix("sharedindex.") } == (form == .splitIndex))++ let index = try #require(GitIndex.read(repository))+ #expect(index.tracksSomething(atOrInside: project.appending(path: "Pods"), of: repository))+ #expect(index.tracksSomething(atOrInside: project.appending(path: "Pods/Foo"), of: repository))+ #expect(index.tracksSomething(atOrInside: project.appending(path: "src"), of: repository))+ #expect(!index.tracksSomething(atOrInside: project.appending(path: "Other"), of: repository))+ }++ @Test func readsTheIndexOfAWorktree() async throws {+ let directory = try TemporaryDirectory()+ let project = try makeProject(in: directory)+ let git = try await GitFixture(home: directory.url.appending(path: "home"))+ try await git.run("init", "-q", in: project)+ try await git.run("add", "Podfile", "Pods", "src", in: project)+ try await git.run("commit", "-q", "-m", "One", in: project)+ let worktree = directory.url.appending(path: "Worktree")+ try await git.run("worktree", "add", "-q", worktree.path(percentEncoded: false), in: project)++ let repository = try #require(GitIndex.repository(containing: worktree.appending(path: "src")))+ #expect(repository.gitDirectory.deletingLastPathComponent().lastPathComponent == "worktrees")+ let index = try #require(GitIndex.read(repository))+ #expect(index.tracksSomething(atOrInside: worktree.appending(path: "Pods"), of: repository))+ }++ @Test func aSparseIndexTracksWhatItLeavesOut() async throws {+ let directory = try TemporaryDirectory()+ let project = try makeProject(in: directory)+ let git = try await GitFixture(home: directory.url.appending(path: "home"))+ try await git.run("init", "-q", in: project)+ try await git.run("add", "Podfile", "Pods", "src", in: project)+ try await git.run("commit", "-q", "-m", "One", in: project)+ try await git.run("sparse-checkout", "set", "--cone", "--sparse-index", "src", in: project)+ #expect(!FileManager.default.fileExists(atPath: project.appending(path: "Pods").path(percentEncoded: false)))+ _ = try directory.file("App/Pods/Foo/Foo.m")++ let repository = try #require(GitIndex.repository(containing: project))+ let index = try #require(GitIndex.read(repository))+ #expect(index.tracksSomething(atOrInside: project.appending(path: "Pods"), of: repository))+ #expect(index.tracksSomething(atOrInside: project.appending(path: "Pods/Foo"), of: repository))+ #expect(!index.tracksSomething(atOrInside: project.appending(path: "Other"), of: repository))+ }++ @Test func aRepositoryWithNothingAddedTracksNothing() async throws {+ let directory = try TemporaryDirectory()+ let project = try makeProject(in: directory)+ let git = try await GitFixture(home: directory.url.appending(path: "home"))+ try await git.run("init", "-q", in: project)++ let repository = try #require(GitIndex.repository(containing: project))+ let index = try #require(GitIndex.read(repository))+ #expect(!index.tracksSomething(atOrInside: project.appending(path: "Pods"), of: repository))+ }++ @Test func aFolderOnlyNamedLikeATrackedOneIsNotTracked() async throws {+ let directory = try TemporaryDirectory()+ let project = try makeProject(in: directory)+ _ = try directory.file("App/PodsArchive/Foo.m")+ let git = try await GitFixture(home: directory.url.appending(path: "home"))+ try await git.run("init", "-q", in: project)+ try await git.run("add", "PodsArchive", in: project)++ let repository = try #require(GitIndex.repository(containing: project))+ let index = try #require(GitIndex.read(repository))+ #expect(index.tracksSomething(atOrInside: project.appending(path: "PodsArchive"), of: repository))+ #expect(!index.tracksSomething(atOrInside: project.appending(path: "Pods"), of: repository))+ }++ @Test(.permissionsHold) func anIndexItCannotReadIsNotKnown() async throws {+ let directory = try TemporaryDirectory()+ let project = try makeProject(in: directory)+ let git = try await GitFixture(home: directory.url.appending(path: "home"))+ try await git.run("init", "-q", in: project)+ try await git.run("add", "Pods", in: project)+ let index = project.appending(path: ".git/index")+ try directory.setPermissions(0, of: index)+ defer { try? directory.setPermissions(0o644, of: index) }++ let repository = try #require(GitIndex.repository(containing: project))+ #expect(GitIndex.read(repository) == nil)+ }++ @Test func neverLooksPastTheDiskItStartedOn() async throws {+ let directory = try TemporaryDirectory()+ let git = try await GitFixture(home: directory.url.appending(path: "home"))+ try await git.run("init", "-q", in: directory.url)+ let disk = try ScratchVolume(fileSystem: "APFS", mountedAt: directory.url.appending(path: "Disk"))+ let project = disk.url.appending(path: "App", directoryHint: .isDirectory)+ try FileManager.default.createDirectory(at: project.appending(path: "Pods"), withIntermediateDirectories: true)++ #expect(GitIndex.repository(containing: directory.url) != nil)+ #expect(GitIndex.repository(containing: project) == nil)+ }++ private func makeProject(in directory: borrowing TemporaryDirectory) throws -> URL {+ _ = try directory.file("App/Podfile")+ _ = try directory.file("App/Pods/Foo/Foo.m")+ _ = try directory.file("App/src/App.swift")+ _ = try directory.file("App/Other/notes.txt")+ return directory.url.appending(path: "App", directoryHint: .isDirectory)+ }+}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ProjectArtifactsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ProjectArtifactsTests.swiftindex a085b164..934aa5a2 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ProjectArtifactsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ProjectArtifactsTests.swift@@ -502,6 +502,49 @@ struct ProjectArtifactsTests {#expect(found.filter(\.isRecommended).map(\.project.lastPathComponent) == ["tool"])}+ @Test func aFolderGitTracksIsListedAndNeverSelected() async throws {+ let directory = try TemporaryDirectory()+ let git = try await GitFixture(home: directory.url.appending(path: "home"))+ for name in ["Tracked", "Ignored"] {+ try directory.file("Code/\(name)/Podfile")+ try directory.file("Code/\(name)/Pods/Foo/Foo.m")+ try directory.file("Code/\(name)/src/App.swift")+ }+ try directory.file("Code/Ignored/.gitignore", contents: Data("Pods/\n".utf8))+ for name in ["Tracked", "Ignored"] {+ let project = directory.url.appending(path: "Code/\(name)", directoryHint: .isDirectory)+ try await git.run("init", "-q", in: project)+ try await git.run("add", "-A", in: project)+ }+ try age(directory.url, days: 60)++ let found = await ProjectArtifacts.scan(roots: [directory.url.appending(path: "Code")]).artifacts++ let reasons = found.map { "\($0.project.lastPathComponent): \($0.heldBack.map(\.rawValue) ?? "none")" }.sorted()+ #expect(reasons == ["Ignored: none", "Tracked: trackedByGit"])+ #expect(found.filter(\.isRecommended).map(\.project.lastPathComponent) == ["Ignored"])+ }++ @Test(.permissionsHold) func whatGitTracksIsNotKnownWhileItsIndexCannotBeRead() async throws {+ let directory = try TemporaryDirectory()+ let git = try await GitFixture(home: directory.url.appending(path: "home"))+ try directory.file("Code/App/Podfile")+ try directory.file("Code/App/Pods/Foo/Foo.m")+ let project = directory.url.appending(path: "Code/App", directoryHint: .isDirectory)+ try await git.run("init", "-q", in: project)+ try await git.run("add", "Podfile", in: project)+ try age(directory.url, days: 60)+ let index = project.appending(path: ".git/index")+ try directory.setPermissions(0, of: index)+ defer { try? directory.setPermissions(0o644, of: index) }++ let found = await ProjectArtifacts.scan(roots: [directory.url.appending(path: "Code")]).artifacts++ let pods = try #require(found.first)+ #expect(pods.heldBack == .gitTrackingNotKnown)+ #expect(!pods.isRecommended)+ }+/// A large `node_modules` is the folder most likely to run out of time. Its size is then unknown, not zero,/// so it is listed first and never selected for the user.@Test func anArtifactThatDidNotAnswerInTimeIsNotReadAsEmpty() async throws {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ToolSettingsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ToolSettingsTests.swiftindex cf7f106d..aea4312c 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ToolSettingsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ToolSettingsTests.swift@@ -78,8 +78,12 @@ struct ToolSettingsTests {\turl = https://example.org/another.git"""- #expect(ToolSettings.gitValue(of: "url", inRemote: "origin", in: config) == "https://github.com/CocoaPods/Specs.git")- #expect(ToolSettings.gitValue(of: "url", inRemote: "upstream", in: config) == nil)+ #expect(+ ToolSettings.gitValue(of: "url", inSection: "remote", named: "origin", in: config)+ == "https://github.com/CocoaPods/Specs.git"+ )+ #expect(ToolSettings.gitValue(of: "url", inSection: "remote", named: "upstream", in: config) == nil)+ #expect(ToolSettings.gitValue(of: "url", inSection: "core", in: config) == "https://example.org/not-a-remote.git")for address in ["https://github.com/CocoaPods/Specs.git", "https://github.com/cocoapods/specs/", "[email protected]:CocoaPods/Specs.git","ssh://[email protected]/CocoaPods/Specs",diff --git a/Peel/Views/Presentation.swift b/Peel/Views/Presentation.swiftindex c49ce6e5..87a28b76 100644--- a/Peel/Views/Presentation.swift+++ b/Peel/Views/Presentation.swift@@ -249,6 +249,10 @@ extension HoldBack {switch self {case .holdsRepository:"Not selected: there is a repository inside, so this folder may hold work that was committed and never pushed anywhere."+ case .trackedByGit:+ "Not selected: Git tracks files in this folder, so it is part of the project. Moving it would show them as deleted in Git."+ case .gitTrackingNotKnown:+ "Not selected: this folder is in a Git repository whose list of tracked files Peel couldn’t read, so it may be part of the project."case .sharedWithEveryone:"Not selected: /Users/Shared belongs to every account on this Mac rather than to one app."case .namedLikeTheApp:diff --git a/SAFETY.md b/SAFETY.mdindex 0cc919a7..61f64ad5 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -322,14 +322,17 @@ offered: its checkouts, which people commit in, carry no such tag and are neverBuild Artifacts recommends what a build or a package manager makes again from the project's own files, such as`DerivedData`, `.build`, and `.next`, once Peel can tell that nothing in the project has changed for a week. Thatincludes `node_modules` and `Pods`, which `npm install` and `pod install` put back from the project's `package.json` and-`Podfile`. A Python environment (`.venv`, `venv`) is listed and never selected, since packages are often installed into-one by hand, and so is Terraform's `.terraform`, which keeps the workspace you chose. A folder whose name says nothing-on its own, such as `target` or `build`, is listed and never selected either. Of a Godot project's `.godot`, only the-caches Godot makes again are offered, `imported` and `shader_cache`: the folder also holds the export passwords and-keys (`export_credentials.cfg`), which exist nowhere else. Build Artifacts never searches a hidden-folder, a Library, or a folder a tool fills, such as `node_modules`: apps and tools keep there what they install, as-an editor keeps each extension's `package.json` beside the `node_modules` it runs with. A folder chosen to search-that is one of those, or sits inside one, is refused with the reason.+`Podfile`, unless Git tracks files in them: CocoaPods suggests keeping `Pods` in the repository, and a folder Git tracks+is part of the project, so it is listed and never selected, and so is one in a repository whose list of tracked files+Peel can't read. Peel reads that list from Git's own index, as Git documents it, and never runs Git in a project. A+Python environment (`.venv`, `venv`) is listed and never selected, since packages are often installed into one by hand,+and so is Terraform's `.terraform`, which keeps the workspace you chose. A folder whose name says nothing on its own,+such as `target` or `build`, is listed and never selected either. Of a Godot project's `.godot`, only the caches Godot+makes again are offered, `imported` and `shader_cache`: the folder also holds the export passwords and keys+(`export_credentials.cfg`), which exist nowhere else. Build Artifacts never searches a hidden folder, a Library, or a+folder a tool fills, such as `node_modules`: apps and tools keep there what they install, as an editor keeps each+extension's `package.json` beside the `node_modules` it runs with. A folder chosen to search that is one of those, or+sits inside one, is refused with the reason.Developer, Build Artifacts, Space, and Installers and Backups select nothing for you: opening a page selects nothing,and Select Recommended selects what Peel recommends there.