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.

Write the Shell tab's zsh settings to a file of Peel's own

Țugui Dragoș123309208f0f
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift
new file mode 100644
index 00000000..5b861474
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift
@@ -0,0 +1,79 @@
+public import Foundation
+import PeelPrivileged
+
+/// The zsh file Peel writes the Shell tab's settings into. The shell reads it only through the line the person
+/// adds to their own startup file, so Peel never edits that file, and putting the settings back empties this one.
+public enum ShellFile {
+ static let header = "# Written by Peel. Change it on the Shell tab of the Terminal page in Peel."
+ static let completionSystem = "(( $+functions[compdef] )) || { autoload -Uz compinit && compinit }"
+ private static let maximumBytes = 64 * 1_024
+
+ public static func url(in folder: URL) -> URL {
+ folder.appending(path: "Terminal/zshrc", directoryHint: .notDirectory)
+ }
+
+ public static func contents(of settings: Set<ShellSetting>) -> String {
+ var lines = [header]
+ for setting in ShellSetting.allCases where settings.contains(setting) {
+ if setting.group == .completion, !lines.contains(completionSystem) {
+ lines.append(completionSystem)
+ }
+ lines += setting.lines
+ }
+ return lines.joined(separator: "\n") + "\n"
+ }
+
+ public static func settings(in contents: String) -> Set<ShellSetting> {
+ let lines = Set(contents.split(separator: "\n").map(String.init))
+ return Set(ShellSetting.allCases.filter { $0.lines.allSatisfy(lines.contains) })
+ }
+
+ /// 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>? {
+ if url.isMissing {
+ return []
+ }
+ return BoundedRead.data(at: url, maximum: maximumBytes).map { settings(in: String(decoding: $0, as: UTF8.self)) }
+ }
+
+ public static func write(_ settings: Set<ShellSetting>, 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)
+ return true
+ } catch {
+ return false
+ }
+ }
+
+ public static func line(sourcing url: URL, home: URL) -> String {
+ let path = "\"" + (insideHome(url, home: home).map { "$HOME/" + escaped($0) } ?? escaped(url.path(percentEncoded: false))) + "\""
+ return "[[ -r \(path) ]] && source \(path)"
+ }
+
+ /// Whether a line of `startupFile` that is not a comment names the file, however its spaces are written.
+ public static func isSourced(_ url: URL, from startupFile: URL, home: URL) -> Bool {
+ guard let data = BoundedRead.data(at: startupFile) else { return false }
+ let name = insideHome(url, home: home) ?? url.path(percentEncoded: false)
+ return String(decoding: data, as: UTF8.self).split(separator: "\n").contains { line in
+ let code = line.trimmingCharacters(in: .whitespaces)
+ return !code.hasPrefix("#") && code.replacing("\\ ", with: " ").contains(name)
+ }
+ }
+
+ private static func insideHome(_ url: URL, home: URL) -> String? {
+ let names = PathComponents.of(url.path(percentEncoded: false))
+ let homeNames = PathComponents.of(home.path(percentEncoded: false))
+ guard PathComponents.isPath(url.path(percentEncoded: false), inside: home.path(percentEncoded: false)) else { return nil }
+ return names.dropFirst(homeNames.count).joined(separator: "/")
+ }
+
+ private static func escaped(_ text: String) -> String {
+ text.reduce(into: "") { result, character in
+ if "\"\\`$".contains(character) {
+ result.append("\\")
+ }
+ result.append(character)
+ }
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellSetting.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellSetting.swift
new file mode 100644
index 00000000..e0774ba4
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellSetting.swift
@@ -0,0 +1,63 @@
+public enum ShellSetting: CaseIterable, Sendable {
+ case longHistory
+ case sharedHistory
+ case timedHistory
+ case noRepeats
+ case spaceHides
+ case tidyHistory
+ case verifyRecall
+ case lockedHistory
+ case comments
+ case prefixSearch
+ case pathWords
+ case autoCD
+ case folderStack
+ case completionMenu
+ case anyCase
+ case colorfulLs
+
+ public enum Group: CaseIterable, Sendable {
+ case history, typing, folders, completion, colors
+ }
+
+ public var group: Group {
+ switch self {
+ case .longHistory, .sharedHistory, .timedHistory, .noRepeats, .spaceHides, .tidyHistory, .verifyRecall,
+ .lockedHistory: .history
+ case .comments, .prefixSearch, .pathWords: .typing
+ case .autoCD, .folderStack: .folders
+ case .completionMenu, .anyCase: .completion
+ case .colorfulLs: .colors
+ }
+ }
+
+ public var lines: [String] {
+ switch self {
+ case .longHistory: ["HISTSIZE=50000", "SAVEHIST=50000"]
+ case .sharedHistory: ["setopt SHARE_HISTORY"]
+ case .timedHistory: ["setopt EXTENDED_HISTORY"]
+ case .noRepeats: ["setopt HIST_IGNORE_ALL_DUPS"]
+ case .spaceHides: ["setopt HIST_IGNORE_SPACE"]
+ case .tidyHistory: ["setopt HIST_REDUCE_BLANKS"]
+ case .verifyRecall: ["setopt HIST_VERIFY"]
+ case .lockedHistory: ["setopt HIST_FCNTL_LOCK"]
+ case .comments: ["setopt INTERACTIVE_COMMENTS"]
+ case .prefixSearch:
+ [
+ "autoload -Uz up-line-or-beginning-search down-line-or-beginning-search",
+ "zle -N up-line-or-beginning-search",
+ "zle -N down-line-or-beginning-search",
+ "bindkey '^[[A' up-line-or-beginning-search",
+ "bindkey '^[OA' up-line-or-beginning-search",
+ "bindkey '^[[B' down-line-or-beginning-search",
+ "bindkey '^[OB' down-line-or-beginning-search",
+ ]
+ case .pathWords: ["WORDCHARS=${WORDCHARS//[\\/]}"]
+ case .autoCD: ["setopt AUTO_CD"]
+ case .folderStack: ["setopt AUTO_PUSHD PUSHD_IGNORE_DUPS"]
+ case .completionMenu: ["zstyle ':completion:*' menu select"]
+ case .anyCase: ["zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'"]
+ case .colorfulLs: ["export CLICOLOR=1"]
+ }
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ProgressLineTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ProgressLineTests.swift
index bdf07034..75ae6429 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/ProgressLineTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ProgressLineTests.swift
@@ -4,60 +4,13 @@ import Foundation
@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()
+ let terminal = try PseudoTerminal()
await ProgressLine.reporting(on: terminal.replica) { show in
show("Looked at 3 items")
@@ -68,7 +21,7 @@ struct ProgressLineTests {
}
@Test func aShorterLineCoversTheLongerOneBeforeIt() async throws {
- let terminal = try Terminal()
+ let terminal = try PseudoTerminal()
await ProgressLine.reporting(on: terminal.replica) { show in
show("Looking for files: 12345 found")
@@ -82,7 +35,7 @@ struct ProgressLineTests {
}
@Test func theLineStaysShortOfTheTerminalsLastColumn() async throws {
- let terminal = try Terminal(columns: 20)
+ let terminal = try PseudoTerminal(columns: 20)
await ProgressLine.reporting(on: terminal.replica) { show in
show("Looked at 12345 items")
@@ -96,7 +49,7 @@ struct ProgressLineTests {
let folder = try TemporaryDirectory()
try folder.file("a")
try folder.file("b/c")
- let terminal = try Terminal()
+ let terminal = try PseudoTerminal()
await ProgressLine.counting(on: terminal.replica) {
_ = await FileSize.contents(of: folder.url)
@@ -111,7 +64,7 @@ struct ProgressLineTests {
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()
+ let terminal = try PseudoTerminal()
// 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
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PseudoTerminal.swift b/Packages/PeelCore/Tests/PeelCoreTests/PseudoTerminal.swift
new file mode 100644
index 00000000..90d5a8c9
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/PseudoTerminal.swift
@@ -0,0 +1,53 @@
+import Darwin
+import Foundation
+
+/// A pseudo terminal, the kind a Terminal window is: what a program writes on its replica is read here as the window
+/// would draw it, and what is typed reaches the program as keys.
+final class PseudoTerminal {
+ 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)
+ }
+
+ func type(_ text: String) {
+ _ = text.utf8CString.withUnsafeBufferPointer { Darwin.write(primary, $0.baseAddress, $0.count - 1) }
+ }
+
+ /// 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
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift
new file mode 100644
index 00000000..e15f0987
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift
@@ -0,0 +1,160 @@
+import Darwin
+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 ))",
+ .sharedHistory: "[[ -o sharehistory ]]",
+ .timedHistory: "[[ -o extendedhistory ]]",
+ .noRepeats: "[[ -o histignorealldups ]]",
+ .spaceHides: "[[ -o histignorespace ]]",
+ .tidyHistory: "[[ -o histreduceblanks ]]",
+ .verifyRecall: "[[ -o histverify ]]",
+ .lockedHistory: "[[ -o histfcntllock ]]",
+ .comments: "[[ -o interactivecomments ]]",
+ .prefixSearch: """
+ [[ $(bindkey '^[[A') == *' up-line-or-beginning-search' && $(bindkey '^[OA') == *' up-line-or-beginning-search' \
+ && $(bindkey '^[[B') == *' down-line-or-beginning-search' && $(bindkey '^[OB') == *' down-line-or-beginning-search' ]]
+ """,
+ .pathWords: "[[ $WORDCHARS != */* ]]",
+ .autoCD: "[[ -o autocd ]]",
+ .folderStack: "[[ -o autopushd && -o pushdignoredups ]]",
+ .completionMenu: "(( $+functions[compdef] )) && [[ $(zstyle -L ':completion:*' menu) == *' menu select' ]]",
+ .anyCase: "(( $+functions[compdef] )) && [[ $(zstyle -L ':completion:*' matcher-list) == *\"'m:{a-zA-Z}={A-Za-z}'\" ]]",
+ .colorfulLs: "[[ ${(t)CLICOLOR} == *export* && $CLICOLOR == 1 ]]",
+ ]
+
+ @Test func everySettingIsInEffectInANewShellOnceItIsOnAndNotBefore() throws {
+ let shell = try ZshHome()
+ #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(try shell.answers(check) == false, "\(setting)")
+ #expect(ShellFile.write([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))
+ 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))
+ 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()
+ let process = Process()
+ process.executableURL = URL(filePath: "/bin/zsh")
+ process.arguments = ["-i"]
+ process.environment = shell.environment
+ let replica = FileHandle(fileDescriptor: terminal.replica, closeOnDealloc: false)
+ process.standardInput = replica
+ process.standardOutput = replica
+ process.standardError = replica
+ try process.run()
+ terminal.read(until: "ready> ")
+ terminal.type("echo al" + up + "\r")
+ terminal.read(until: "\r\nalpha")
+ terminal.type("exit\r")
+ _ = terminal.everything()
+ if process.isRunning {
+ kill(process.processIdentifier, SIGKILL)
+ }
+ process.waitUntilExit()
+ #expect(terminal.drawn.contains("\r\nalpha\r\n"), "\(up.debugDescription): \(terminal.drawn.debugDescription)")
+ #expect(!terminal.drawn.contains("\r\nbeta\r\n"), "\(up.debugDescription)")
+ }
+ }
+
+ @Test func theFileReadsBackAsTheSettingsWrittenInIt() {
+ for setting in ShellSetting.allCases {
+ #expect(ShellFile.settings(in: ShellFile.contents(of: [setting])) == [setting])
+ }
+ #expect(ShellFile.settings(in: ShellFile.contents(of: Set(ShellSetting.allCases))) == Set(ShellSetting.allCases))
+ #expect(ShellFile.settings(in: ShellFile.contents(of: [])).isEmpty)
+ }
+
+ @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) == [])
+ try FileManager.default.createDirectory(at: file, withIntermediateDirectories: true)
+ #expect(ShellFile.read(file) == nil)
+ }
+
+ @Test func writingReplacesALinkInsteadOfWritingWhereItLeads() throws {
+ let folder = FileManager.default.temporaryDirectory.appending(path: "ShellFileTests-\(UUID().uuidString)", directoryHint: .isDirectory)
+ let file = ShellFile.url(in: folder)
+ let theirs = folder.appending(path: "theirs")
+ 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(try String(contentsOf: theirs, encoding: .utf8) == "theirs\n")
+ #expect(try file.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == false)
+ #expect(ShellFile.read(file) == [.comments])
+ }
+
+ @Test func theLineIsFoundInTheStartupFileUnlessItIsACommentOrSpelledAnotherWay() throws {
+ let shell = try ZshHome()
+ let startup = shell.home.appending(path: ".zshrc")
+ #expect(ShellFile.line(sourcing: shell.peelFile, home: shell.home)
+ == "[[ -r \"$HOME/Library/Application Support/Peel/Terminal/zshrc\" ]] && source \"$HOME/Library/Application Support/Peel/Terminal/zshrc\"")
+ #expect(ShellFile.isSourced(shell.peelFile, from: startup, home: shell.home))
+ for (text, found) in [
+ ("source ~/Library/Application\\ Support/Peel/Terminal/zshrc\n", true),
+ ("export PATH=/opt/homebrew/bin:$PATH\n . \"$HOME/Library/Application Support/Peel/Terminal/zshrc\"\n", true),
+ ("# " + ShellFile.line(sourcing: shell.peelFile, home: shell.home) + "\n", false),
+ ("setopt AUTO_CD\n", false),
+ ] {
+ try text.write(to: startup, atomically: true, encoding: .utf8)
+ #expect(ShellFile.isSourced(shell.peelFile, from: startup, home: shell.home) == found, "\(text)")
+ }
+ try FileManager.default.removeItem(at: startup)
+ #expect(!ShellFile.isSourced(shell.peelFile, from: startup, home: shell.home))
+ }
+}