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.

Let the Shell tab choose a prompt, or keep macOS's own

Țugui Dragoș77714020d440
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/PromptStyle.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/PromptStyle.swift
new file mode 100644
index 00000000..51b58c8a
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/PromptStyle.swift
@@ -0,0 +1,63 @@
+import Darwin
+
+public enum PromptStyle: CaseIterable, Sendable {
+ case macOS
+ case arrow
+ case arrowAndBranch
+ case twoLines
+ case folderOnly
+ case classic
+
+ /// A run of the prompt's text in one of the 16 colors a Terminal theme sets, or in its text color when nil.
+ public struct Segment: Equatable, Sendable {
+ public let text: String
+ public let color: Int?
+
+ public init(_ text: String, _ color: Int? = nil) {
+ self.text = text
+ self.color = color
+ }
+ }
+
+ static let branchLines = [
+ "autoload -Uz vcs_info add-zsh-hook",
+ "zstyle ':vcs_info:*' enable git",
+ "zstyle ':vcs_info:git:*' formats ' %F{yellow}%b%f'",
+ "zstyle ':vcs_info:git:*' actionformats ' %F{yellow}%b%f %F{red}%a%f'",
+ "add-zsh-hook precmd vcs_info",
+ "setopt PROMPT_SUBST",
+ ]
+
+ public var lines: [String] {
+ switch self {
+ case .macOS: []
+ case .arrow: ["PROMPT='%F{cyan}%~%f %(?.%F{green}.%F{red})❯%f '"]
+ case .arrowAndBranch: Self.branchLines + ["PROMPT='%F{cyan}%~%f${vcs_info_msg_0_} %(?.%F{green}.%F{red})❯%f '"]
+ case .twoLines: Self.branchLines + ["PROMPT=$'%F{cyan}%~%f${vcs_info_msg_0_}\\n%(?.%F{green}.%F{red})❯%f '"]
+ case .folderOnly: ["PROMPT='%F{cyan}%1~%f %(?.%F{green}.%F{red})❯%f '"]
+ case .classic: ["PROMPT='%F{green}%n@%m%f %F{blue}%~%f %# '"]
+ }
+ }
+
+ /// How the prompt reads in `path`, written from the home folder as `~/…`, after a command that `failed` or not.
+ public func sample(user: String, host: String, path: String, branch: String?, failed: Bool) -> [Segment] {
+ let folder = path == "~" ? path : String(path.split(separator: "/").last ?? "")
+ let mark = Segment("❯", failed ? 1 : 2)
+ let onBranch = branch.map { [Segment(" "), Segment($0, 3)] } ?? []
+ switch self {
+ case .macOS: return [Segment("\(user)@\(host) \(folder) % ")]
+ case .arrow: return [Segment(path, 6), Segment(" "), mark, Segment(" ")]
+ case .arrowAndBranch: return [Segment(path, 6)] + onBranch + [Segment(" "), mark, Segment(" ")]
+ case .twoLines: return [Segment(path, 6)] + onBranch + [Segment("\n"), mark, Segment(" ")]
+ case .folderOnly: return [Segment(folder, 6), Segment(" "), mark, Segment(" ")]
+ case .classic: return [Segment("\(user)@\(host)", 2), Segment(" "), Segment(path, 4), Segment(" % ")]
+ }
+ }
+
+ /// The computer's name as zsh's `%m` shows it: up to the first dot.
+ public static func hostName() -> String {
+ var name = [CChar](repeating: 0, count: Int(MAXHOSTNAMELEN) + 1)
+ guard gethostname(&name, name.count - 1) == 0 else { return "" }
+ return String(String(cString: name).prefix { $0 != "." })
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift
index 5b861474..53acabad 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift
@@ -8,38 +8,53 @@ public enum ShellFile {
static let completionSystem = "(( $+functions[compdef] )) || { autoload -Uz compinit && compinit }"
private static let maximumBytes = 64 * 1_024
+ public struct Choices: Equatable, Sendable {
+ public var settings: Set<ShellSetting>
+ public var prompt: PromptStyle
+
+ public init(settings: Set<ShellSetting> = [], prompt: PromptStyle = .macOS) {
+ self.settings = settings
+ self.prompt = prompt
+ }
+ }
+
public static func url(in folder: URL) -> URL {
folder.appending(path: "Terminal/zshrc", directoryHint: .notDirectory)
}
- public static func contents(of settings: Set<ShellSetting>) -> String {
+ public static func contents(of choices: Choices) -> String {
var lines = [header]
- for setting in ShellSetting.allCases where settings.contains(setting) {
+ for setting in ShellSetting.allCases where choices.settings.contains(setting) {
if setting.group == .completion, !lines.contains(completionSystem) {
lines.append(completionSystem)
}
lines += setting.lines
}
+ lines += choices.prompt.lines
return lines.joined(separator: "\n") + "\n"
}
- public static func settings(in contents: String) -> Set<ShellSetting> {
+ public static func choices(in contents: String) -> Choices {
let lines = Set(contents.split(separator: "\n").map(String.init))
- return Set(ShellSetting.allCases.filter { $0.lines.allSatisfy(lines.contains) })
+ let isIn: (Set<String>) -> Bool = { $0.isSubset(of: lines) }
+ return Choices(
+ settings: Set(ShellSetting.allCases.filter { isIn(Set($0.lines)) }),
+ prompt: PromptStyle.allCases.first { !$0.lines.isEmpty && isIn(Set($0.lines)) } ?? .macOS
+ )
}
- /// The settings in the file, none when it is not there, and nil when it is there and cannot be read.
- public static func read(_ url: URL) -> Set<ShellSetting>? {
+ /// The choices in the file, none when it is not there, and nil when it is there and cannot be read.
+ public static func read(_ url: URL) -> Choices? {
if url.isMissing {
- return []
+ return Choices()
}
- return BoundedRead.data(at: url, maximum: maximumBytes).map { settings(in: String(decoding: $0, as: UTF8.self)) }
+ return BoundedRead.data(at: url, maximum: maximumBytes).map { choices(in: String(decoding: $0, as: UTF8.self)) }
}
- public static func write(_ settings: Set<ShellSetting>, to url: URL) -> Bool {
+ public static func write(_ choices: Choices, to url: URL) -> Bool {
do {
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
- try Data(contents(of: settings).utf8).write(to: url, options: .atomic)
+ try Data(contents(of: choices).utf8).write(to: url, options: .atomic)
return true
} catch {
return false
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PromptStyleTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PromptStyleTests.swift
new file mode 100644
index 00000000..d6edbc44
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/PromptStyleTests.swift
@@ -0,0 +1,57 @@
+import Foundation
+@testable import PeelCore
+import Testing
+
+struct PromptStyleTests {
+ @Test func everyStyleShowsInZshAsItsSampleAfterACommandThatWorkedAndOneThatFailed() throws {
+ let shell = try ZshHome()
+ let project = shell.home.appending(path: "Projects/peel", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: project, withIntermediateDirectories: true)
+ let git = Process()
+ git.executableURL = URL(filePath: "/usr/bin/git")
+ git.arguments = ["init", "-q", "-b", "main", project.path]
+ git.environment = shell.environment
+ try git.run()
+ git.waitUntilExit()
+ #expect(git.terminationStatus == 0)
+ for style in PromptStyle.allCases {
+ #expect(ShellFile.write(.init(prompt: style), to: shell.peelFile))
+ for failed in [false, true] {
+ let shown = try shell.output(
+ of: "cd ~/Projects/peel; (( $+functions[vcs_info] )) && vcs_info; \(failed ? "false" : "true"); print -rnP -- \"${(e)PROMPT}\""
+ )
+ let sample = style.sample(user: NSUserName(), host: PromptStyle.hostName(), path: "~/Projects/peel", branch: "main", failed: failed)
+ #expect(Self.merged(Self.segments(in: shown)) == Self.merged(sample), "\(style), failed: \(failed), shown: \(shown.debugDescription)")
+ }
+ }
+ }
+
+ static func segments(in text: String) -> [PromptStyle.Segment] {
+ var segments: [PromptStyle.Segment] = []
+ var color: Int?
+ var rest = Substring(text)
+ while !rest.isEmpty {
+ if rest.hasPrefix("\u{1B}["), let end = rest.firstIndex(of: "m") {
+ let code = Int(rest[rest.index(rest.startIndex, offsetBy: 2)..<end]) ?? 0
+ color = (30...37).contains(code) ? code - 30 : (90...97).contains(code) ? code - 82 : nil
+ rest = rest[rest.index(after: end)...]
+ } else {
+ let next = rest.dropFirst().firstIndex(of: "\u{1B}") ?? rest.endIndex
+ segments.append(PromptStyle.Segment(String(rest[..<next]), color))
+ rest = rest[next...]
+ }
+ }
+ return segments
+ }
+
+ static func merged(_ segments: [PromptStyle.Segment]) -> [PromptStyle.Segment] {
+ segments.reduce(into: []) { result, segment in
+ guard !segment.text.isEmpty else { return }
+ if let last = result.last, last.color == segment.color {
+ result[result.count - 1] = PromptStyle.Segment(last.text + segment.text, last.color)
+ } else {
+ result.append(segment)
+ }
+ }
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift
index e15f0987..dc1006eb 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift
@@ -3,42 +3,6 @@ import Foundation
@testable import PeelCore
import Testing
-/// A made-up home whose `.zshrc` sources Peel's file, the way a person's does once they add Peel's line.
-private struct ZshHome {
- let home: URL
- let peelFile: URL
-
- init() throws {
- home = FileManager.default.temporaryDirectory.appending(path: "ShellFileTests-\(UUID().uuidString)", directoryHint: .isDirectory)
- peelFile = ShellFile.url(in: home.appending(path: "Library/Application Support/Peel", directoryHint: .isDirectory))
- try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
- try (ShellFile.line(sourcing: peelFile, home: home) + "\nPS1='ready> '\n")
- .write(to: home.appending(path: ".zshrc"), atomically: true, encoding: .utf8)
- }
-
- var environment: [String: String] {
- ["HOME": home.path, "ZDOTDIR": home.path, "TERM": "xterm-256color", "PATH": "/usr/bin:/bin"]
- }
-
- /// Whether `check` holds in a new interactive zsh, which also has to start without a single error.
- func answers(_ check: String) throws -> Bool {
- let process = Process()
- process.executableURL = URL(filePath: "/bin/zsh")
- process.arguments = ["-i", "-c", "if \(check); then print yes; else print no; fi"]
- process.environment = environment
- let output = Pipe()
- let errors = Pipe()
- process.standardOutput = output
- process.standardError = errors
- try process.run()
- let said = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
- let complained = String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
- process.waitUntilExit()
- #expect(complained.isEmpty, "\(complained)")
- return said == "yes\n"
- }
-}
-
struct ShellFileTests {
static let inEffect: [ShellSetting: String] = [
.longHistory: "(( HISTSIZE == 50000 && SAVEHIST == 50000 ))",
@@ -67,23 +31,23 @@ struct ShellFileTests {
#expect(Set(Self.inEffect.keys) == Set(ShellSetting.allCases))
for setting in ShellSetting.allCases {
let check = try #require(Self.inEffect[setting])
- #expect(ShellFile.write([], to: shell.peelFile))
+ #expect(ShellFile.write(.init(), to: shell.peelFile))
#expect(try shell.answers(check) == false, "\(setting)")
- #expect(ShellFile.write([setting], to: shell.peelFile))
+ #expect(ShellFile.write(.init(settings: [setting]), to: shell.peelFile))
#expect(try shell.answers(check) == true, "\(setting)")
}
}
@Test func everySettingAtOnceIsInEffectWithoutAnError() throws {
let shell = try ZshHome()
- #expect(ShellFile.write(Set(ShellSetting.allCases), to: shell.peelFile))
+ #expect(ShellFile.write(.init(settings: Set(ShellSetting.allCases)), to: shell.peelFile))
let all = ShellSetting.allCases.compactMap { Self.inEffect[$0] }.map { "{ \($0) }" }.joined(separator: " && ")
#expect(try shell.answers(all))
}
@Test func upAndDownFindTheCommandsThatStartWithWhatWasTyped() throws {
- let shell = try ZshHome()
- #expect(ShellFile.write([.prefixSearch], to: shell.peelFile))
+ let shell = try ZshHome(thenRun: ["PS1='ready> '"])
+ #expect(ShellFile.write(.init(settings: [.prefixSearch]), to: shell.peelFile))
for up in ["\u{1B}[A", "\u{1B}OA"] {
try "echo alpha\necho beta\n".write(to: shell.home.appending(path: ".zsh_history"), atomically: true, encoding: .utf8)
let terminal = try PseudoTerminal()
@@ -110,18 +74,22 @@ struct ShellFileTests {
}
}
- @Test func theFileReadsBackAsTheSettingsWrittenInIt() {
+ @Test func theFileReadsBackAsTheChoicesWrittenInIt() {
for setting in ShellSetting.allCases {
- #expect(ShellFile.settings(in: ShellFile.contents(of: [setting])) == [setting])
+ let choices = ShellFile.Choices(settings: [setting])
+ #expect(ShellFile.choices(in: ShellFile.contents(of: choices)) == choices)
+ }
+ for prompt in PromptStyle.allCases {
+ let choices = ShellFile.Choices(settings: Set(ShellSetting.allCases), prompt: prompt)
+ #expect(ShellFile.choices(in: ShellFile.contents(of: choices)) == choices)
}
- #expect(ShellFile.settings(in: ShellFile.contents(of: Set(ShellSetting.allCases))) == Set(ShellSetting.allCases))
- #expect(ShellFile.settings(in: ShellFile.contents(of: [])).isEmpty)
+ #expect(ShellFile.choices(in: ShellFile.contents(of: .init())) == .init())
}
@Test func aMissingFileHasNothingOnAndOneThatCannotBeReadIsNotKnown() throws {
let folder = FileManager.default.temporaryDirectory.appending(path: "ShellFileTests-\(UUID().uuidString)", directoryHint: .isDirectory)
let file = ShellFile.url(in: folder)
- #expect(ShellFile.read(file) == [])
+ #expect(ShellFile.read(file) == .init())
try FileManager.default.createDirectory(at: file, withIntermediateDirectories: true)
#expect(ShellFile.read(file) == nil)
}
@@ -133,10 +101,10 @@ struct ShellFileTests {
try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
try "theirs\n".write(to: theirs, atomically: true, encoding: .utf8)
try FileManager.default.createSymbolicLink(at: file, withDestinationURL: theirs)
- #expect(ShellFile.write([.comments], to: file))
+ #expect(ShellFile.write(.init(settings: [.comments]), to: file))
#expect(try String(contentsOf: theirs, encoding: .utf8) == "theirs\n")
#expect(try file.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == false)
- #expect(ShellFile.read(file) == [.comments])
+ #expect(ShellFile.read(file) == .init(settings: [.comments]))
}
@Test func theLineIsFoundInTheStartupFileUnlessItIsACommentOrSpelledAnotherWay() throws {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ZshHome.swift b/Packages/PeelCore/Tests/PeelCoreTests/ZshHome.swift
new file mode 100644
index 00000000..3b67cfa0
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ZshHome.swift
@@ -0,0 +1,46 @@
+import Foundation
+@testable import PeelCore
+import Testing
+
+/// A made-up home whose `.zshrc` sources Peel's file, the way a person's does once they add Peel's line.
+struct ZshHome {
+ let home: URL
+ let peelFile: URL
+
+ init(thenRun lines: [String] = []) throws {
+ home = FileManager.default.temporaryDirectory.appending(path: "ZshHome-\(UUID().uuidString)", directoryHint: .isDirectory)
+ peelFile = ShellFile.url(in: home.appending(path: "Library/Application Support/Peel", directoryHint: .isDirectory))
+ try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
+ try ([ShellFile.line(sourcing: peelFile, home: home)] + lines).joined(separator: "\n").appending("\n")
+ .write(to: home.appending(path: ".zshrc"), atomically: true, encoding: .utf8)
+ }
+
+ var environment: [String: String] {
+ [
+ "HOME": home.path, "ZDOTDIR": home.path, "TERM": "xterm-256color", "PATH": "/usr/bin:/bin",
+ "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": "/dev/null",
+ ]
+ }
+
+ /// What a new interactive zsh prints for `command`. It has to start and run without a single error.
+ func output(of command: String) throws -> String {
+ let process = Process()
+ process.executableURL = URL(filePath: "/bin/zsh")
+ process.arguments = ["-i", "-c", command]
+ process.environment = environment
+ let output = Pipe()
+ let errors = Pipe()
+ process.standardOutput = output
+ process.standardError = errors
+ try process.run()
+ let said = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
+ let complained = String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
+ process.waitUntilExit()
+ #expect(complained.isEmpty, "\(complained)")
+ return said
+ }
+
+ func answers(_ check: String) throws -> Bool {
+ try output(of: "if \(check); then print yes; else print no; fi") == "yes\n"
+ }
+}