Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
Start Peel's line in ~/.zshrc on a line of its own
Țugui Dragoș48429cf84617
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/PathBelowHome.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/PathBelowHome.swiftindex 6c7565a5..20415ffd 100644--- a/Packages/PeelCore/Sources/PeelCore/Terminal/PathBelowHome.swift+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/PathBelowHome.swift@@ -27,3 +27,13 @@ extension String {"'" + replacing("'", with: "'\\''") + "'"}}++enum ShellCommand {+ /// The command that adds `lines` at the end of `file`, each on a line of its own, and makes the file when it is+ /// not there. An empty line goes first: a file whose last line has no newline after it would otherwise run into+ /// the first of `lines`, and the shell would read the two as one.+ static func appending(_ lines: [String], to file: URL, home: URL) -> String {+ let arguments = ([""] + lines).map(\.quotedForTheShell).joined(separator: " ")+ return "printf '%s\\n' \(arguments) >> \(file.pathForTheShell(home: home))"+ }+}diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/SSHFile.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/SSHFile.swiftindex b6e5b84c..df003e6d 100644--- a/Packages/PeelCore/Sources/PeelCore/Terminal/SSHFile.swift+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/SSHFile.swift@@ -74,12 +74,11 @@ public enum SSHFile {return ["Match all", " Include \"\(path.replacing("\\", with: "\\\\").replacing("\"", with: "\\\""))\""]}- /// The command that adds `lines` at the end of `config`, after an empty line, making the folder it is in, closed- /// to everyone else as ssh wants it, and the file itself when they are not there.+ /// The command that adds `lines` at the end of `config`, making the folder it is in, closed to everyone else as+ /// ssh wants it, and the file itself when they are not there.public static func command(adding lines: [String], to config: URL, home: URL) -> String {let folder = config.deletingLastPathComponent().pathForTheShell(home: home)- let arguments = ([""] + lines).map(\.quotedForTheShell).joined(separator: " ")- return "mkdir -p -m 700 \(folder) && printf '%s\\n' \(arguments) >> \(config.pathForTheShell(home: home))"+ return "mkdir -p -m 700 \(folder) && " + ShellCommand.appending(lines, to: config, home: home)}/// Whether an `Include` line of `config` names the file, however its spaces are written.diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swiftindex 42397f08..3364a219 100644--- a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift@@ -70,28 +70,45 @@ public enum ShellFile {/// The command that adds `line` at the end of `startupFile`, which it makes when there is none.public static func command(adding line: String, to startupFile: URL, home: URL) -> String {- "printf '%s\\n' \(line.quotedForTheShell) >> \(startupFile.pathForTheShell(home: home))"+ ShellCommand.appending([line], to: startupFile, home: home)}- /// Whether a line of `startupFile` that is not a comment names the file, however its spaces are written.+ /// Whether a line of `startupFile` reads the file.public static func isSourced(_ url: URL, from startupFile: URL, home: URL) -> Bool {guard let data = BoundedRead.data(at: startupFile) else { return false }- let name = url.path(below: 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)+ return String(decoding: data, as: UTF8.self).split(separator: "\n")+ .contains { sources(String($0), url, home: home) }+ }++ /// Whether `line` reads the file: `source` or `.` with the file's path as its argument, written from `$HOME`,+ /// `${HOME}` or `~`, or whole, in quotes or not, its spaces escaped or not, and not in a comment. Peel's own line+ /// tests the file first, `[[ -r … ]] && source …`, and counts only when that test starts a command: run into the+ /// line before it, as happened in a file whose last line had no newline, zsh fails on the line and never reaches+ /// the `source`.+ static func sources(_ line: String, _ url: URL, home: URL) -> Bool {+ let code = line.trimmingCharacters(in: .whitespaces).replacing("\\ ", with: " ")+ guard !code.hasPrefix("#") else { return false }+ let escaped = NSRegularExpression.escapedPattern(for:)+ let whole = "[\"']?" + escaped(url.path(percentEncoded: false)) + "[\"']?"+ let fromHome = url.path(below: home).map { below in+ "\"?(?:\\$HOME|\\$\\{HOME\\}|~)/" + escaped(below) + "\"?"}+ let path = "(?:" + ([fromHome, whole].compactMap { $0 }).joined(separator: "|") + ")"+ let start = #"(?:^|[\s;&|(){])"#+ let test = #"\[\[\s+-r\s+"# + path + #"\s+\]\]\s*&&\s*"#+ let reads = #"(?:source|\.)\s+"# + path + #"(?:$|[\s;&|)}#])"#+ let contains = { (pattern: String) in (try? Regex(pattern)).map { code.contains($0) } ?? false }+ return contains(test) ? contains(start + test + reads) : contains(start + reads)}/// Whether `startupFile` sets the prompt after the line that reads Peel's file, so zsh shows that one instead.public static func setsItsOwnPrompt(after url: URL, in startupFile: URL, home: URL) -> Bool {guard let data = BoundedRead.data(at: startupFile) else { return false }- let name = url.path(below: home) ?? url.path(percentEncoded: false)- let code = String(decoding: data, as: UTF8.self).split(separator: "\n")- .map { $0.trimmingCharacters(in: .whitespaces) }- .filter { !$0.hasPrefix("#") }- guard let peels = code.firstIndex(where: { $0.replacing("\\ ", with: " ").contains(name) }) else { return false }- return code[(peels + 1)...].contains { $0.contains(/^(?:(?:export|typeset(?:\s+-g)?)\s+)?(?:PROMPT|PS1)=/) }+ let lines = String(decoding: data, as: UTF8.self).split(separator: "\n").map(String.init)+ guard let peels = lines.firstIndex(where: { sources($0, url, home: home) }) else { return false }+ return lines[(peels + 1)...].contains {+ $0.trimmingCharacters(in: .whitespaces).contains(/^(?:(?:export|typeset(?:\s+-g)?)\s+)?(?:PROMPT|PS1)=/)+ }}private static func escaped(_ text: String) -> String {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swiftindex a6deee53..6d275676 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ShellFileTests.swift@@ -114,11 +114,17 @@ struct ShellFileTests {#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))+ let line = ShellFile.line(sourcing: shell.peelFile, 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),+ ("source \"${HOME}/Library/Application Support/Peel/Terminal/zshrc\" # Peel\n", true),+ ("source '\(shell.peelFile.path(percentEncoded: false))'\n", true),+ ("# " + line + "\n", false),("setopt AUTO_CD\n", false),+ ("export PATH=/opt/homebrew/bin:$PATH" + line + "\n", false),+ ("alias peelrc='open ~/Library/Application Support/Peel/Terminal/zshrc'\n", false),+ ("echo ~/Library/Application\\ Support/Peel/Terminal/zshrc\n", false),] {try text.write(to: startup, atomically: true, encoding: .utf8)#expect(ShellFile.isSourced(shell.peelFile, from: startup, home: shell.home) == found, "\(text)")@@ -183,11 +189,31 @@ struct PeelLinesCommandTests {let command = ShellFile.command(adding: line, to: zshrc, home: home)#expect(command.hasSuffix(" >> ~/.zshrc"))#expect(try await run(command, home: home) == 0)- #expect(try String(contentsOf: zshrc, encoding: .utf8) == line + "\n")+ #expect(try String(contentsOf: zshrc, encoding: .utf8) == "\n" + line + "\n")#expect(ShellFile.isSourced(file, from: zshrc, home: home))try "setopt AUTO_CD\n".write(to: zshrc, atomically: true, encoding: .utf8)#expect(try await run(command, home: home) == 0)- #expect(try String(contentsOf: zshrc, encoding: .utf8) == "setopt AUTO_CD\n" + line + "\n")+ #expect(try String(contentsOf: zshrc, encoding: .utf8) == "setopt AUTO_CD\n\n" + line + "\n")+ }++ @Test func theShellsCommandKeepsTheLastLineOfAZshrcThatEndsWithoutANewline() async throws {+ let home = try madeUpHome()+ let file = ShellFile.url(in: home.appending(path: "Library/Application Support/Peel", directoryHint: .isDirectory))+ let zshrc = home.appending(path: ".zshrc")+ #expect(ShellFile.write(.init(settings: [.autoCD]), to: file))+ try Data("export PEEL_PROBE=1".utf8).write(to: zshrc)+ let line = ShellFile.line(sourcing: file, home: home)+ #expect(try await run(ShellFile.command(adding: line, to: zshrc, home: home), home: home) == 0)+ let answer = await Subprocess.run(+ "/bin/zsh",+ ["-i", "-c", "print -r -- $PEEL_PROBE; [[ -o autocd ]] && print on"],+ environment: ["HOME": home.path(percentEncoded: false), "ZDOTDIR": home.path(percentEncoded: false), "TERM": "xterm", "PATH": "/usr/bin:/bin"],+ timeout: 10+ )+ guard case .success(let output) = answer else { throw POSIXError(.EIO) }+ #expect(output.errorText.isEmpty, "\(output.errorText)")+ #expect(output.text == "1\non\n")+ #expect(ShellFile.isSourced(file, from: zshrc, home: home))}@Test func theSSHCommandMakesAClosedFolderAndAddsTheLinesPeelFinds() async throws {