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.

Tell two files that declare one background item apart

Țugui Dragoș8cb950b1baa1
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index 38b17430..4ce32b15 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -16306,6 +16306,112 @@
}
}
},
+ "Another file with this name is loaded" : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Načtený je jiný soubor s tímto názvem"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Eine andere Datei mit diesem Namen ist geladen"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Otro archivo con este nombre está cargado"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Un autre fichier portant ce nom est chargé"
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "È caricato un altro file con questo nome"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "同じ名前の別のファイルが読み込まれています"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "이름이 같은 다른 파일이 로드되어 있음"
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Er is een ander bestand met deze naam geladen"
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Wczytany jest inny plik o tej nazwie"
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Outro arquivo com este nome está carregado"
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Este încărcat un alt fișier cu acest nume"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Загружен другой файл с таким же именем"
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "En annan fil med det här namnet är inläst"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bu ada sahip başka bir dosya yüklü"
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Завантажено інший файл із цією назвою"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已载入同名的另一个文件"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "另一個同名的檔案已載入"
+ }
+ }
+ }
+ },
"Any kind" : {
"localizations" : {
"cs" : {
@@ -187335,6 +187441,112 @@
}
}
},
+ "Two files declare this job." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tuto úlohu uvádějí dva soubory."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Zwei Dateien definieren diesen Job."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dos archivos declaran esta tarea."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Deux fichiers déclarent cette tâche."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Questo elemento è dichiarato da due file."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "このジョブを宣言しているファイルが2つあります。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "이 작업을 지정하는 파일이 두 개 있습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Deze taak wordt in twee bestanden vermeld."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "To zadanie jest zadeklarowane w dwóch plikach."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dois arquivos declaram esta tarefa."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Două fișiere declară această sarcină."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Это задание объявлено в двух файлах."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Det här jobbet anges i två filer."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bu işi iki dosya tanımlıyor."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Це завдання оголошено у двох файлах."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "有两个文件声明了此任务。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "有兩個檔案宣告了此工作。"
+ }
+ }
+ }
+ },
"Two hyphens stay two hyphens instead of becoming a long dash." : {
"localizations" : {
"cs" : {
@@ -221043,6 +221255,112 @@
}
}
},
+ "launchd runs this job from another file that declares the same name, so this file isn’t loaded. Peel doesn’t start, stop, enable, or disable it from here." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd spouští tuto úlohu z jiného souboru, který uvádí stejný název, takže tento soubor není načtený. Peel ji odtud nespouští, nezastavuje, nezapíná ani nevypíná."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd führt diesen Job aus einer anderen Datei aus, die denselben Namen angibt, daher ist diese Datei nicht geladen. Peel startet, stoppt, aktiviert oder deaktiviert ihn nicht von hier aus."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd ejecuta esta tarea desde otro archivo que declara el mismo nombre, así que este archivo no está cargado. Desde aquí, Peel no la inicia, no la detiene, no la activa ni la desactiva."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd exécute cette tâche à partir d’un autre fichier qui déclare le même nom : ce fichier-ci n’est donc pas chargé. Peel ne démarre pas cet élément, ne l’arrête pas, ne l’active pas et ne le désactive pas d’ici."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd esegue questo elemento da un altro file che dichiara lo stesso nome, quindi questo file non è caricato. Da qui Peel non lo avvia, non lo interrompe, non lo abilita e non lo disabilita."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchdは、同じ名前を宣言している別のファイルからこのジョブを実行しているため、このファイルは読み込まれていません。Peelはここから開始、停止、有効化、無効化を行いません。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd가 같은 이름을 지정하는 다른 파일에서 이 작업을 실행하므로 이 파일은 로드되지 않습니다. Peel은 여기에서 이 항목을 시작, 중단, 활성화 또는 비활성화하지 않습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd voert deze taak uit vanuit een ander bestand dat dezelfde naam vermeldt, dus dit bestand is niet geladen. Peel start het van hieruit niet, stopt het niet en schakelt het niet in of uit."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd uruchamia to zadanie z innego pliku, który deklaruje tę samą nazwę, więc ten plik nie jest wczytany. Peel go stąd nie uruchamia, nie zatrzymuje, nie włącza ani nie wyłącza."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O launchd executa esta tarefa a partir de outro arquivo que declara o mesmo nome, então este arquivo não está carregado. O Peel não a inicia, não a interrompe, não a ativa nem a desativa daqui."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd rulează această sarcină dintr‑un alt fișier care declară același nume, așa că acest fișier nu este încărcat. Peel nu îl pornește, nu îl oprește, nu îl activează și nu îl dezactivează de aici."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd запускает это задание из другого файла, в котором объявлено то же имя, поэтому этот файл не загружен. Peel не запускает, не останавливает, не включает и не выключает его отсюда."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd kör det här jobbet från en annan fil som anger samma namn, så den här filen är inte inläst. Peel varken startar, stoppar, aktiverar eller avaktiverar det härifrån."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd bu işi aynı adı tanımlayan başka bir dosyadan çalıştırıyor, bu yüzden bu dosya yüklü değil. Peel onu buradan başlatmaz, durdurmaz, etkinleştirmez veya etkisizleştirmez."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd виконує це завдання з іншого файлу, який оголошує таку саму назву, тож цей файл не завантажено. Peel не запускає, не зупиняє, не вмикає й не вимикає його звідси."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd从另一个声明了相同名称的文件运行此任务,因此此文件未载入。Peel不会从此处启动、停止、启用或停用它。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "launchd會從另一個宣告相同名稱的檔案執行此工作,因此這個檔案未載入。Peel不會從這裡啟動、停止、啟用或停用它。"
+ }
+ }
+ }
+ },
"macOS" : {
"comment" : "The system's name, never translated.",
"shouldTranslate" : false
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift
index 1f600638..7b0dd1d6 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift
@@ -39,7 +39,7 @@ public struct BackgroundItem: Sendable, Hashable, Identifiable {
/// True when no installed app claims the job and its program is gone from disk, or it names none of its own.
/// The full rule is `BackgroundItemOwnership.isOrphan(label:program:owner:)`.
public let isOrphan: Bool
- public let state: State
+ public internal(set) var state: State
public let isDisabled: Bool
/// False when only a name points to the owner (`BackgroundItemOwnership.Owner.isConfirmed`).
public var isOwnerConfirmed = true
@@ -66,6 +66,7 @@ public struct BackgroundItem: Sendable, Hashable, Identifiable {
/// True for a job launchd runs from a file no longer on disk, removed while it was loaded: launchd forgets it at
/// the next logout or restart, and nothing loads it again.
public var isFileGone = false
+ public var anotherFileIsLoaded = false
public var isOwnerInstalled: Bool { ownerURL != nil }
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
index 508e6ff5..e92745e6 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
@@ -49,7 +49,11 @@ public enum BackgroundItems {
inTheUserDomain: Launchctl.parseSystemServices(await userDomainPrint.output).map { Set($0.keys) }
)
- var items = declared(in: environment, ownership: ownership, exclusions: exclusions, loaded: loaded)
+ var items = await settlingSharedLabels(
+ declared(in: environment, ownership: ownership, exclusions: exclusions, loaded: loaded)
+ ) { item in
+ Launchctl.parseDetails(await Launchctl.run(["print", BackgroundItemActions.target(of: item)]).output)?.path
+ }
let submitted = undeclared(in: loaded, declared: items, uid: getuid())
@@ -254,6 +258,31 @@ public enum BackgroundItems {
return items
}
+ /// Gives a job two files declare its state on the row of the file launchd loaded it from, which `loadedFrom` asks
+ /// of launchd, and marks the other row as not loaded. When launchd doesn't say which, neither row is said to run.
+ static func settlingSharedLabels(
+ _ items: [BackgroundItem], loadedFrom: (BackgroundItem) async -> String?
+ ) async -> [BackgroundItem] {
+ let declared = items.indices.filter { items[$0].plistURL != nil && !items[$0].isUnreadable }
+ let shared = Dictionary(grouping: declared) { "\(items[$0].kind.rawValue)/\(items[$0].label)" }
+ .values.filter { $0.count > 1 }
+ var settled = items
+ for rows in shared where ![.notLoaded, .unknown].contains(items[rows[0]].state) {
+ let path = await loadedFrom(items[rows[0]]).map { PathPattern.comparablePath(of: URL(filePath: $0)) }
+ for row in rows {
+ guard let path else {
+ settled[row].state = .unknown
+ continue
+ }
+ if let plist = items[row].plistURL, PathPattern.comparablePath(of: plist) != path {
+ settled[row].state = .notLoaded
+ settled[row].anotherFileIsLoaded = true
+ }
+ }
+ }
+ return settled
+ }
+
/// A job file launchd can't load, named by its file since it declares no label that can be read.
private static func unreadable(
_ plist: URL, kind: BackgroundItem.Kind, source: BackgroundItem.Source, ownership: BackgroundItemOwnership
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift
index 74256a03..09867fd9 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift
@@ -44,8 +44,11 @@ enum LaunchdCleanup {
@concurrent
static func stop(_ jobs: [Job], canUseHelper: Bool) async -> [Job] {
var stopped: [Job] = []
- for job in jobs
- where await bootout(job.label, in: job.domain, isDaemon: job.isDaemon, canUseHelper: canUseHelper) {
+ for job in jobs {
+ let loadedFrom = Launchctl.parseDetails(await Launchctl.run(["print", "\(job.domain)/\(job.label)"]).output)?.path
+ guard isLoaded(from: loadedFrom, job),
+ await bootout(job.label, in: job.domain, isDaemon: job.isDaemon, canUseHelper: canUseHelper)
+ else { continue }
stopped.append(job)
}
return stopped
@@ -92,6 +95,14 @@ enum LaunchdCleanup {
return stopped
}
+ /// Whether the job launchd runs under `job`'s label comes from `job`'s file: not when launchd names another file
+ /// that is still there, as when two files declare one label.
+ static func isLoaded(from loadedFrom: String?, _ job: Job) -> Bool {
+ guard let loadedFrom else { return true }
+ let other = URL(filePath: loadedFrom)
+ return PathPattern.comparablePath(of: other) == PathPattern.comparablePath(of: job.plist) || other.isMissing
+ }
+
static func isAppsOwn(_ label: String) -> Bool {
!label.hasPrefix("application.") && PrivilegedPathPolicy.isValidLabel(label) && label != HelperIdentity.helperIdentifier
&& !SystemDaemons.shipped.contains(label) && !SystemAgents.shipped.contains(label)
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift b/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift
index a5c510fe..df1115ea 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift
@@ -11,7 +11,7 @@ public enum FixedSentence: CaseIterable, Sendable {
case notThereAnymore, alreadyThere, protectedByMacOS, irreplaceable, codeFolder, onlyLinksThere, leadsSomewhere
case onlyGoneProgramsThere
case helperOutOfDate, accountNotAllowed, tooManyItems, noTrash, pathTooLong, cannotKeepRecord, cannotReadRecord
- case notInTrash, notMovedByHelper, invalidRequest, configurationMissing
+ case notInTrash, notMovedByHelper, invalidRequest, configurationMissing, declaredTwice
case toolTimedOut, toolStopped
case receiptMisplaced, receiptForgotten, homebrewNotInstalled, helperUnavailable
@@ -49,6 +49,7 @@ public enum FixedSentence: CaseIterable, Sendable {
case .notMovedByHelper: HelperRefusal.notMovedByHelper.rawValue
case .invalidRequest: HelperRefusal.invalidRequest.rawValue
case .configurationMissing: HelperRefusal.missingConfiguration.rawValue
+ case .declaredTwice: HelperRefusal.declaredTwice.rawValue
case .toolTimedOut: Subprocess.Failure.timedOut.explanation
case .toolStopped: Subprocess.Failure.canceled.explanation
case .receiptMisplaced: PackageActions.misplacedReceipt
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/HelperRefusal.swift b/Packages/PeelCore/Sources/PeelPrivileged/HelperRefusal.swift
index df3430b9..7bc27989 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/HelperRefusal.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/HelperRefusal.swift
@@ -13,4 +13,5 @@ public enum HelperRefusal: String, CaseIterable, Sendable {
case notMovedByHelper = "Peel’s helper didn’t move this from there, so it stays in the Trash. You can drag it back out in Finder."
case invalidRequest = "The request wasn’t valid."
case missingConfiguration = "The configuration file is missing."
+ case declaredTwice = "Two files declare this job."
}
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/SystemDaemons.swift b/Packages/PeelCore/Sources/PeelPrivileged/SystemDaemons.swift
index 5234bf0b..8ca20844 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/SystemDaemons.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/SystemDaemons.swift
@@ -17,10 +17,9 @@ public enum SystemDaemons {
/// Where other vendors' daemons are installed.
public static let installed = "/Library/LaunchDaemons"
- /// The one file in `directory` that declares `label`. A file's name usually repeats its label but need
- /// not, so a job is loaded only from the file that declares it. Links are not followed, and a label that
- /// two files declare returns nil.
- public static func file(declaring label: String, in directory: String = installed) -> String? {
+ /// The files in `directory` that declare `label`, two at most: a job is loaded only from the one file that
+ /// declares it, since a file's name usually repeats its label but need not. Links are not followed.
+ public static func files(declaring label: String, in directory: String = installed) -> [String] {
let contents = (try? FileManager.default.contentsOfDirectory(atPath: directory)) ?? []
let declaring = contents.lazy
.filter { $0.hasSuffix(".plist") }
@@ -36,8 +35,7 @@ public enum SystemDaemons {
else { return false }
return plist["Label"] as? String == label
}
- let found = Array(declaring.prefix(2))
- return found.count == 1 ? found[0] : nil
+ return Array(declaring.prefix(2))
}
public static func labels(in directory: String) -> Set<String> {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
index 47313fbe..6d732233 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
@@ -585,6 +585,28 @@ struct DeclaredBackgroundItemsTests {
)
}
+ @Test func aLabelTwoFilesDeclareRunsFromTheOneLaunchdNames() async throws {
+ let directory = try TemporaryDirectory()
+ try directory.file("home/Library/LaunchAgents/org.example.updater.plist", contents: job("org.example.updater"))
+ let shared = try directory.file(
+ "root/Library/LaunchAgents/org.example.updater.plist", contents: job("org.example.updater")
+ )
+ let items = BackgroundItems.declared(
+ in: environment(directory), ownership: BackgroundItemOwnership(installedApps: []),
+ loaded: BackgroundItems.Loaded(user: ["org.example.updater": 42])
+ )
+
+ let named = await BackgroundItems.settlingSharedLabels(items) { _ in shared.path(percentEncoded: false) }
+ let unknown = await BackgroundItems.settlingSharedLabels(items) { _ in nil }
+ let loadedRow = named.first { $0.source == .systemLibrary }
+ let otherRow = named.first { $0.source == .userLibrary }
+
+ #expect(loadedRow?.state == .running(pid: 42))
+ #expect(otherRow?.state == .notLoaded)
+ #expect(otherRow?.anotherFileIsLoaded == true)
+ #expect(unknown.count == 2 && unknown.allSatisfy { $0.state == .unknown })
+ }
+
/// launchd runs a program with the arguments after it, and a program named apart from them (`Program`) takes the
/// place of the first. The whole command is read for its shape.
@Test func readsTheWholeCommandOfAJob() throws {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift
index fc4f636d..e2ac0a45 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift
@@ -435,10 +435,10 @@ struct PrivilegedPathPolicyTests {
try plist("one.plist", label: "com.twice.daemon")
try plist("two.plist", label: "com.twice.daemon")
- #expect(SystemDaemons.file(declaring: "com.vendor.daemon", in: daemons) == real.path(percentEncoded: false))
- #expect(SystemDaemons.file(declaring: "com.linked.daemon", in: daemons) == nil, "a link out of the folder was followed")
- #expect(SystemDaemons.file(declaring: "com.twice.daemon", in: daemons) == nil, "two files declare it, and one was picked")
- #expect(SystemDaemons.file(declaring: "com.nobody.daemon", in: daemons) == nil)
+ #expect(SystemDaemons.files(declaring: "com.vendor.daemon", in: daemons) == [real.path(percentEncoded: false)])
+ #expect(SystemDaemons.files(declaring: "com.linked.daemon", in: daemons).isEmpty, "a link out of the folder was followed")
+ #expect(SystemDaemons.files(declaring: "com.twice.daemon", in: daemons).count == 2, "two files declare it")
+ #expect(SystemDaemons.files(declaring: "com.nobody.daemon", in: daemons).isEmpty)
}
/// The helper opens only what really sits in the user's Trash. The path comes from the app, which reads it
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift
index 688d3111..54b73a3e 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift
@@ -81,6 +81,17 @@ struct RemovalHygieneTests {
#expect(jobs.map(\.domain) == ["user/\(getuid())", "gui/\(getuid())"])
}
+ @Test func stopsAMovedFilesJobOnlyWhenLaunchdLoadedItFromThatFile() throws {
+ let directory = try TemporaryDirectory()
+ let other = try launchdPlist("root/Library/LaunchAgents/org.example.updater.plist", label: "org.example.updater", in: directory)
+ let moved = directory.url.appending(path: "home/Library/LaunchAgents/org.example.updater.plist")
+ let job = LaunchdCleanup.Job(label: "org.example.updater", isDaemon: false, plist: moved)
+
+ #expect(LaunchdCleanup.isLoaded(from: moved.path(percentEncoded: false), job))
+ #expect(LaunchdCleanup.isLoaded(from: nil, job))
+ #expect(!LaunchdCleanup.isLoaded(from: other.path(percentEncoded: false), job))
+ }
+
@Test func findsThePreferenceDomainsToForget() {
let urls = [
URL(filePath: "/Users/x/Library/Preferences/com.example.app.plist"),
diff --git a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
index 1f794aac..6a95a74c 100644
--- a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
+++ b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
@@ -124,6 +124,16 @@ struct BackgroundItemDetailView: View {
}
}
+ if item.anotherFileIsLoaded {
+ Section {
+ Notice(
+ title: Text("Another file with this name is loaded"),
+ detail: Text("launchd runs this job from another file that declares the same name, so this file isn’t loaded. Peel doesn’t start, stop, enable, or disable it from here."),
+ kind: .note
+ ) {}
+ }
+ }
+
if item.hasAnUnusableLabel, !item.canBeControlled {
Section {
Notice(
@@ -354,11 +364,11 @@ struct BackgroundItemDetailView: View {
.contentTransition(.opacity)
}
- /// Start, Stop, Enable, and Disable, which a job Peel may not control, a job whose state Peel could not read, and a
- /// file macOS can't load don't have. A job loaded from a file elsewhere has only Stop. A job Peel may not disable
- /// has only Enable, while launchd keeps it disabled.
+ /// Start, Stop, Enable, and Disable, which a job Peel may not control, a job whose state Peel could not read, a
+ /// file macOS can't load, and a file whose label launchd runs from another file don't have. A job loaded from a
+ /// file elsewhere has only Stop. A job Peel may not disable has only Enable, while launchd keeps it disabled.
private var hasOwnControls: Bool {
- guard item.canBeControlled, item.state != .unknown, !item.isUnreadable else {
+ guard item.canBeControlled, item.state != .unknown, !item.isUnreadable, !item.anotherFileIsLoaded else {
return false
}
if item.canOnlyBeStopped { return true }
diff --git a/Peel/Views/BackgroundItems/BackgroundItemList.swift b/Peel/Views/BackgroundItems/BackgroundItemList.swift
index 9fd076c7..23597dce 100644
--- a/Peel/Views/BackgroundItems/BackgroundItemList.swift
+++ b/Peel/Views/BackgroundItems/BackgroundItemList.swift
@@ -172,6 +172,11 @@ private struct BackgroundItemRow: View {
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
+ } else if item.anotherFileIsLoaded {
+ StatusLabel(title: Text("Another file with this name is loaded"))
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
} else if #available(macOS 27, *), item.runsFromTheTrash {
StatusLabel(title: Text("Runs from the Trash"))
.font(.caption)
diff --git a/Peel/Views/FixedSentenceText.swift b/Peel/Views/FixedSentenceText.swift
index 7db9f01f..2687604a 100644
--- a/Peel/Views/FixedSentenceText.swift
+++ b/Peel/Views/FixedSentenceText.swift
@@ -31,6 +31,7 @@ extension FixedSentence {
case .notMovedByHelper: "Peel’s helper didn’t move this from there, so it stays in the Trash. You can drag it back out in Finder."
case .invalidRequest: "The request wasn’t valid."
case .configurationMissing: "The configuration file is missing."
+ case .declaredTwice: "Two files declare this job."
case .toolTimedOut: "The tool didn’t answer in time, so it was stopped."
case .toolStopped: "Stopped before it finished."
case .receiptMisplaced: "The receipt isn’t where macOS keeps receipts."
diff --git a/PeelHelper/HelperService.swift b/PeelHelper/HelperService.swift
index 3f5f5677..447702f6 100644
--- a/PeelHelper/HelperService.swift
+++ b/PeelHelper/HelperService.swift
@@ -164,13 +164,13 @@ final class HelperService: NSObject, PeelHelperProtocol {
}
let target = "system/\(label)"
// The job's file is found by the `Label` inside it, since a file's name does not always match its label.
- let plist = command == .bootstrap ? SystemDaemons.file(declaring: label) : nil
- if command == .bootstrap, plist == nil {
- reply(HelperRefusal.missingConfiguration.rawValue)
+ let plists = command == .bootstrap ? SystemDaemons.files(declaring: label) : []
+ if command == .bootstrap, plists.count != 1 {
+ reply((plists.isEmpty ? HelperRefusal.missingConfiguration : .declaredTwice).rawValue)
return
}
let arguments = switch command {
- case .bootstrap: ["bootstrap", "system", plist ?? ""]
+ case .bootstrap: ["bootstrap", "system", plists[0]]
case .bootout: ["bootout", target]
case .kickstart: ["kickstart", target]
case .enable: ["enable", target]