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.

A launchctl answer Peel cannot read leaves a job's state unknown

Țugui Dragoș9d64a541082a
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index cfa92c07..c2962c4a 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -71591,6 +71591,112 @@
}
}
},
+ "Peel asked macOS about it and got no answer it could read, so Peel doesn’t start, stop, enable, or disable it here." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel se na ni zeptal systému macOS a nedostal odpověď, kterou by dokázal přečíst, a proto ji tu Peel nespouští, nezastavuje, nezapíná ani nevypíná."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel hat macOS danach gefragt und keine lesbare Antwort erhalten, daher startet, stoppt, aktiviert oder deaktiviert Peel es hier nicht."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel se lo ha preguntado a macOS y no ha obtenido ninguna respuesta que pueda leer, así que aquí Peel no lo inicia, no lo detiene, no lo activa ni lo desactiva."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel a interrogé macOS à son sujet, sans obtenir de réponse lisible : Peel ne le démarre donc pas, ne l’arrête pas, ne l’active pas et ne le désactive pas ici."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel l’ha chiesto a macOS e non ha ricevuto una risposta leggibile, quindi qui Peel non lo avvia, non lo interrompe, non lo abilita e non lo disabilita."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "PeelはmacOSに問い合わせましたが、読み取れる応答がなかったため、ここでは開始、停止、有効化、無効化を行いません。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel이 macOS에 물었지만 읽을 수 있는 응답을 받지 못했으므로 Peel은 여기에서 이 항목을 시작, 중단, 활성화 또는 비활성화하지 않습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel heeft het aan macOS gevraagd, maar kreeg geen antwoord dat Peel kon lezen, dus Peel start het hier niet, stopt het niet en schakelt het niet in of uit."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel zapytał o to macOS i nie otrzymał odpowiedzi, którą mógłby odczytać, więc Peel tego tutaj nie uruchamia, nie zatrzymuje, nie włącza ani nie wyłącza."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O Peel perguntou ao macOS sobre ele e não obteve uma resposta que conseguisse ler, por isso o Peel não o inicia, não o interrompe, não o ativa nem o desativa aqui."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel a întrebat macOS despre el și nu a primit niciun răspuns pe care să îl poată citi, așa că Peel nu îl pornește, nu îl oprește, nu îl activează și nu îl dezactivează de aici."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel спросил macOS о нем, но не получил ответа, который смог бы прочитать, поэтому Peel здесь не запускает, не останавливает, не включает и не выключает его."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel frågade macOS om det och fick inget svar som gick att läsa, så Peel varken startar, stoppar, aktiverar eller avaktiverar det här."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel bunu macOS’e sordu ve okuyabileceği bir yanıt alamadı, bu yüzden Peel onu burada başlatmaz, durdurmaz, etkinleştirmez veya etkisizleştirmez."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel запитала macOS про нього, але не отримала відповіді, яку могла б прочитати, тож Peel тут його не запускає, не зупиняє, не вмикає й не вимикає."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel向macOS查询了它的状态,但没有得到可读取的回应,因此Peel不会在此处启动、停止、启用或停用它。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel向macOS詢問了它的狀態,但沒有得到它能讀取的回應,因此Peel不會在這裡啟動、停止、啟用或停用它。"
+ }
+ }
+ }
+ },
"Peel asked macOS what was installed with a package and got no answer. This list says nothing about what is on this Mac." : {
"localizations" : {
"cs" : {
@@ -72651,6 +72757,112 @@
}
}
},
+ "Peel can’t tell whether this runs" : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel nedokáže zjistit, zda běží"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel kann nicht erkennen, ob dieses Objekt läuft"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel no puede saber si se está ejecutando"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel ne peut pas savoir si cet élément est actif"
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel non riesce a capire se è in esecuzione"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peelでは実行中かどうかを判断できません"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel은 이 항목이 실행 중인지 알 수 없습니다"
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel kan niet zien of dit actief is"
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel nie może ustalić, czy to działa"
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O Peel não consegue saber se este item está em execução"
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel nu poate ști dacă rulează"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel не может определить, выполняется ли этот объект"
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel kan inte avgöra om det här är igång"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel bunun çalışıp çalışmadığını anlayamıyor"
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel не може визначити, чи виконується цей елемент"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel无法判断它是否正在运行"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel無法判斷它是否正在執行"
+ }
+ }
+ }
+ },
"Peel compares files by their full contents. A folder is a copy only when every file in it matches, hidden ones included. Repositories (Git, Mercurial, Subversion), projects with a build file such as package.json or Cargo.toml, node_modules, and libraries such as Photos and Music are left alone, and an app is never offered on its own. A build file at the top of a folder you chose doesn’t make it a project." : {
"localizations" : {
"cs" : {
@@ -116527,6 +116739,119 @@
}
}
},
+ "Unknown (background item state)" : {
+ "extractionState" : "extracted_with_value",
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Není známo"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Unbekannt"
+ }
+ },
+ "en" : {
+ "stringUnit" : {
+ "state" : "new",
+ "value" : "Unknown"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Desconocido"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Inconnu"
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Sconosciuto"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "不明"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "알 수 없음"
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Onbekend"
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Nieznany"
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Desconhecido"
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Necunoscut"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Неизвестно"
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Okänt"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bilinmiyor"
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Невідомо"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "未知"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "未知"
+ }
+ }
+ }
+ },
"Unknown (extension state)" : {
"extractionState" : "extracted_with_value",
"localizations" : {
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift
index e1da09e4..7187df60 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItem.swift
@@ -17,6 +17,7 @@ public struct BackgroundItem: Sendable, Hashable, Identifiable {
case running(pid: Int32)
case loaded
case notLoaded
+ case unknown
}
public let label: String
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
index 6d97b501..d7dcd81f 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
@@ -51,8 +51,6 @@ public enum BackgroundItems {
.sorted { $0.label.localizedStandardCompare($1.label) == .orderedAscending }
}
- /// What `launchctl` reports right now: the loaded jobs, with the process ID of each one running, and the
- /// jobs marked disabled or enabled.
/// The loaded jobs no file in the three folders declares, which an app may have submitted and `appSubmittedItem`
/// then asks about. Apple's own are left out.
static func undeclared(
@@ -63,17 +61,40 @@ public enum BackgroundItems {
// By kind and label: an item's `id` also holds its file's path, which a loaded job does not report.
let known = Set(items.map { "\($0.kind.rawValue)/\($0.label)" })
let candidates: [(label: String, kind: BackgroundItem.Kind, target: String)] =
- loaded.user.keys.map { ($0, .agent, "\(userDomain)/\($0)") } + loaded.system.keys.map { ($0, .daemon, "system/\($0)") }
+ (loaded.user ?? [:]).keys.map { ($0, .agent, "\(userDomain)/\($0)") }
+ + (loaded.system ?? [:]).keys.map { ($0, .daemon, "system/\($0)") }
return candidates.filter { label, kind, _ in
!label.hasPrefix("com.apple.") && !label.hasPrefix("application.") && !known.contains("\(kind.rawValue)/\(label)")
}.sorted { $0.label < $1.label }
}
+ /// What `launchctl` reports right now: the loaded jobs, with the process ID of each one running, and the
+ /// jobs marked disabled or enabled. Each is nil when `launchctl` answered in a form Peel cannot read.
struct Loaded {
- var user: [String: Int32?] = [:]
- var system: [String: Int32?] = [:]
- var userDisabled: [String: Bool] = [:]
- var systemDisabled: [String: Bool] = [:]
+ var user: [String: Int32?]? = [:]
+ var system: [String: Int32?]? = [:]
+ var userDisabled: [String: Bool]? = [:]
+ var systemDisabled: [String: Bool]? = [:]
+
+ /// The state of the job `label` of `kind`, known only when what `launchctl` said about both the jobs and
+ /// the overrides of its domain could be read.
+ func state(of label: String, _ kind: BackgroundItem.Kind) -> BackgroundItem.State {
+ guard let jobs = kind == .agent ? user : system, overrides(kind) != nil else { return .unknown }
+ return switch jobs[label] {
+ case .none: .notLoaded
+ case .some(.none): .loaded
+ case .some(.some(let pid)): .running(pid: pid)
+ }
+ }
+
+ /// Whether `launchctl` marks the job `label` of `kind` disabled, or nil when it says nothing of it.
+ func override(of label: String, _ kind: BackgroundItem.Kind) -> Bool? {
+ overrides(kind)?[label]
+ }
+
+ private func overrides(_ kind: BackgroundItem.Kind) -> [String: Bool]? {
+ kind == .agent ? userDisabled : systemDisabled
+ }
}
/// Returns the jobs declared in `~/Library/LaunchAgents`, `/Library/LaunchAgents`, and `/Library/LaunchDaemons`.
@@ -98,8 +119,6 @@ public enum BackgroundItems {
// Skips a job with the label of one of macOS's own daemons. Any other `com.apple.` label is kept
// and shown, because a made-up Apple label is a common way to disguise a job.
guard let job = JobDefinition(contentsOf: plist), !SystemDaemons.shipped.contains(job.label), !SystemAgents.shipped.contains(job.label) else { continue }
- let jobs = kind == .agent ? loaded.user : loaded.system
- let disabled = kind == .agent ? loaded.userDisabled : loaded.systemDisabled
let owner = ownership.owner(label: job.label, associated: job.associated, program: job.program)
items.append(BackgroundItem(
label: job.label,
@@ -113,8 +132,8 @@ public enum BackgroundItems {
ownerName: owner?.name,
isOwnerInstalled: owner?.isInstalled ?? false,
isOrphan: ownership.isOrphan(label: job.label, program: job.program, owner: owner),
- state: state(of: jobs[job.label]),
- isDisabled: disabled[job.label] ?? job.isDisabled
+ state: loaded.state(of: job.label, kind),
+ isDisabled: loaded.override(of: job.label, kind) ?? job.isDisabled
))
}
}
@@ -130,7 +149,6 @@ public enum BackgroundItems {
let isSubmittedByApp = details.path?.hasPrefix("(submitted by") == true
&& details.program.map { !PathComponents.isPath($0, inside: "/System") } == true
guard details.managedBy == serviceManagement || isSubmittedByApp else { return nil }
- let isAgent = candidate.kind == .agent
let path = details.path.flatMap { $0.hasPrefix("/") ? URL(filePath: $0) : nil }
let job = path.flatMap(JobDefinition.init(contentsOf:))
let program = details.program ?? job?.program
@@ -153,19 +171,11 @@ public enum BackgroundItems {
ownerName: owner.name,
isOwnerInstalled: owner.isInstalled,
isOrphan: ownership.isOrphan(label: candidate.label, program: program, owner: owner),
- state: state(of: (isAgent ? loaded.user : loaded.system)[candidate.label]),
- isDisabled: (isAgent ? loaded.userDisabled : loaded.systemDisabled)[candidate.label] ?? false
+ state: loaded.state(of: candidate.label, candidate.kind),
+ isDisabled: loaded.override(of: candidate.label, candidate.kind) ?? false
)
}
- private static func state(of job: Int32??) -> BackgroundItem.State {
- switch job {
- case .none: .notLoaded
- case .some(.none): .loaded
- case .some(.some(let pid)): .running(pid: pid)
- }
- }
-
private static func plists(in folder: URL) -> [URL] {
let contents = (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? []
return contents.filter { $0.pathExtension == "plist" }
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift
index ff0e381a..90a6a523 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift
@@ -20,53 +20,56 @@ enum Launchctl {
}
}
- /// Parses `launchctl list`: "PID\tStatus\tLabel", where PID is "-" for jobs that aren't running.
- static func parseList(_ output: String) -> [String: Int32?] {
+ /// Parses `launchctl list`: "PID\tStatus\tLabel", where PID is "-" for jobs that aren't running. Nil when the
+ /// output does not start with that header: `launchctl`'s output can change, and another form says nothing.
+ static func parseList(_ output: String) -> [String: Int32?]? {
+ let lines = output.split(whereSeparator: \.isNewline)
+ guard lines.first == "PID\tStatus\tLabel" else { return nil }
var jobs: [String: Int32?] = [:]
- for line in output.split(whereSeparator: \.isNewline) {
+ for line in lines.dropFirst() {
let columns = line.split(separator: "\t", omittingEmptySubsequences: false)
- guard columns.count == 3, columns[0] != "PID" else { continue }
+ guard columns.count == 3 else { continue }
jobs[String(columns[2])] = Int32(columns[0])
}
return jobs
}
- /// Parses the "services = { … }" block of `launchctl print system`: "pid exit-status label".
- static func parseSystemServices(_ output: String) -> [String: Int32?] {
- var jobs: [String: Int32?] = [:]
- var isInServices = false
+ /// Parses the "services = { … }" block of `launchctl print system`: "pid exit-status label". Nil when there is
+ /// no such block.
+ static func parseSystemServices(_ output: String) -> [String: Int32?]? {
+ var jobs: [String: Int32?]?
for line in output.split(whereSeparator: \.isNewline) {
let trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed == "services = {" {
- isInServices = true
+ jobs = [:]
continue
}
- guard isInServices else { continue }
+ guard jobs != nil else { continue }
if trimmed == "}" { break }
let columns = trimmed.split(whereSeparator: \.isWhitespace)
guard columns.count >= 3 else { continue }
- jobs[columns[2...].joined(separator: " ")] = Int32(columns[0]).flatMap { $0 > 0 ? $0 : nil }
+ jobs?[columns[2...].joined(separator: " ")] = Int32(columns[0]).flatMap { $0 > 0 ? $0 : nil }
}
return jobs
}
- /// Parses the `"label" => disabled|enabled` lines of a "disabled services = { … }" block.
- static func parseDisabled(_ output: String) -> [String: Bool] {
- var overrides: [String: Bool] = [:]
- var isInBlock = false
+ /// Parses the `"label" => disabled|enabled` lines of a "disabled services = { … }" block. Nil when there is no
+ /// such block.
+ static func parseDisabled(_ output: String) -> [String: Bool]? {
+ var overrides: [String: Bool]?
for line in output.split(whereSeparator: \.isNewline) {
let trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed == "disabled services = {" {
- isInBlock = true
+ overrides = [:]
continue
}
- guard isInBlock else { continue }
+ guard overrides != nil else { continue }
if trimmed == "}" { break }
// Finds the last arrow after the opening quote, because a label can contain an arrow of its own.
let afterQuote = trimmed.index(after: trimmed.startIndex)..<trimmed.endIndex
guard trimmed.hasPrefix("\""), let arrow = trimmed.range(of: "\" => ", options: .backwards, range: afterQuote) else { continue }
let label = String(trimmed[trimmed.index(after: trimmed.startIndex)..<arrow.lowerBound])
- overrides[label] = trimmed[arrow.upperBound...].hasPrefix("disabled")
+ overrides?[label] = trimmed[arrow.upperBound...].hasPrefix("disabled")
}
return overrides
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
index 8b033954..fa985172 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
@@ -189,6 +189,22 @@ struct DeclaredBackgroundItemsTests {
#expect(items.first?.isDisabled == true)
}
+ /// Where `launchctl` answered in a form Peel cannot read, a job's state is not known, never "not loaded",
+ /// whether its list of jobs or its overrides could not be read. Its loaded jobs are not asked about either.
+ @Test func aJobWhoseStateCouldNotBeReadIsNotKnown() throws {
+ let directory = try TemporaryDirectory()
+ try directory.file("home/Library/LaunchAgents/agent.plist", contents: job("com.example.agent"))
+ try directory.file("root/Library/LaunchDaemons/daemon.plist", contents: job("com.example.daemon"))
+ let loaded = BackgroundItems.Loaded(user: nil, system: ["com.example.daemon": 12], systemDisabled: nil)
+ let ownership = BackgroundItemOwnership(installedApps: [])
+
+ let items = BackgroundItems.declared(in: environment(directory), ownership: ownership, loaded: loaded)
+
+ #expect(items.first { $0.label == "com.example.agent" }?.state == .unknown)
+ #expect(items.first { $0.label == "com.example.daemon" }?.state == .unknown)
+ #expect(BackgroundItems.undeclared(in: loaded, declared: items, userDomain: "gui/501").isEmpty)
+ }
+
/// A loaded job is asked about as one an app submitted only when no file in the three folders declares it, so
/// a job with a file is never asked about again, nor listed a second time. Apple's own are never asked about.
@Test func asksOnlyAboutLoadedJobsNoFileDeclares() throws {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift
index 7f1b6f10..eea429fc 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift
@@ -9,18 +9,31 @@ struct LaunchctlTests {
let output = "\tdisabled services = {\n\t\t\" => x\" => disabled\n\t\t\"com.example.agent\" => enabled\n\t}"
let parsed = Launchctl.parseDisabled(output)
- #expect(parsed[" => x"] == true)
- #expect(parsed["com.example.agent"] == false)
+ #expect(parsed?[" => x"] == true)
+ #expect(parsed?["com.example.agent"] == false)
}
- @Test func parsesUserJobList() {
+ @Test func parsesUserJobList() throws {
let output = "PID\tStatus\tLabel\n-\t0\tcom.adguard.mac.adguard.loginhelper\n22251\t0\tapplication.com.example.jotter.22249290.22249296\n"
- let jobs = Launchctl.parseList(output)
+ let jobs = try #require(Launchctl.parseList(output))
#expect(jobs.count == 2)
#expect(jobs["com.adguard.mac.adguard.loginhelper"] == .some(nil))
#expect(jobs["application.com.example.jotter.22249290.22249296"] == .some(22251))
}
+ /// `launchctl`'s output is not an interface and can change. An answer in a form Peel does not recognize says
+ /// nothing about which jobs are loaded, so it is read as not known rather than as no jobs at all.
+ @Test func anAnswerInAnotherFormIsNotKnown() {
+ #expect(Launchctl.parseList("Label\tPID\ncom.example.agent\t-\n") == nil)
+ #expect(Launchctl.parseList("Could not connect to the domain.\n") == nil)
+ #expect(Launchctl.parseSystemServices("system = {\n\tjobs = {\n\t}\n}\n") == nil)
+ #expect(Launchctl.parseDisabled("Bad request.\n") == nil)
+
+ #expect(Launchctl.parseList("PID\tStatus\tLabel\n") == [:])
+ #expect(Launchctl.parseSystemServices("system = {\n\tservices = {\n\t}\n}\n") == [:])
+ #expect(Launchctl.parseDisabled("\tdisabled services = {\n\t}\n") == [:])
+ }
+
@Test func parsesSystemServicesAndDisabledOverrides() {
let output = """
system = {
@@ -40,8 +53,8 @@ struct LaunchctlTests {
}
"""
let services = Launchctl.parseSystemServices(output)
- #expect(services["com.vix.cron"] == .some(nil))
- #expect(services["com.adguard.mac.adguard.helper"] == .some(761))
+ #expect(services?["com.vix.cron"] == .some(nil))
+ #expect(services?["com.adguard.mac.adguard.helper"] == .some(761))
let disabled = Launchctl.parseDisabled(output)
#expect(disabled == ["com.piriform.ccleaner.uninstall": false, "com.example.daemon": true])
diff --git a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
index a17520ad..24bb9824 100644
--- a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
+++ b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
@@ -105,15 +105,25 @@ struct BackgroundItemDetailView: View {
}
}
+ if item.state == .unknown {
+ Section {
+ Notice(
+ title: Text("Peel can’t tell whether this runs"),
+ detail: Text("Peel asked macOS about it and got no answer it could read, so Peel doesn’t start, stop, enable, or disable it here."),
+ kind: .note
+ ) {}
+ }
+ }
+
if needsHelper {
Section {
HelperRequiredBanner()
}
}
- // Leaves out the section when it would be empty: Peel's helper has no Start, Stop, Enable, or Disable
+ // Leaves out the section when it would be empty: some jobs have no Start, Stop, Enable, or Disable
// buttons, and a job macOS registered for an app has no file to show.
- if !item.isPeelsHelper || finderURL != nil {
+ if hasOwnControls || finderURL != nil {
Section {
if item.canMoveToTrash {
ExclusionsUnreadableBanner()
@@ -230,22 +240,25 @@ struct BackgroundItemDetailView: View {
/// The item's state, as one badge whose text, symbol, and color change with it. A badge per state would swap
/// without a fade, because a form row shows a newly inserted view at once.
private var stateBadge: some View {
- let (title, symbol, tint): (Text, String, Color) = if item.isDisabled {
- (Text("Disabled"), "minus.circle", .orange)
- } else {
- switch item.state {
- case .running(let pid): (Text("Running · PID \(String(pid))"), "circle.fill", .green)
- case .loaded: (Text("Not running"), "circle", .secondary)
- case .notLoaded: (Text("Not loaded"), "circle.dashed", .secondary)
- }
+ let (title, symbol, tint): (Text, String, Color) = switch item.state {
+ case .unknown: (Text(.unknownBackgroundItemState), "questionmark.circle.dashed", .secondary)
+ case _ where item.isDisabled: (Text("Disabled"), "minus.circle", .orange)
+ case .running(let pid): (Text("Running · PID \(String(pid))"), "circle.fill", .green)
+ case .loaded: (Text("Not running"), "circle", .secondary)
+ case .notLoaded: (Text("Not loaded"), "circle.dashed", .secondary)
}
// The state changes right after the user presses a button here, so the text and symbol crossfade.
return Badge(title: title, systemImage: symbol, tint: tint)
.contentTransition(.opacity)
}
+ /// Start, Stop, Enable, and Disable, which Peel's own helper, a job under one of Apple's names, and a job whose
+ /// state Peel could not read don't have.
+ private var hasOwnControls: Bool {
+ !item.isPeelsHelper && !item.declaresAnAppleLabel && item.state != .unknown
+ }
+
private var controls: some View {
- let hasOwnControls = !item.isPeelsHelper && !item.declaresAnAppleLabel
let hasFileControls = finderURL != nil || item.canMoveToTrash
// With controls on one side only, there is no spacer, so the row is only as wide as its buttons and is
// centered. When the buttons don't fit on one line, `FlowLayout` wraps them onto the next.
diff --git a/Peel/Views/BackgroundItems/BackgroundItemList.swift b/Peel/Views/BackgroundItems/BackgroundItemList.swift
index 1278738a..1086658b 100644
--- a/Peel/Views/BackgroundItems/BackgroundItemList.swift
+++ b/Peel/Views/BackgroundItems/BackgroundItemList.swift
@@ -161,9 +161,11 @@ struct BackgroundItemStateIndicator: View {
.accessibilityLabel(label)
}
+ // A state Peel could not read comes first, since whether the job is disabled may not have been read either.
private var symbol: String {
- if item.isDisabled { return "minus.circle.fill" }
- return switch item.state {
+ switch item.state {
+ case .unknown: "questionmark.circle.dashed"
+ case _ where item.isDisabled: "minus.circle.fill"
case .running: "circle.fill"
case .loaded: "circle"
case .notLoaded: "circle.dashed"
@@ -171,17 +173,29 @@ struct BackgroundItemStateIndicator: View {
}
private var color: Color {
- if item.isDisabled { return .orange }
- if case .running = item.state { return .green }
- return .secondary
+ switch item.state {
+ case .unknown: .secondary
+ case _ where item.isDisabled: .orange
+ case .running: .green
+ case .loaded, .notLoaded: .secondary
+ }
}
private var label: Text {
- if item.isDisabled { return Text("Disabled") }
- return switch item.state {
+ switch item.state {
+ case .unknown: Text(.unknownBackgroundItemState)
+ case _ where item.isDisabled: Text("Disabled")
case .running: Text("Running")
case .loaded: Text("Not running")
case .notLoaded: Text("Not loaded")
}
}
}
+
+extension LocalizedStringResource {
+ /// The state of a background item when `launchctl` did not say it in a form Peel can read.
+ static let unknownBackgroundItemState = LocalizedStringResource(
+ "Unknown (background item state)",
+ defaultValue: "Unknown"
+ )
+}