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 SSH tab set ssh options in a file of Peel's own

Țugui Dragoșdb14c5be9e0a
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/PathBelowHome.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/PathBelowHome.swift
new file mode 100644
index 00000000..94827987
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/PathBelowHome.swift
@@ -0,0 +1,12 @@
+import Foundation
+import PeelPrivileged
+
+extension URL {
+ /// The path from `home` down to this item, or nil when the item is not inside `home`.
+ func path(below home: URL) -> String? {
+ let names = PathComponents.of(path(percentEncoded: false))
+ let homeNames = PathComponents.of(home.path(percentEncoded: false))
+ guard names.count > homeNames.count, names.starts(with: homeNames) else { return nil }
+ return names.dropFirst(homeNames.count).joined(separator: "/")
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/SSHFile.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/SSHFile.swift
new file mode 100644
index 00000000..4caca9a8
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/SSHFile.swift
@@ -0,0 +1,71 @@
+public import Foundation
+import PeelPrivileged
+
+/// The SSH settings file Peel writes the SSH tab's settings into. ssh reads it only through the lines the person
+/// adds at the end of `~/.ssh/config`, and since ssh keeps the first value it finds for each option, what the
+/// person set for a server earlier in that file stays in force.
+public enum SSHFile {
+ static let header = "# Written by Peel. Change it on the SSH tab of the Terminal page in Peel."
+ private static let maximumBytes = 64 * 1_024
+
+ public static func url(in folder: URL) -> URL {
+ folder.appending(path: "Terminal/ssh_config", directoryHint: .notDirectory)
+ }
+
+ public static func contents(of settings: Set<SSHSetting>) -> String {
+ ([header] + SSHSetting.allCases.filter(settings.contains).flatMap(\.lines)).joined(separator: "\n") + "\n"
+ }
+
+ public static func settings(in contents: String) -> Set<SSHSetting> {
+ let lines = Set(contents.split(separator: "\n").map(String.init))
+ return Set(SSHSetting.allCases.filter { Set($0.lines).isSubset(of: lines) })
+ }
+
+ /// 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<SSHSetting>? {
+ 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<SSHSetting>, 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
+ }
+ }
+
+ /// The lines that make ssh read the file. `Match all` first, so they apply to every server even after a `Host`
+ /// block, where an `Include` alone would apply only to that block's servers.
+ public static func lines(including url: URL, home: URL) -> [String] {
+ let path = url.path(below: home).map { "~/" + $0 } ?? url.path(percentEncoded: false)
+ return ["Match all", " Include \"\(path.replacing("\\", with: "\\\\").replacing("\"", with: "\\\""))\""]
+ }
+
+ /// Whether an `Include` line of `config` names the file, however its spaces are written.
+ public static func isIncluded(_ url: URL, from config: URL, home: URL) -> Bool {
+ guard let data = BoundedRead.data(at: config) 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.lowercased().hasPrefix("include") && code.replacing("\\ ", with: " ").contains(name)
+ }
+ }
+
+ /// The settings the ssh on this Mac accepts, asked on its command line so nothing is written to try them.
+ public static func accepted() async -> Set<SSHSetting> {
+ var accepted: Set<SSHSetting> = []
+ for setting in SSHSetting.allCases {
+ let options = setting.lines.flatMap { ["-o", $0] }
+ let answer = await Subprocess.run("/usr/bin/ssh", ["-G", "-F", "/dev/null"] + options + ["peel.invalid"], environment: [:], timeout: 10)
+ if case .success(let output) = answer, output.status == 0 {
+ accepted.insert(setting)
+ }
+ }
+ return accepted
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/SSHSetting.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/SSHSetting.swift
new file mode 100644
index 00000000..9d4694b8
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/SSHSetting.swift
@@ -0,0 +1,13 @@
+public enum SSHSetting: CaseIterable, Sendable {
+ case keychain
+ case keepAlive
+ case reuseConnections
+
+ public var lines: [String] {
+ switch self {
+ case .keychain: ["UseKeychain yes", "AddKeysToAgent yes"]
+ case .keepAlive: ["ServerAliveInterval 60"]
+ case .reuseConnections: ["ControlMaster auto", "ControlPath ~/.ssh/cm-%C", "ControlPersist 10m"]
+ }
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift
index 53acabad..9c68c5ba 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift
@@ -1,5 +1,4 @@
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.
@@ -62,27 +61,20 @@ public enum ShellFile {
}
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))) + "\""
+ let path = "\"" + (url.path(below: 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)
+ 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)
}
}
- 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) {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SSHFileTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SSHFileTests.swift
new file mode 100644
index 00000000..812cbe38
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/SSHFileTests.swift
@@ -0,0 +1,105 @@
+import Foundation
+@testable import PeelCore
+import PeelPrivileged
+import Testing
+
+private struct SSHHome {
+ let folder: URL
+ let peelFile: URL
+ let config: URL
+
+ init(before lines: [String] = []) throws {
+ folder = FileManager.default.temporaryDirectory.appending(path: "SSHFileTests-\(UUID().uuidString)", directoryHint: .isDirectory)
+ peelFile = SSHFile.url(in: folder.appending(path: "Library/Application Support/Peel", directoryHint: .isDirectory))
+ config = folder.appending(path: "config")
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ let including = SSHFile.lines(including: peelFile, home: URL(filePath: "/var/empty", directoryHint: .isDirectory))
+ try (lines + including).joined(separator: "\n").appending("\n").write(to: config, atomically: true, encoding: .utf8)
+ }
+
+ /// The options ssh would use for `host`, by their names in lowercase, as `ssh -G` prints them.
+ func options(for host: String) async throws -> [String: String] {
+ let answer = await Subprocess.run("/usr/bin/ssh", ["-G", "-F", config.path(percentEncoded: false), host], environment: [:], timeout: 10)
+ guard case .success(let output) = answer else { throw POSIXError(.EIO) }
+ #expect(output.status == 0, "\(output.errorText)")
+ return Dictionary(output.text.split(separator: "\n").compactMap { line in
+ line.firstIndex(of: " ").map { (String(line[..<$0]), String(line[line.index(after: $0)...])) }
+ }, uniquingKeysWith: { first, _ in first })
+ }
+}
+
+struct SSHFileTests {
+ static let inEffect: [SSHSetting: [String: String]] = [
+ .keychain: ["addkeystoagent": "true"],
+ .keepAlive: ["serveraliveinterval": "60"],
+ .reuseConnections: ["controlmaster": "auto", "controlpersist": "600"],
+ ]
+
+ @Test func everySettingIsInEffectForEveryServerOnceItIsOnAndNotBefore() async throws {
+ let ssh = try SSHHome()
+ #expect(Set(Self.inEffect.keys) == Set(SSHSetting.allCases))
+ for setting in SSHSetting.allCases {
+ let wanted = try #require(Self.inEffect[setting])
+ #expect(SSHFile.write([], to: ssh.peelFile))
+ let before = try await ssh.options(for: "example.org")
+ #expect(wanted.allSatisfy { before[$0.key] != $0.value }, "\(setting)")
+ #expect(SSHFile.write([setting], to: ssh.peelFile))
+ let after = try await ssh.options(for: "example.org")
+ #expect(wanted.allSatisfy { after[$0.key] == $0.value }, "\(setting)")
+ }
+ #expect(try await ssh.options(for: "example.org")["controlpath"]?.contains("/.ssh/cm-") == true)
+ }
+
+ @Test func whatTheConfigSetsForAServerEarlierStaysFirst() async throws {
+ let ssh = try SSHHome(before: ["Host server", " ServerAliveInterval 10"])
+ #expect(SSHFile.write([.keepAlive], to: ssh.peelFile))
+ #expect(try await ssh.options(for: "server")["serveraliveinterval"] == "10")
+ #expect(try await ssh.options(for: "example.org")["serveraliveinterval"] == "60")
+ }
+
+ @Test func theSSHOnThisMacAcceptsEverySetting() async {
+ #expect(await SSHFile.accepted() == Set(SSHSetting.allCases))
+ }
+
+ @Test func theLinesNameTheFileFromTheHomeOrByItsWholePath() {
+ let home = URL(filePath: "/Users/example", directoryHint: .isDirectory)
+ let file = SSHFile.url(in: home.appending(path: "Library/Application Support/Peel", directoryHint: .isDirectory))
+ #expect(SSHFile.lines(including: file, home: home) == ["Match all", " Include \"~/Library/Application Support/Peel/Terminal/ssh_config\""])
+ #expect(SSHFile.lines(including: URL(filePath: "/Volumes/Other/Peel/Terminal/ssh_config"), home: home)
+ == ["Match all", " Include \"/Volumes/Other/Peel/Terminal/ssh_config\""])
+ }
+
+ @Test func theIncludeIsFoundUnlessItIsACommentOrOnlyMentionsTheFile() throws {
+ let ssh = try SSHHome()
+ let home = URL(filePath: "/var/empty", directoryHint: .isDirectory)
+ #expect(SSHFile.isIncluded(ssh.peelFile, from: ssh.config, home: home))
+ let user = ssh.folder.appending(path: "user")
+ for (text, found) in [
+ ("Match all\n Include ~/Library/Application\\ Support/Peel/Terminal/ssh_config\n", true),
+ ("Include=\"~/Library/Application Support/Peel/Terminal/ssh_config\"\n", true),
+ ("# Include \"~/Library/Application Support/Peel/Terminal/ssh_config\"\n", false),
+ ("Host server\n IdentityFile ~/Library/Application Support/Peel/Terminal/ssh_config\n", false),
+ ] {
+ try text.write(to: user, atomically: true, encoding: .utf8)
+ let home = URL(filePath: "/Users/example", directoryHint: .isDirectory)
+ let file = SSHFile.url(in: home.appending(path: "Library/Application Support/Peel", directoryHint: .isDirectory))
+ #expect(SSHFile.isIncluded(file, from: user, home: home) == found, "\(text)")
+ }
+ }
+
+ @Test func theFileReadsBackAsTheSettingsWrittenInIt() {
+ for setting in SSHSetting.allCases {
+ #expect(SSHFile.settings(in: SSHFile.contents(of: [setting])) == [setting])
+ }
+ #expect(SSHFile.settings(in: SSHFile.contents(of: Set(SSHSetting.allCases))) == Set(SSHSetting.allCases))
+ #expect(SSHFile.settings(in: SSHFile.contents(of: [])).isEmpty)
+ }
+
+ @Test func aMissingFileHasNothingOnAndOneThatCannotBeReadIsNotKnown() throws {
+ let folder = FileManager.default.temporaryDirectory.appending(path: "SSHFileTests-\(UUID().uuidString)", directoryHint: .isDirectory)
+ let file = SSHFile.url(in: folder)
+ #expect(SSHFile.read(file) == [])
+ try FileManager.default.createDirectory(at: file, withIntermediateDirectories: true)
+ #expect(SSHFile.read(file) == nil)
+ }
+}