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.

Long peel scans say how far they have got

Țugui Dragoș83ef913b28f3
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 9d1e6d56..eda8f2cc 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -183,7 +183,9 @@ beside each item, stop there with `--dry-run`, ask unless given `-y`, exit 2 whe
removal couldn't finish, and write the same History the app shows. The tool never uses the helper. Everything it
prints goes through `Output`, so scripts can read it: its own words are plain ASCII, and names, paths, and what
macOS says in an error are printed as they are, in UTF-8, with every character that could hide or reorder text shown
-as `?` (`PlainText`).
+as `?` (`PlainText`). A long scan says how far it has got on one line of standard error, written over itself and
+cleared before anything else is printed (`ProgressLine`). Only a terminal shows it, and only while `peel` is its
+foreground job, so a script reading standard error gets nothing.
The app's build puts the tool's shell completions, written by the tool it just built, and its manual page,
`Support/peel.1`, in `Peel.app/Contents/Resources/completions` and `man` (the Command Line Documentation phase),
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift
index 0ee27674..0e5bfa74 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift
@@ -142,13 +142,15 @@ struct LeftoversCommand: AsyncParsableCommand {
let exclusions = await ExclusionStore().load()
try AppLookup.refuseIfExcluded(target, by: exclusions)
let homebrew = await CaskLookup.evidence(for: target)
- let uninstallation = await Uninstallation.prepare(
- target,
- installedApps: apps,
- exclusions: exclusions,
- casks: homebrew.casks,
- receipts: homebrew.receipts
- )
+ let uninstallation = await ProgressLine.counting {
+ await Uninstallation.prepare(
+ target,
+ installedApps: apps,
+ exclusions: exclusions,
+ casks: homebrew.casks,
+ receipts: homebrew.receipts
+ )
+ }
let leftovers = uninstallation.scan.leftovers.filter { all || $0.match.isRecommended }
// Printed in JSON mode too, on standard error, so a script that reads an empty list still learns what
@@ -413,13 +415,15 @@ struct UninstallCommand: AsyncParsableCommand {
}
try await Self.refuseWhileRunning(target, among: apps)
let homebrew = await CaskLookup.evidence(for: target)
- let uninstallation = await Uninstallation.prepare(
- target,
- installedApps: apps,
- exclusions: exclusions,
- casks: homebrew.casks,
- receipts: homebrew.receipts
- )
+ let uninstallation = await ProgressLine.counting {
+ await Uninstallation.prepare(
+ target,
+ installedApps: apps,
+ exclusions: exclusions,
+ casks: homebrew.casks,
+ receipts: homebrew.receipts
+ )
+ }
guard !uninstallation.appRequiresPrivileges else {
throw CommandFailure("Moving \(Output.plain(target.name)) to the Trash needs administrator access. Remove it with the Peel app.")
}
@@ -624,11 +628,12 @@ struct UpdatesCommand: AsyncParsableCommand {
// The Peel app's own update settings, so `peel` and the app agree on which updates are waiting.
let preferences = UpdatePreferences.asTheAppSeesThem()
let homebrew = await CaskLookup.installed()
- let statuses = await Self.statuses(
- for: apps.filter { !preferences.isIgnored($0) },
- preference: preferences.source,
- casks: homebrew.casks
- )
+ let toCheck = apps.filter { !preferences.isIgnored($0) }
+ let statuses = await ProgressLine.reporting { show in
+ await Self.statuses(for: toCheck, preference: preferences.source, casks: homebrew.casks) { answered in
+ show(Self.progress(checked: answered, of: toCheck.count))
+ }
+ }
let report = Self.report(apps: apps, statuses: statuses, preferences: preferences, all: all)
if output.json {
@@ -658,6 +663,10 @@ struct UpdatesCommand: AsyncParsableCommand {
}
}
+ static func progress(checked: Int, of total: Int) -> String {
+ "Checked \(Output.number(checked)) of \(Output.count(total, "app", "apps"))"
+ }
+
/// The status as the table writes it. An update the person skipped in the app reads as skipped.
static func summary(_ status: UpdateStatus, isWaiting: Bool) -> String {
switch status {
@@ -672,7 +681,8 @@ struct UpdatesCommand: AsyncParsableCommand {
private static func statuses(
for apps: [InstalledApp],
preference: UpdateSource,
- casks: [HomebrewPackage]
+ casks: [HomebrewPackage],
+ answered: (Int) -> Void
) async -> [InstalledApp.ID: UpdateStatus] {
let checker = UpdateChecker()
return await withTaskGroup(of: (InstalledApp.ID, UpdateStatus).self) { group in
@@ -684,6 +694,7 @@ struct UpdatesCommand: AsyncParsableCommand {
}
while case let (id, status)? = await group.next() {
statuses[id] = status
+ answered(statuses.count)
if let app = pending.next() {
group.addTask { (app.id, await checker.status(for: app, preference: preference, casks: casks)) }
}
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift
index 601edbbd..8a05a7b6 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift
@@ -71,9 +71,9 @@ struct OrphansCommand: AsyncParsableCommand {
let running = Set(await RunningCopies.current.map(\.bundleIdentifier))
let exclusions = await UnreadableExclusions.load()
let scanner = OrphanScanner(exclusions: exclusions)
- let scan = await scanner.scan(
- installedApps: apps, remembered: remembered, running: running, owners: OrphanOwners().load()
- )
+ let scan = await ProgressLine.counting {
+ await scanner.scan(installedApps: apps, remembered: remembered, running: running, owners: OrphanOwners().load())
+ }
if let group {
return try await clean(group, in: scan, apps: apps, scanner: scanner, using: TrashService(exclusions: exclusions))
}
@@ -208,7 +208,8 @@ struct CachesCommand: AsyncParsableCommand {
}
func run() async throws {
- let all = await DeveloperCaches.scan(exclusions: UnreadableExclusions.load())
+ let exclusions = await UnreadableExclusions.load()
+ let all = await ProgressLine.counting { await DeveloperCaches.scan(exclusions: exclusions) }
let environments = try Self.chosen(from: all, named: tools)
guard !remove else {
return try await clean(environments, using: TrashService(exclusions: await ExclusionStore().load()))
@@ -379,7 +380,8 @@ struct ProjectsCommand: AsyncParsableCommand {
Output.note("\(Output.plain(Output.path(root))): \(refusal.summary)")
}
}
- let scan = await ProjectArtifacts.scan(roots: roots, exclusions: UnreadableExclusions.load())
+ let exclusions = await UnreadableExclusions.load()
+ let scan = await ProgressLine.counting { await ProjectArtifacts.scan(roots: roots, exclusions: exclusions) }
let artifacts = scan.artifacts
if remove {
Self.notes(for: scan).forEach(Output.note)
@@ -544,7 +546,9 @@ struct DuplicatesCommand: AsyncParsableCommand {
var options = DuplicateScanOptions(folders: urls)
options.kind = kind?.fileKind ?? .any
options.minimumSize = minimumSize?.bytes ?? 1
- let scan = try await finder.scan(options)
+ let scan = try await ProgressLine.reporting { show in
+ try await finder.scan(options) { show(Self.progress($0)) }
+ }
if remove {
Self.notes(for: scan).forEach(Output.note)
return try await clean(scan, using: TrashService(exclusions: await ExclusionStore().load()))
@@ -601,6 +605,17 @@ struct DuplicatesCommand: AsyncParsableCommand {
)
}
+ /// The progress line for each step of the scan. The folders are compared by the files inside them, so both
+ /// steps compare and read files.
+ static func progress(_ report: DuplicateScanProgress) -> String {
+ switch report {
+ case .listing(let found): "Looking through folders: \(Output.number(found)) found"
+ case .collecting(let found): "Looking for files: \(Output.number(found)) found"
+ case .comparing(let compared, let total): "Comparing files: \(Output.number(compared)) of \(Output.number(total))"
+ case .verifying(let read, let total): "Reading contents: \(Output.size(read)) of \(Output.size(total))"
+ }
+ }
+
static func heading(for group: DuplicateFolderGroup) -> String {
"\(Output.count(group.folders.count, "copy", "copies")) of a folder of \(Output.count(group.fileCount, "file", "files")), \(Output.size(group.size)), \(Output.size(group.reclaimableSize)) to free"
}
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/ProgressLine.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/ProgressLine.swift
new file mode 100644
index 00000000..a981ea40
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/ProgressLine.swift
@@ -0,0 +1,125 @@
+import Darwin
+import Dispatch
+import PeelCore
+import Synchronization
+
+/// One line on standard error that says how far a long scan has got, written over itself as the scan goes on and
+/// cleared once it ends, before the command prints anything else. Only a terminal shows it, and only while `peel`
+/// is its foreground job: a script reading standard error, or a job sent to the background, gets nothing.
+enum ProgressLine {
+ /// Nothing is drawn in the first half second, so a quick scan leaves no flash behind.
+ private static let firstDraw = DispatchTimeInterval.milliseconds(500)
+ private static let redraw = DispatchTimeInterval.milliseconds(100)
+
+ /// Runs a scan that counts what it reads (`ScanCount`), and shows how much it has read.
+ static func counting<Answer>(on descriptor: Int32 = STDERR_FILENO, _ scan: () async throws -> Answer) async rethrows -> Answer {
+ let count = ScanCount()
+ return try await showing({ lookedAt(count.value) }, on: descriptor) {
+ try await ScanCount.$current.withValue(count) { try await scan() }
+ }
+ }
+
+ /// Runs `work`, which tells `show` what the line says, and shows the newest of it.
+ static func reporting<Answer>(
+ on descriptor: Int32 = STDERR_FILENO,
+ _ work: (_ show: @escaping @Sendable (String) -> Void) async throws -> Answer
+ ) async rethrows -> Answer {
+ let newest = Newest()
+ return try await showing({ newest.text }, on: descriptor) {
+ try await work { newest.text = $0 }
+ }
+ }
+
+ /// What a scan that counts its reads says, in the app's words, once it has read something.
+ static func lookedAt(_ read: Int) -> String? {
+ read > 0 ? "Looked at \(Output.count(read, "item", "items"))" : nil
+ }
+
+ private static func showing<Answer>(
+ _ text: @escaping @Sendable () -> String?,
+ on descriptor: Int32,
+ while work: () async throws -> Answer
+ ) async rethrows -> Answer {
+ guard isatty(descriptor) == 1 else { return try await work() }
+ let line = Line(descriptor)
+ let timer = DispatchSource.makeTimerSource(queue: line.queue)
+ timer.setEventHandler { line.draw(text()) }
+ timer.schedule(deadline: .now() + firstDraw, repeating: redraw)
+ timer.activate()
+ defer {
+ // A canceled timer starts no new draw, and the queue holds the clear until a draw under way is done.
+ timer.cancel()
+ line.queue.sync { line.clear() }
+ }
+ return try await work()
+ }
+}
+
+private final class Newest: Sendable {
+ private let said = Mutex<String?>(nil)
+
+ var text: String? {
+ get { said.withLock { $0 } }
+ set { said.withLock { $0 = newValue } }
+ }
+}
+
+/// The line itself, drawn and cleared only on its own queue.
+private final class Line: Sendable {
+ let queue = DispatchQueue(label: "com.tuguidragos.Peel.CLI.progress")
+ private let descriptor: Int32
+ private let shown = Mutex("")
+
+ init(_ descriptor: Int32) {
+ self.descriptor = descriptor
+ }
+
+ func draw(_ text: String?) {
+ guard let text, isTheForegroundJob else { return }
+ // A line as wide as the terminal wraps, and a carriage return goes back only to the start of its last row.
+ let width = columns.map { $0 - 1 } ?? .max
+ let fitted = String(text.prefix(max(width, 0)))
+ shown.withLock { shown in
+ guard fitted != shown else { return }
+ write("\r" + fitted + String(repeating: " ", count: max(min(shown.count, width) - fitted.count, 0)))
+ shown = fitted
+ }
+ }
+
+ func clear() {
+ shown.withLock { shown in
+ guard !shown.isEmpty, isTheForegroundJob else { return }
+ write("\r" + String(repeating: " ", count: shown.count) + "\r")
+ shown = ""
+ }
+ }
+
+ /// A job in the background would draw over what is being typed in front of it. A terminal that is not this
+ /// process's own has no foreground job to ask about (`tcgetpgrp(3)`), and is drawn on.
+ private var isTheForegroundJob: Bool {
+ let foreground = tcgetpgrp(descriptor)
+ return foreground < 0 || foreground == getpgrp()
+ }
+
+ private var columns: Int? {
+ var size = winsize()
+ guard withUnsafeMutablePointer(to: &size, { ioctl(descriptor, TIOCGWINSZ, $0) }) == 0, size.ws_col > 0 else {
+ return nil
+ }
+ return Int(size.ws_col)
+ }
+
+ private func write(_ text: String) {
+ var bytes = Array(text.utf8)[...]
+ while !bytes.isEmpty {
+ let written = bytes.withUnsafeBytes { Darwin.write(descriptor, $0.baseAddress, $0.count) }
+ if written > 0 {
+ bytes = bytes.dropFirst(written)
+ } else if written < 0, errno == EINTR {
+ continue
+ } else {
+ return
+ }
+ }
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ProgressLineTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ProgressLineTests.swift
new file mode 100644
index 00000000..bdf07034
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ProgressLineTests.swift
@@ -0,0 +1,158 @@
+import Darwin
+import Foundation
+@testable import PeelCommandLine
+@testable import PeelCore
+import Testing
+
+/// A pseudo terminal, the kind a Terminal window is: what `peel` writes on its replica is read here as the window
+/// would draw it.
+private final class Terminal {
+ let replica: Int32
+ private let primary: Int32
+ private(set) var drawn = ""
+
+ init(columns: UInt16 = 80) throws {
+ var primary: Int32 = 0
+ var replica: Int32 = 0
+ var size = winsize(ws_row: 24, ws_col: columns, ws_xpixel: 0, ws_ypixel: 0)
+ guard openpty(&primary, &replica, nil, nil, &size) == 0 else { throw POSIXError(.EAGAIN) }
+ self.primary = primary
+ self.replica = replica
+ }
+
+ deinit {
+ close(replica)
+ close(primary)
+ }
+
+ /// Reads until `text` has been drawn, giving up after ten seconds.
+ func read(until text: String) {
+ let end = ContinuousClock.now + .seconds(10)
+ while !drawn.contains(text), ContinuousClock.now < end {
+ readMore(waiting: 100)
+ }
+ }
+
+ /// Everything drawn, once nothing more has come for a third of a second.
+ func everything() -> String {
+ while readMore(waiting: 300) {}
+ return drawn
+ }
+
+ @discardableResult
+ private func readMore(waiting milliseconds: Int32) -> Bool {
+ var ready = pollfd(fd: primary, events: Int16(POLLIN), revents: 0)
+ guard poll(&ready, 1, milliseconds) > 0 else { return false }
+ var buffer = [UInt8](repeating: 0, count: 4_096)
+ let count = Darwin.read(primary, &buffer, buffer.count)
+ guard count > 0 else { return false }
+ drawn += String(decoding: buffer[0..<count], as: UTF8.self)
+ return true
+ }
+}
+
+struct ProgressLineTests {
+ private func spaces(_ count: Int) -> String {
+ String(repeating: " ", count: count)
+ }
+
+ @Test func aTerminalIsShownHowFarTheScanHasGotAndTheLineGoesWhenItEnds() async throws {
+ let terminal = try Terminal()
+
+ await ProgressLine.reporting(on: terminal.replica) { show in
+ show("Looked at 3 items")
+ terminal.read(until: "Looked at 3 items")
+ }
+
+ #expect(terminal.everything() == "\rLooked at 3 items" + "\r" + spaces(17) + "\r")
+ }
+
+ @Test func aShorterLineCoversTheLongerOneBeforeIt() async throws {
+ let terminal = try Terminal()
+
+ await ProgressLine.reporting(on: terminal.replica) { show in
+ show("Looking for files: 12345 found")
+ terminal.read(until: "found")
+ show("Comparing files: 1 of 2")
+ terminal.read(until: "1 of 2")
+ }
+
+ let shorter = "\rComparing files: 1 of 2" + spaces(7)
+ #expect(terminal.everything() == "\rLooking for files: 12345 found" + shorter + "\r" + spaces(23) + "\r")
+ }
+
+ @Test func theLineStaysShortOfTheTerminalsLastColumn() async throws {
+ let terminal = try Terminal(columns: 20)
+
+ await ProgressLine.reporting(on: terminal.replica) { show in
+ show("Looked at 12345 items")
+ terminal.read(until: "Looked at 12345 ite")
+ }
+
+ #expect(terminal.everything() == "\rLooked at 12345 ite" + "\r" + spaces(19) + "\r")
+ }
+
+ @Test func aScanSaysHowManyItemsItHasRead() async throws {
+ let folder = try TemporaryDirectory()
+ try folder.file("a")
+ try folder.file("b/c")
+ let terminal = try Terminal()
+
+ await ProgressLine.counting(on: terminal.replica) {
+ _ = await FileSize.contents(of: folder.url)
+ terminal.read(until: "items")
+ }
+
+ #expect(terminal.everything() == "\rLooked at 3 items" + "\r" + spaces(17) + "\r")
+ }
+
+ @Test func aPipeOrAFileGetsNothing() async throws {
+ let directory = try TemporaryDirectory()
+ let file = open(directory.url.appending(path: "notes").path(percentEncoded: false), O_WRONLY | O_CREAT, 0o600)
+ var ends: [Int32] = [0, 0]
+ #expect(pipe(&ends) == 0)
+ let terminal = try Terminal()
+
+ // The terminal's line is drawn last of the three, so by then the others would have been too.
+ await ProgressLine.reporting(on: ends[1]) { toThePipe in
+ await ProgressLine.reporting(on: file) { toTheFile in
+ await ProgressLine.reporting(on: terminal.replica) { toTheTerminal in
+ for show in [toThePipe, toTheFile, toTheTerminal] {
+ show("Looked at 3 items")
+ }
+ terminal.read(until: "Looked at 3 items")
+ }
+ }
+ }
+
+ close(ends[1])
+ close(file)
+ var buffer = [UInt8](repeating: 0, count: 64)
+ #expect(read(ends[0], &buffer, buffer.count) == 0)
+ close(ends[0])
+ let written = try FileManager.default.attributesOfItem(atPath: directory.url.appending(path: "notes").path)
+ #expect(written[.size] as? Int == 0)
+ #expect(terminal.everything().hasPrefix("\rLooked at 3 items"))
+ }
+
+ @Test func countsReadAsTheAppSaysThem() {
+ #expect(ProgressLine.lookedAt(0) == nil)
+ #expect(ProgressLine.lookedAt(1) == "Looked at 1 item")
+ #expect(ProgressLine.lookedAt(12_345) == "Looked at 12345 items")
+ }
+
+ @Test func duplicatesSayWhichStepTheyAreOn() {
+ #expect(DuplicatesCommand.progress(.listing(foldersFound: 1_234)) == "Looking through folders: 1234 found")
+ #expect(DuplicatesCommand.progress(.collecting(filesFound: 12_345)) == "Looking for files: 12345 found")
+ #expect(DuplicatesCommand.progress(.comparing(filesCompared: 120, filesToCompare: 3_400)) == "Comparing files: 120 of 3400")
+ #expect(
+ DuplicatesCommand.progress(.verifying(bytesRead: 1_200_000_000, bytesToRead: 3_400_000_000))
+ == "Reading contents: 1.2 GB of 3.4 GB"
+ )
+ }
+
+ @Test func updatesSayHowManyAppsHaveBeenChecked() {
+ #expect(UpdatesCommand.progress(checked: 12, of: 80) == "Checked 12 of 80 apps")
+ #expect(UpdatesCommand.progress(checked: 1, of: 1) == "Checked 1 of 1 app")
+ }
+}