diff --git a/CHANGELOG.md b/CHANGELOG.md index f6c5889..c8dc983 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,19 @@ What changed in each version of Kaern. A version's section is what its update wi - Settings › Open In: choose the editor and the terminal, leave out of the Open menus what you don't use, and add any other app, a command to run in your terminal, or a link (Customize Menu… in the ▾ goes there). Open in Terminal used to always open Terminal. +- Delete a tag from its right-click menu, in the sidebar or the history. Delete takes it from your repository, and + ⌘Z brings it back. Delete Here and on origin… takes it from the remote too, after asking. +- Put a file back the way a commit has it: right-click the file in that commit and choose Restore Version at…. + It lands in your changes, unstaged. The file's own changes go to Stashes first, and ⌘Z puts everything back. A + file the commit deleted comes back as it was just before. +- When ssh needs to ask something, Kaern asks you in a window: your SSH key's passphrase, whether to trust a server + it hasn't seen (with its key's fingerprint), or a security key's PIN. Kaern can remember the passphrase in your + Keychain; Settings › Advanced lists the keys and forgets them. Auto-fetch never asks: a locked key pauses it, and + the status bar says why. +- Diffs color the code by its language: keywords, strings, comments, numbers, types and functions, in Review, Focus, + file history and stashes, with the colors of Xcode's default themes. Swift, Objective-C, C and C++, C#, Java, + Kotlin, Go, Rust, JavaScript and TypeScript, Python, Ruby, PHP, shell scripts, SQL, HTML and XML, CSS, JSON, YAML, + TOML, Markdown, Dockerfiles, Makefiles and more. Settings › Diff turns it off. ### Improved @@ -28,6 +41,9 @@ What changed in each version of Kaern. A version's section is what its update wi its sections scrolls on its own, and so do the panel's Unstaged Files and Staged Files. While everything fits, nothing changes. When it doesn't, drag the line between two of them to give one more room; Kaern keeps the heights for next time, and a double-click on the line shares the room out again. +- Diffs scroll with less work: a file's lines take about a third less to bring into view, a file of many small + hunks about 40 % less, and All Files over many files about half. It shows most where scrolling a long diff + stuttered. ### Fixed @@ -39,8 +55,28 @@ What changed in each version of Kaern. A version's section is what its update wi the submodule out, as it does with `ignore = all`. It read "?" before. - Quick Look opened again right after closing it (Space twice in a row) stays open. Before, it closed again at once. +- Hooks find what your login shell finds. Kaern runs git with your login shell's PATH, as Terminal does, so a + pre-commit hook that calls npx, lint-staged or a tool from nvm, mise or `~/.local/bin` no longer fails with + "command not found" in Kaern only. The Command Log says when a command ran with it. +- Discard keeps a file that `git rm --cached` left on disk. Git lists such a file twice, as a staged deletion and + as a new file. Discarding the deletion put the committed file over it, and ⌘Z then deleted it. Now what was in + the file goes to Stashes with the rest, and ⌘Z brings it back. The same goes for a new file at a renamed file's + old name. +- Discard leaves what has taken a deleted file's place: a folder there with files of its own, or a file where the + deleted file's folder was. Git removes those to put the file back, so Kaern stops and names what is in the way. +- Before a repository's first commit, Discard deleted a new file without a copy, since git can't make a stash yet. + It discards nothing there now and says why. +- Discarding a file that became a folder of files, or a folder that became a file, works. It stopped with an error + before. +- An SSH failure says what happened. A key with a passphrase, or a server ssh hadn't seen, used to read as "SSH + key not accepted". A server whose host key changed now says how to check it, and a question you cancel ends + without an error. - Blame on a file that a commit deleted, from that commit's right-click menu, shows the file as it was before the commit. It showed an empty blame. +- A line number of five digits (from line 10,000 on, or a shorter one with a big diff font) no longer wraps onto a + second line and makes its row twice as tall: it is drawn a little narrower. +- In Split, when the diff's width leaves half a pixel over, the line between the two sides is straight. It stepped + a pixel left and right from row to row. ## [1.0.1] - 2026-11-19 diff --git a/Kaern/App/AppDelegate.swift b/Kaern/App/AppDelegate.swift index f6cb78f..1c076d2 100644 --- a/Kaern/App/AppDelegate.swift +++ b/Kaern/App/AppDelegate.swift @@ -26,12 +26,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // acts on commands a test run sends to its sample repositories. if SessionStore.testSessionPath != nil { DebugDriver.shared.start() } #endif + // Your login shell's PATH: git and its hooks run with it, and the agents in the terminal are found on it. + // Asked before the repositories open, so a command that can start a hook knows to wait for it. + LoginPath.load() AppModel.shared.launch() QuickLookCopies.removeOld() VersionCopies.removeOld() TerminalCommands.removeOld() - // The agents in the terminal are found on your login shell's PATH (OpenAgents). - LoginPath.load() // Release builds only (UpdateController.isAvailable). UpdateController.shared.start() } diff --git a/Kaern/App/AppModel.swift b/Kaern/App/AppModel.swift index 09b0c7d..cadbd89 100644 --- a/Kaern/App/AppModel.swift +++ b/Kaern/App/AppModel.swift @@ -91,6 +91,8 @@ final class AppModel { runner = GitRunner(executableURL: resolution.url, extraEnvironment: testEnvironment, removedEnvironment: launchUsesSSHAgent ? [] : ["SSH_AUTH_SOCK"], + searchPath: LoginPath.searchPath, + askpass: AskpassServer.shared.start(), onCommand: { CommandLog.receive($0) }) Self.log.info("Using git at \(resolution.url.path(percentEncoded: false), privacy: .public) (\(resolution.source.rawValue, privacy: .public)), version \(resolution.version ?? "unknown", privacy: .public)") startRepositories() diff --git a/Kaern/App/DebugDriver+Askpass.swift b/Kaern/App/DebugDriver+Askpass.swift new file mode 100644 index 0000000..9170cf0 --- /dev/null +++ b/Kaern/App/DebugDriver+Askpass.swift @@ -0,0 +1,45 @@ +#if DEBUG +import AppKit +import KaernKit + +/// Debug commands for what ssh asks (`AskpassCenter`): answer the question the window shows, cancel it, the Keychain +/// checkbox, and forgetting what's saved (a test instance keeps it in memory). +extension DebugDriver { + static let askpassCommands: Set = ["askpassAnswer", "askpassCancel", "askpassRemember", "askpassForget"] + + func askpassCommand(_ command: String, _ args: [String]) { + let center = AskpassCenter.shared + switch command { + case "askpassAnswer": + // askpassAnswer [text…]: what was typed; nothing for Connect and Allow. + let text = args.joined(separator: " ") + center.respond(text.isEmpty ? nil : text) + case "askpassCancel": + center.cancel() + case "askpassRemember": + center.remember = args.first != "off" + case "askpassForget": + SSHPassphrases.forgetAll() + default: + break + } + } + + /// The question shown (its kind and words), how many wait, how many the window showed, and the saved keys. + func askpassDump() -> [String: Any] { + let center = AskpassCenter.shared + var result: [String: Any] = [ + "shown": center.shownCount, "waiting": center.questions.count, "saved": SSHPassphrases.keys, + "remember": center.remember, "window": AskpassWindowController.shared.window?.isVisible ?? false, + ] + if let question = center.current { + result["kind"] = String("\(question.kind)".prefix { $0 != "(" }) + result["question"] = "\(question.kind)" + result["action"] = question.action + result["repository"] = question.repository + result["retry"] = question.retry + } + return result + } +} +#endif diff --git a/Kaern/App/DebugDriver+Phase5.swift b/Kaern/App/DebugDriver+Phase5.swift index a168f34..2d5c93a 100644 --- a/Kaern/App/DebugDriver+Phase5.swift +++ b/Kaern/App/DebugDriver+Phase5.swift @@ -353,6 +353,19 @@ extension DebugDriver { func sizes(_ value: [String: LFSSizes]) -> [String: String] { value.mapValues { "\($0.old.map(String.init) ?? "-")→\($0.new.map(String.init) ?? "-")" } } + // The code of the file Review shows, colored: its language and each line's pieces (Settings › Diff). + if let path = repository.review?.path, let file = repository.reviewFiles?.first(where: { $0.path == path }) { + let rows = DiffRowItem.rows(for: file, layout: .unified, limit: 60, words: false, syntax: AppSettings.diffSyntax) + result["syntax"] = [ + "language": SyntaxHighlighter.language(forPath: path)?.name ?? "", + "lines": rows.compactMap { row -> String? in + guard case .unified(_, let line, _, _, let syntax) = row else { return nil } + let characters = Array(line.text) + return (syntax?.spans(of: line) ?? []).map { "\($0.kind):" + String(characters[$0.range.clamped(to: 0.. — keeps that size, as a drag does (0: the board's). let keys = ["sidebar": PaneSizes.sidebarKey, "panel": PaneSizes.panelKey, "drawer": PaneSizes.drawerKey, "list": PaneSizes.listKey] @@ -267,6 +272,12 @@ final class DebugDriver { if rest.contains("option") { flags.insert(.option) } click(at: CGPoint(x: x, y: y), count: rest.first.flatMap { Int($0) } ?? 1, flags: flags) } + case "mouseDown", "mouseUp": + // mouseDown x y | mouseUp x y — half a click each (window points, top-left origin): a button held down, + // then let go of somewhere else. + if args.count >= 2, let x = Double(args[0]), let y = Double(args[1]) { + mouse(command == "mouseDown" ? .leftMouseDown : .leftMouseUp, at: CGPoint(x: x, y: y)) + } case "drag": // drag x1 y1 x2 y2 [sequence reply-file]. A retry only acknowledges the same drag. guard args.count == 4 || args.count == 6 else { return } @@ -1188,6 +1199,7 @@ final class DebugDriver { "recent": app.recent.map(\.name), "phase5": phase5Dump(window), "phase6": phase6Dump(window), + "askpass": askpassDump(), // The global git config and credential helpers git sees (TestSession). "gitConfigEnvironment": (app.runner?.environment ?? [:]).filter { $0.key.hasPrefix("GIT_CONFIG") }, // Kaern's settings as this instance reads them: launch arguments over its own store. @@ -1226,6 +1238,8 @@ final class DebugDriver { "lastCommand": entries.last?.id.uuidString ?? "", "commandCount": entries.count, "fetchingAll": AutoFetcher.shared.isFetchingAll, + // The login shell's PATH hasn't come yet (a check holds it back). + "loginPathHeld": LoginPath.isHeld, // Popovers, menus, Settings, the Command Log…: what is on screen besides the main windows. "visibleWindows": NSApp.windows.filter(\.isVisible).map { "\(type(of: $0)) \($0.title)" }, "firstResponder": responder.map { String(describing: type(of: $0)) } ?? "", diff --git a/Kaern/App/FailureHelp.swift b/Kaern/App/FailureHelp.swift index 2080a4d..7f347a2 100644 --- a/Kaern/App/FailureHelp.swift +++ b/Kaern/App/FailureHelp.swift @@ -31,6 +31,37 @@ struct FailureHelp { fixTitle: "How to Add an SSH Key", fix: { NSWorkspace.shared.open(URL(string: "https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account")!) }, short: "SSH key not accepted") + case .sshKeyLocked(let host): + let name = host ?? repository?.remoteHost ?? "the server" + return FailureHelp( + message: "Your SSH key for \(name) is locked, and Kaern asks for its passphrase only for what you start yourself" + + (auto ? ", so auto-fetch for \(repositoryName) is paused. Fetch once to unlock it; Kaern can remember the passphrase in your Keychain." + : ". Fetch to unlock it."), + fixTitle: repository == nil ? nil : "Fetch", + fix: repository.map { model in { model.from("Command Log") { model.fetch() } } }, + short: "SSH key locked") + case .hostKeyUnknown(let host): + let name = host ?? repository?.remoteHost ?? "the server" + return FailureHelp( + message: "ssh hasn’t seen \(name)’s host key before, and nobody confirmed it" + + (auto ? ", so auto-fetch for \(repositoryName) is paused." : ".") + " Fetch to see the key and connect.", + fixTitle: repository == nil ? nil : "Fetch", + fix: repository.map { model in { model.from("Command Log") { model.fetch() } } }, + short: "new SSH host") + case .hostKeyChanged(let host): + let name = host ?? repository?.remoteHost ?? "the server" + return FailureHelp( + message: "\(name)’s host key isn’t the one ssh knows for it. If \(name) announced a new key, remove the old one " + + "(ssh-keygen -R \(name)) and connect again. If it didn’t, someone may be in between: don’t connect.", + fixTitle: "Copy the Command", + fix: { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString("ssh-keygen -R \(name)", forType: .string) + }, + short: "SSH host key changed") + case .promptCancelled: + return FailureHelp(message: "You cancelled what ssh asked, so \(repositoryName) didn’t connect.", fixTitle: nil, fix: nil, + short: "cancelled") case .network(let host): return FailureHelp( message: "Kaern couldn’t reach \(host ?? "the server"). Check the connection or VPN, then try again.", @@ -84,6 +115,10 @@ struct FailureHelp { "\(host ?? "The server") didn’t accept your SSH key. Add it to your account there, or clone with the HTTPS URL." case .network(let host)?: "Kaern couldn’t reach \(host ?? "the server"). Check the connection or VPN, then try again." + case .hostKeyChanged(let host)?: + "\(host ?? "The server")’s host key isn’t the one ssh knows for it. If it announced a new key, remove the old one (ssh-keygen -R \(host ?? "host")) and clone again." + case .promptCancelled?: + "You cancelled what ssh asked, so nothing was cloned." default: nil } diff --git a/Kaern/App/OpenAgents.swift b/Kaern/App/OpenAgents.swift index 5b3df6e..6fbb980 100644 --- a/Kaern/App/OpenAgents.swift +++ b/Kaern/App/OpenAgents.swift @@ -264,6 +264,8 @@ extension RepositoryModel { enum LoginPath { private static var folders: [String] = [] private static var asked = false + /// What git and its hooks run with: this PATH, once read, ahead of Kaern's own (`GitRunner.searchPath`). + nonisolated static let searchPath = GitSearchPath() /// Your login shell (the one Terminal starts). static let shell: String = { @@ -287,17 +289,33 @@ enum LoginPath { return nil } - /// Asks the login shell for its PATH, once a launch; the agents are looked for again when it answers. A test - /// instance goes by the usual places. + /// Asks the login shell for its PATH, once a launch: git and its hooks get it (a command that can start a hook + /// waits for the answer), and the agents are looked for again. A test instance goes by the usual places, or by + /// the PATH a check gives it (`-KaernLoginPath`): at once, or, with `-KaernLoginPathHeld YES`, when the check + /// says so (`loginPath`), as a login shell that takes its time. static func load() { guard !asked else { return } asked = true #if DEBUG - if SessionStore.testSessionPath != nil { return } + if SessionStore.testSessionPath != nil { + if let given = UserDefaults.standard.string(forKey: "KaernLoginPath") { + if UserDefaults.standard.bool(forKey: "KaernLoginPathHeld") { + held = given + searchPath.expect() + } else { + folders = given.split(separator: ":").map(String.init).filter { !$0.isEmpty } + searchPath.provide(given) + } + } + return + } #endif + searchPath.expect() let shell = shell Task.detached(priority: .utility) { - guard let path = readPath(shell) else { return } + let path = readPath(shell) + searchPath.provide(path) + guard let path else { return } await MainActor.run { folders = path.split(separator: ":").map(String.init).filter { !$0.isEmpty } OpenAgents.refresh() @@ -305,6 +323,20 @@ enum LoginPath { } } + #if DEBUG + /// The PATH a check holds back until it says `loginPath` (`-KaernLoginPathHeld YES`). + private static var held: String? + static var isHeld: Bool { held != nil } + + /// The held PATH arrives, as the login shell's answer does. + static func provideHeld() { + guard let given = held else { return } + held = nil + folders = given.split(separator: ":").map(String.init).filter { !$0.isEmpty } + searchPath.provide(given) + } + #endif + /// The shell's PATH, written to a file so what its setup prints doesn't matter; nothing after 6 s. nonisolated private static func readPath(_ shell: String) -> String? { let file = FileManager.default.temporaryDirectory.appending(path: "kaern-path-\(UUID().uuidString)") diff --git a/Kaern/App/main.swift b/Kaern/App/main.swift index 0abadd5..06e7fa0 100644 --- a/Kaern/App/main.swift +++ b/Kaern/App/main.swift @@ -1,5 +1,8 @@ import AppKit +// Started by ssh as its asker (`GitAskpass`): hand the question to the running Kaern, print the answer, end here. +AskpassClient.runIfAsked() + // Kaern runs on the AppKit app lifecycle: it creates its windows itself from its session file, // and its menus are AppKit menus validated against the current window (see `MainMenu`). let application = NSApplication.shared diff --git a/Kaern/Askpass/AskpassCenter.swift b/Kaern/Askpass/AskpassCenter.swift new file mode 100644 index 0000000..4ec2a16 --- /dev/null +++ b/Kaern/Askpass/AskpassCenter.swift @@ -0,0 +1,191 @@ +import AppKit +import KaernKit +import Observation +import Security + +/// What ssh asks, answered: from what Kaern remembers (a saved passphrase), or in a window (`AskpassWindowController`), +/// one question at a time. A background command gets no window: a locked key or a new host fails it with a note +/// that says so (`GitAskpass.Note`), and auto-fetch pauses until you fetch by hand. +@MainActor @Observable +final class AskpassCenter { + static let shared = AskpassCenter() + + struct Question: Identifiable { + let id: UUID + let kind: AskpassQuestion + /// What you did ("Fetch"). + let action: String + /// The repository's name. + let repository: String + /// The passphrase is asked again: the last one given didn't unlock the key. + let retry: Bool + fileprivate let reply: CheckedContinuation + } + + private(set) var questions: [Question] = [] + var current: Question? { questions.first } + /// Remember the passphrase in the Keychain (the window's checkbox). + var remember = true + /// How many questions Kaern showed in its window (the checks count them). + private(set) var shownCount = 0 + /// Which ssh was given which key's passphrase a moment ago: its next question for the key means that one + /// didn't unlock it (`AskpassAttempts`). + @ObservationIgnored private var attempts = AskpassAttempts() + + func answer(_ request: AskpassRequest, id: UUID) async -> AskpassReply { + let kind = AskpassQuestion.read(prompt: request.prompt, mode: request.mode) + var retry = false + if case .passphrase(let key) = kind { + // The saved one, unless this ssh was just turned down with it; then it goes, and you're asked. + switch attempts.next(key: key, process: request.asker, saved: SSHPassphrases.saved(for: key)) { + case .give(let saved): + return AskpassReply(ok: true, answer: saved) + case .ask(let again, let forget): + retry = again + if forget { SSHPassphrases.forget(key) } + } + } + if request.action.isEmpty { + switch kind { + case .passphrase: return AskpassReply(ok: false, note: GitAskpass.Note.locked) + case .newHost: return AskpassReply(ok: false, note: GitAskpass.Note.newHost) + default: return .no + } + } + if case .gitCredential = kind { return .no } + let name = request.repository.isEmpty ? "" : (request.repository as NSString).lastPathComponent + // "Toolbar › Fetch" in the Command Log; the window says what you did. + let action = request.action.components(separatedBy: " › ").last ?? request.action + let reply = await withCheckedContinuation { continuation in + questions.append(Question(id: id, kind: kind, action: action, repository: name, retry: retry, reply: continuation)) + if questions.count == 1 { present() } + } + if reply.ok, let passphrase = reply.answer, case .passphrase(let key) = kind { + attempts.answered(passphrase, key: key, process: request.asker) + } + return reply + } + + /// The window's answer to the question it shows: what was typed, or nil for Connect and Yes. + func respond(_ text: String?) { + guard let question = questions.first else { return } + switch question.kind { + case .passphrase(let key): + guard let text else { return } + if remember { SSHPassphrases.save(text, for: key) } + let reply = AskpassReply(ok: true, answer: text) + // Another ssh waiting with the same question (two fetches at once with one key) has its answer too: + // one key, one passphrase. + let same = questions.dropFirst().filter { $0.kind == question.kind } + questions.removeAll { waiting in same.contains { $0.id == waiting.id } } + for waiting in same { waiting.reply.resume(returning: reply) } + finish(reply) + case .newHost: + finish(AskpassReply(ok: true, answer: "yes")) + case .confirm: + finish(AskpassReply(ok: true)) + case .pin, .other: + finish(AskpassReply(ok: true, answer: text ?? "")) + case .touch, .gitCredential: + finish(.no) + } + } + + /// Cancel: ssh gets no answer, and the command ends without an alert (`GitFailure.promptCancelled`). + func cancel() { + guard let question = questions.first else { return } + if case .touch = question.kind { finish(.no) } else { finish(AskpassReply(ok: false, note: GitAskpass.Note.cancelled)) } + } + + /// The asker went away (ssh ended it, or the command was stopped): its question goes. + func withdraw(_ id: UUID) { + guard let index = questions.firstIndex(where: { $0.id == id }) else { return } + let question = questions.remove(at: index) + question.reply.resume(returning: .no) + if index == 0 { present() } + } + + private func finish(_ reply: AskpassReply) { + let question = questions.removeFirst() + question.reply.resume(returning: reply) + present() + } + + private func present() { + remember = true + if let current { + shownCount += 1 + AskpassWindowController.shared.show(current) + } else { + AskpassWindowController.shared.hide() + } + } +} + +/// SSH key passphrases Kaern remembers, in your login Keychain: one item per key file, "Kaern SSH key passphrase". +/// A test instance keeps them in memory only. +enum SSHPassphrases { + private static let service = "Kaern SSH key passphrase" + #if DEBUG + private static var memory: [String: String] = [:] + private static var inMemory: Bool { SessionStore.testSessionPath != nil } + #endif + + static func saved(for key: String) -> String? { + #if DEBUG + if inMemory { return memory[key] } + #endif + var query = item(key) + query[kSecReturnData as String] = true + query[kSecMatchLimit as String] = kSecMatchLimitOne + var result: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil } + return String(data: data, encoding: .utf8) + } + + static func save(_ passphrase: String, for key: String) { + #if DEBUG + if inMemory { + memory[key] = passphrase + return + } + #endif + let data = Data(passphrase.utf8) + if SecItemUpdate(item(key) as CFDictionary, [kSecValueData as String: data] as CFDictionary) == errSecItemNotFound { + var new = item(key) + new[kSecValueData as String] = data + new[kSecAttrLabel as String] = service + " (" + (key as NSString).lastPathComponent + ")" + SecItemAdd(new as CFDictionary, nil) + } + } + + static func forget(_ key: String) { + #if DEBUG + if inMemory { + memory[key] = nil + return + } + #endif + SecItemDelete(item(key) as CFDictionary) + } + + /// The key files whose passphrase is saved. + static var keys: [String] { + #if DEBUG + if inMemory { return memory.keys.sorted() } + #endif + let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, + kSecReturnAttributes as String: true, kSecMatchLimit as String: kSecMatchLimitAll] + var result: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, let items = result as? [[String: Any]] else { return [] } + return items.compactMap { $0[kSecAttrAccount as String] as? String }.sorted() + } + + static func forgetAll() { + for key in keys { forget(key) } + } + + private static func item(_ key: String) -> [String: Any] { + [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: key] + } +} diff --git a/Kaern/Askpass/AskpassServer.swift b/Kaern/Askpass/AskpassServer.swift new file mode 100644 index 0000000..c1f6989 --- /dev/null +++ b/Kaern/Askpass/AskpassServer.swift @@ -0,0 +1,103 @@ +import Darwin +import Foundation +import KaernKit + +/// The running app's end of `GitAskpass`: a Unix socket read on a thread of its own. Each question goes to +/// `AskpassCenter` on the main actor and its answer back to the asker. A question whose asker goes away (ssh ended +/// it, or the command was stopped) is taken back. +nonisolated final class AskpassServer: @unchecked Sendable { + static let shared = AskpassServer() + + private let lock = NSLock() + private var started: GitAskpass? + private let token = UUID().uuidString + + /// Starts listening, once. `nil` when the socket can't be made: ssh then asks no one, as before. + func start() -> GitAskpass? { + lock.lock() + defer { lock.unlock() } + if let started { return started } + guard let program = Bundle.main.executableURL?.path(percentEncoded: false) else { return nil } + let path = FileManager.default.temporaryDirectory + .appending(path: "kaern-askpass-\(UUID().uuidString.prefix(8)).sock").path(percentEncoded: false) + guard var address = AskpassSocket.address(path) else { return nil } + unlink(path) + let listener = socket(AF_UNIX, SOCK_STREAM, 0) + guard listener >= 0 else { return nil } + let bound = withUnsafePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(listener, $0, socklen_t(MemoryLayout.size)) } + } + guard bound == 0, chmod(path, 0o600) == 0, listen(listener, 16) == 0 else { + close(listener) + return nil + } + let thread = Thread { [self] in acceptLoop(listener) } + thread.name = "Kaern askpass" + thread.start() + let askpass = GitAskpass(program: program, socket: path, token: token) + started = askpass + return askpass + } + + private func acceptLoop(_ listener: Int32) { + while true { + let client = accept(listener, nil, nil) + if client < 0 { + if errno == EINTR || errno == ECONNABORTED { continue } + return + } + var on: Int32 = 1 + setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &on, socklen_t(MemoryLayout.size)) + DispatchQueue.global(qos: .userInitiated).async { [self] in serve(client) } + } + } + + /// One question: read, answered on the main actor, replied, closed. + private func serve(_ client: Int32) { + defer { close(client) } + guard let line = AskpassSocket.readLine(client, limit: 64 * 1024), + let request = try? JSONDecoder().decode(AskpassRequest.self, from: line), request.token == token else { return } + let id = UUID() + let done = DispatchSemaphore(value: 0) + let reply = ReplyBox() + Task { @MainActor in + reply.set(await AskpassCenter.shared.answer(request, id: id)) + done.signal() + } + // Until the answer comes, notice the asker going away. + var gone = false + while done.wait(timeout: .now() + .milliseconds(200)) == .timedOut { + if !gone, Self.hungUp(client) { + gone = true + Task { @MainActor in AskpassCenter.shared.withdraw(id) } + } + } + guard !gone, let body = try? JSONEncoder().encode(reply.value) else { return } + _ = AskpassSocket.writeAll(client, body + Data([0x0A])) + } + + /// The other end closed: readable, with nothing to read. + private static func hungUp(_ socket: Int32) -> Bool { + var descriptor = pollfd(fd: socket, events: Int16(POLLIN), revents: 0) + guard poll(&descriptor, 1, 0) > 0 else { return false } + var byte: UInt8 = 0 + return recv(socket, &byte, 1, MSG_PEEK | MSG_DONTWAIT) <= 0 + } +} + +nonisolated private final class ReplyBox: @unchecked Sendable { + private let lock = NSLock() + private var reply = AskpassReply.no + + func set(_ value: AskpassReply) { + lock.lock() + reply = value + lock.unlock() + } + + var value: AskpassReply { + lock.lock() + defer { lock.unlock() } + return reply + } +} diff --git a/Kaern/Askpass/AskpassSocket.swift b/Kaern/Askpass/AskpassSocket.swift new file mode 100644 index 0000000..3d60c74 --- /dev/null +++ b/Kaern/Askpass/AskpassSocket.swift @@ -0,0 +1,104 @@ +import Darwin +import Foundation +import KaernKit + +/// One question from the asker to the app: a line of JSON (`GitAskpass`). +nonisolated struct AskpassRequest: Codable, Sendable { + var token: String + var prompt: String + /// `SSH_ASKPASS_PROMPT`: "none" (a notice ssh ends itself) or "confirm" (yes or no). + var mode: String? + /// What the user did ("Fetch"); empty for a background command. + var action: String + var repository: String + /// The asker's parent, ssh: a second question about the same key from it means the first answer was wrong. + var asker: Int32 +} + +/// The app's reply, a line of JSON: the answer to print, or none (`ok` false) with a note for ssh's error output. +nonisolated struct AskpassReply: Codable, Sendable { + var ok: Bool + var answer: String? + var note: String? + + static let no = AskpassReply(ok: false) +} + +/// The Unix socket both ends use: in the temporary folder, which is yours alone, with a token besides. +nonisolated enum AskpassSocket { + static func address(_ path: String) -> sockaddr_un? { + var address = sockaddr_un() + let bytes = Array(path.utf8CString).map { UInt8(bitPattern: $0) } + guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else { return nil } + address.sun_family = sa_family_t(AF_UNIX) + address.sun_len = UInt8(MemoryLayout.size) + withUnsafeMutableBytes(of: &address.sun_path) { $0.copyBytes(from: bytes) } + return address + } + + /// The asker's side: sends `request` and waits for the reply. `nil` when the app isn't there to ask. + static func send(_ request: AskpassRequest, to path: String) -> AskpassReply? { + guard var address = address(path), let body = try? JSONEncoder().encode(request) else { return nil } + let socket = Darwin.socket(AF_UNIX, SOCK_STREAM, 0) + guard socket >= 0 else { return nil } + defer { close(socket) } + let connected = withUnsafePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(socket, $0, socklen_t(MemoryLayout.size)) } + } + guard connected == 0, writeAll(socket, body + Data([0x0A])), let line = readLine(socket, limit: 64 * 1024) else { return nil } + return try? JSONDecoder().decode(AskpassReply.self, from: line) + } + + static func writeAll(_ socket: Int32, _ data: Data) -> Bool { + data.withUnsafeBytes { buffer in + guard let base = buffer.baseAddress else { return true } + var offset = 0 + while offset < buffer.count { + let written = write(socket, base + offset, buffer.count - offset) + if written < 0 { + if errno == EINTR { continue } + return false + } + offset += written + } + return true + } + } + + /// One line, without its newline; `nil` at the end before one, or past `limit` bytes. + static func readLine(_ socket: Int32, limit: Int) -> Data? { + var line = Data() + var byte: UInt8 = 0 + while line.count < limit { + let count = read(socket, &byte, 1) + if count < 0 { + if errno == EINTR { continue } + return nil + } + if count == 0 { return nil } + if byte == 0x0A { return line } + line.append(byte) + } + return nil + } +} + +/// Kaern started by ssh as its asker (`SSH_ASKPASS`, with `KAERN_ASKPASS` set): hands the question to the running +/// app, prints the answer, and ends, without starting the app. +nonisolated enum AskpassClient { + /// Asks and exits when that's how Kaern was started; returns otherwise. + static func runIfAsked() { + let environment = ProcessInfo.processInfo.environment + let arguments = CommandLine.arguments + guard let socket = environment[GitAskpass.Key.socket], !socket.isEmpty, + arguments.count >= 2, !arguments[1].hasPrefix("-") else { return } + let request = AskpassRequest(token: environment[GitAskpass.Key.token] ?? "", prompt: arguments[1], + mode: environment["SSH_ASKPASS_PROMPT"], action: environment[GitAskpass.Key.action] ?? "", + repository: environment[GitAskpass.Key.repository] ?? "", asker: getppid()) + guard let reply = AskpassSocket.send(request, to: socket) else { exit(1) } + if let note = reply.note { FileHandle.standardError.write(Data((note + "\n").utf8)) } + guard reply.ok else { exit(1) } + if let answer = reply.answer { FileHandle.standardOutput.write(Data((answer + "\n").utf8)) } + exit(0) + } +} diff --git a/Kaern/Askpass/AskpassWindow.swift b/Kaern/Askpass/AskpassWindow.swift new file mode 100644 index 0000000..fc4da02 --- /dev/null +++ b/Kaern/Askpass/AskpassWindow.swift @@ -0,0 +1,220 @@ +import AppKit +import KaernKit +import SwiftUI + +/// The window that asks what ssh asks (`AskpassCenter`), over Kaern's windows. It isn't a sheet of one window: a +/// question can come from a repository no window shows (Fetch All). +@MainActor +final class AskpassWindowController: NSWindowController, NSWindowDelegate { + static let shared = AskpassWindowController() + private let hosting: KaernHostingView + + private init() { + let window = AppWindow(contentRect: NSRect(x: 0, y: 0, width: z(440), height: z(200)), + styleMask: [.titled, .fullSizeContentView], backing: .buffered, defer: false) + window.title = "SSH" + window.titlebarAppearsTransparent = true + window.titleVisibility = .hidden + window.titlebarSeparatorStyle = .none + window.isRestorable = false + window.tabbingMode = .disallowed + window.isReleasedWhenClosed = false + window.level = .floating + window.isMovableByWindowBackground = true + hosting = KaernHostingView(rootView: AnyView(AskpassView(center: AskpassCenter.shared).zoomed())) + // The title bar is see-through and empty: the question starts at the window's top, and its size is the + // question's. + hosting.safeAreaRegions = [] + window.contentView = hosting + super.init(window: window) + window.delegate = self + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError() } + + /// Shows the question, near the top of the window in front (centered without one). + func show(_ question: AskpassCenter.Question) { + guard let window else { return } + hosting.layoutSubtreeIfNeeded() + window.setContentSize(hosting.fittingSize) + let front = NSApp.mainWindow ?? NSApp.orderedWindows.first { $0 is KaernWindow && $0.isVisible } + if let front { + let frame = front.frame + window.setFrameOrigin(NSPoint(x: frame.midX - window.frame.width / 2, y: frame.maxY - window.frame.height - z(110))) + } else { + window.center() + } + window.makeKeyAndOrderFront(nil) + #if DEBUG + if TestSession.stem != nil { return } + #endif + if !NSApp.isActive { NSApp.requestUserAttention(.informationalRequest) } + } + + func hide() { + window?.orderOut(nil) + } +} + +/// One question: what it's for, the field or the key's fingerprint, and the buttons. +struct AskpassView: View { + @Bindable var center: AskpassCenter + @State private var text = "" + @FocusState private var focused: Bool + + var body: some View { + Group { + if let question = center.current { + content(question) + .id(question.id) + .onAppear { + text = "" + focused = true + } + } else { + Color.clear.frame(width: z(440), height: z(1)) + } + } + } + + private func content(_ question: AskpassCenter.Question) -> some View { + VStack(alignment: .leading, spacing: z(14)) { + HStack(alignment: .top, spacing: z(14)) { + Image(systemName: symbol(question.kind)) + .font(.system(size: z(26), weight: .regular)) + .foregroundStyle(K.accent) + .frame(width: z(34)) + VStack(alignment: .leading, spacing: z(5)) { + Text(title(question)) + .font(.system(size: z(13.5), weight: .semibold)) + Text(detail(question)) + .font(.system(size: z(12))) + .foregroundStyle(K.label2) + .fixedSize(horizontal: false, vertical: true) + } + } + if case .newHost(_, let type, let fingerprint) = question.kind, let fingerprint { + VStack(alignment: .leading, spacing: z(3)) { + Text((type.map { $0 + " " } ?? "") + "key fingerprint") + .font(.system(size: z(10.5))) + .foregroundStyle(K.label2) + Text(fingerprint) + .font(.system(size: z(11), design: .monospaced)) + .lineLimit(1) + .minimumScaleFactor(0.7) + .textSelection(.enabled) + } + .padding(.horizontal, z(10)) + .padding(.vertical, z(8)) + .frame(maxWidth: .infinity, alignment: .leading) + .background(RoundedRectangle(cornerRadius: z(6), style: .continuous).fill(K.field)) + .overlay(RoundedRectangle(cornerRadius: z(6), style: .continuous).strokeBorder(K.sepStrong, lineWidth: 0.5)) + .padding(.leading, z(48)) + } + if needsText(question.kind) { + VStack(alignment: .leading, spacing: z(8)) { + SecureField(fieldLabel(question.kind), text: $text) + .textFieldStyle(.roundedBorder) + .focused($focused) + .onSubmit { submit(question) } + if question.retry { + Text("That passphrase didn’t unlock the key. Try again.") + .font(.system(size: z(11.5))) + .foregroundStyle(K.err) + } + if case .passphrase = question.kind { + Toggle("Remember in my Keychain", isOn: $center.remember) + .toggleStyle(.checkbox) + .font(.system(size: z(12))) + } + } + .padding(.leading, z(48)) + } + HStack(spacing: z(8)) { + Spacer() + if case .touch = question.kind { + Button("Hide") { center.cancel() } + .keyboardShortcut(.cancelAction) + } else { + Button("Cancel") { center.cancel() } + .keyboardShortcut(.cancelAction) + Button(confirmTitle(question.kind)) { submit(question) } + .keyboardShortcut(.defaultAction) + .disabled(needsText(question.kind) && text.isEmpty) + } + } + } + .padding(EdgeInsets(top: z(22), leading: z(20), bottom: z(18), trailing: z(20))) + .frame(width: z(440)) + } + + private func submit(_ question: AskpassCenter.Question) { + if needsText(question.kind) { + guard !text.isEmpty else { return } + center.respond(text) + } else { + center.respond(nil) + } + } + + private func needsText(_ kind: AskpassQuestion) -> Bool { + switch kind { + case .passphrase, .pin, .other: true + default: false + } + } + + private func symbol(_ kind: AskpassQuestion) -> String { + switch kind { + case .passphrase: "key.fill" + case .newHost: "server.rack" + case .pin, .touch: "touchid" + default: "lock.fill" + } + } + + private func title(_ question: AskpassCenter.Question) -> String { + switch question.kind { + case .passphrase: "Unlock your SSH key" + case .newHost(let host, _, _): "Connect to \(host)?" + case .pin: "Enter your security key’s PIN" + case .touch: "Touch your security key" + case .confirm(let message): message + case .gitCredential(let message), .other(let message): message + } + } + + private func detail(_ question: AskpassCenter.Question) -> String { + let doing = question.repository.isEmpty ? question.action : "\(question.action) in \(question.repository)" + switch question.kind { + case .passphrase(let key): + return "\(doing) needs the passphrase of \(Formatters.abbreviatedPath(key))." + case .newHost(let host, _, _): + return "Kaern hasn’t connected to \(host) before. Check that the key below is the one \(host) publishes; once you connect, ssh remembers it." + case .pin(let key): + return "\(doing) uses \(Formatters.abbreviatedPath(key))." + case .touch(let message): + return message + case .confirm, .gitCredential, .other: + return "ssh asks for \(doing)." + } + } + + private func fieldLabel(_ kind: AskpassQuestion) -> String { + switch kind { + case .passphrase: "Passphrase" + case .pin: "PIN" + default: "Answer" + } + } + + private func confirmTitle(_ kind: AskpassQuestion) -> String { + switch kind { + case .passphrase: "Unlock" + case .newHost: "Connect" + case .confirm: "Allow" + default: "OK" + } + } +} diff --git a/Kaern/Design/Tokens.swift b/Kaern/Design/Tokens.swift index e92700a..56ff1bc 100644 --- a/Kaern/Design/Tokens.swift +++ b/Kaern/Design/Tokens.swift @@ -72,6 +72,15 @@ nonisolated enum K { static let addWord = dynamic(rgba(40, 167, 69, 0.28), rgba(48, 209, 88, 0.3)) // changed words static let delWord = dynamic(rgba(255, 59, 48, 0.22), rgba(255, 69, 58, 0.32)) static let hunk = dynamic(0xf0f4fa, 0x222b37) + // Code in diffs (Settings › Diff › Highlight syntax), after Xcode's default themes. + static let synKeyword = dynamic(0x9b2393, 0xfc5fa3) + static let synString = dynamic(0xc41a16, 0xfc6a5d) + static let synComment = dynamic(0x5d6c79, 0x8b96a2) + static let synNumber = dynamic(0x1c00cf, 0xd0bf69) + static let synType = dynamic(0x3900a0, 0xd0a8ff) + static let synFunction = dynamic(0x326d74, 0x67b7a4) + static let synAttribute = dynamic(0x815f03, 0xbf8555) + static let synPreprocessor = dynamic(0x643820, 0xfd8f3f) // ScreenConflicts: the operation bar, open conflict blocks, the two sides. static let opBg = dynamic(0xfdecea, 0x3b2321) static let opText = dynamic(0x8a1f17, 0xffb4ab) diff --git a/Kaern/Repository/RepositoryModel+Actions.swift b/Kaern/Repository/RepositoryModel+Actions.swift index 2d2eec7..10c4889 100644 --- a/Kaern/Repository/RepositoryModel+Actions.swift +++ b/Kaern/Repository/RepositoryModel+Actions.swift @@ -441,6 +441,33 @@ extension RepositoryModel { } } + /// Delete: the tag goes here, and ⌘Z makes it again with the object it had (an annotated tag keeps its message + /// and signature). A remote keeps its copy: a fetch brings it back while the remote has it. + func deleteTag(_ name: String) { + perform(.working("Deleting \(name)…"), trigger: "Delete Tag \(name)") { [weak self] repository in + guard let object = await repository.resolve("refs/tags/\(name)") else { return } + try await repository.deleteTag(name) + self?.record(.deletedTag(name: name, object: object), toast: "Deleted \(name) · ⌘Z brings it back") + } + } + + /// Delete Here and on origin…: asks first, a remote can't be undone. A tag the remote doesn't have goes here only. + func deleteTagEverywhere(_ name: String) { + guard let remote = defaultRemote else { return } + confirmation = Confirmation( + title: "Delete \(name) here and on \(remote)?", + message: "The tag is removed for everyone who uses \(remote). Kaern can’t undo changes on a remote.", + confirmTitle: "Delete", + confirm: { [weak self] in + self?.perform(.network("Deleting \(name)…"), trigger: "Delete Tag \(name)") { [weak self] repository in + let wasThere = try await repository.deleteRemoteTag(name, on: remote) + if await repository.resolve("refs/tags/\(name)") != nil { try await repository.deleteTag(name) } + self?.showToast(wasThere ? "Deleted \(name) here and on \(remote)" : "Deleted \(name) · \(remote) didn’t have it") + } + } + ) + } + /// Records a branch move; when the uncommitted changes had to stay in the stash list, the /// toast says so and ⌘Z brings them back too. func recordMove(label: String, branch: String?, from: String, to: String, kept: String?, toast: String?) { @@ -472,17 +499,30 @@ extension RepositoryModel { func discard(_ entries: [StatusEntry], keepingStaged: Bool) { guard !entries.isEmpty else { return } let paths = Array(Set(entries.flatMap { [$0.originalPath, $0.path].compactMap { $0 } })).sorted() - let untracked = entries.filter(\.isUntracked).map(\.path) let name = entries.count == 1 ? (entries[0].path as NSString).lastPathComponent : Formatters.count(entries.count, "file", "files") let label = entries.count == 1 ? "Discard ‘\(name)’" : "Discard \(name)" let message = "Before discarding " + (entries.count == 1 ? name : Formatters.count(entries.count, "file", "files")) perform(.working("Discarding \(name)…"), trigger: keepingStaged ? "Discard Unstaged Changes" : "Discard Changes") { [weak self] repository in - let record = try await repository.discard(paths: paths, untracked: untracked, keepingStaged: keepingStaged, message: message) + let record = try await repository.discard(paths: paths, keepingStaged: keepingStaged, message: message) self?.record(.discarded(label: label, record: record, message: message), toast: "Discarded changes to \(name) · Kaern kept a copy in Stashes") } } + /// Restore Version at…: the file as that version has it, in the working copy and unstaged (what's staged is + /// HEAD's). Its own changes go to Stashes first, as Discard keeps them, and ⌘Z puts the file back as it was. + func restoreVersion(_ version: (commit: String, path: String)) { + let name = (version.path as NSString).lastPathComponent + let short = String(version.commit.prefix(7)) + let label = "Restore ‘\(name)’" + let message = "Before restoring \(name) from \(short)" + perform(.working("Restoring \(name)…"), trigger: "Restore Version at \(short)") { [weak self] repository in + let restore = try await repository.restoreVersion(of: version.path, at: version.commit, message: message) + self?.record(.restoredVersion(label: label, restore: restore, message: message), + toast: "Restored \(name) from \(short)" + (restore.record == nil ? "" : " · Kaern kept your changes in Stashes")) + } + } + /// Adds a pattern to `.gitignore`; ⌘Z puts the file back. func ignore(pattern: String) { let before = Set(status.entries.map(\.path)) diff --git a/Kaern/Repository/RepositoryModel+Fetch.swift b/Kaern/Repository/RepositoryModel+Fetch.swift index 8f2bc20..1463d25 100644 --- a/Kaern/Repository/RepositoryModel+Fetch.swift +++ b/Kaern/Repository/RepositoryModel+Fetch.swift @@ -31,9 +31,12 @@ extension RepositoryModel { guard !(error is CancellationError) else { return } let gitError = error as? GitError let failure = gitError.flatMap { GitFailure.explain(arguments: $0.arguments, errorOutput: $0.message, status: $0.status) } + if failure == .promptCancelled { return } fetchProblem = FetchProblem(failure: failure, remote: defaultRemote ?? "origin", message: error.localizedDescription, date: .now) - if case .signIn = failure { autoFetchPaused = true } - if case .sshKey = failure { autoFetchPaused = true } + switch failure { + case .signIn, .sshKey, .sshKeyLocked, .hostKeyUnknown, .hostKeyChanged: autoFetchPaused = true + default: break + } } /// The host of the default remote ("github.com"), for Sign In. diff --git a/Kaern/Repository/RepositoryModel+Undo.swift b/Kaern/Repository/RepositoryModel+Undo.swift index 2103b31..4b23701 100644 --- a/Kaern/Repository/RepositoryModel+Undo.swift +++ b/Kaern/Repository/RepositoryModel+Undo.swift @@ -238,6 +238,21 @@ nonisolated extension ReversibleStep { } } + /// Delete (a tag): ⌘Z makes it again with the object it had; ⌘⇧Z deletes it again while it's still that one. + static func deletedTag(name: String, object: String) -> ReversibleStep { + let label = "Delete Tag \(name)" + return ReversibleStep(label: label) { repository in + try await repository.restoreTag(name, object: object) + return ReversibleStep(label: label) { repository in + guard await repository.resolve("refs/tags/\(name)") == object else { + throw UndoRefusal(message: "The tag \(name) changed since, so Kaern won’t delete it again.") + } + try await repository.deleteTag(name) + return deletedTag(name: name, object: object) + } + } + } + /// Reset Branch to Here. Soft and Mixed keep the changes; Hard stashed them first, and Undo /// puts them back after moving the branch back. static func reset(label: String, branch: String?, from: String, to: String, mode: GitRepository.ResetMode, @@ -316,6 +331,18 @@ nonisolated extension ReversibleStep { } } + /// Restore Version at…: ⌘Z takes the version back while the file is still it, then puts its own changes back; + /// ⇧⌘Z restores the version again (keeping whatever the file has by then). + static func restoredVersion(label: String, restore: VersionRestore, message: String) -> ReversibleStep { + ReversibleStep(label: label) { repository in + try await repository.undoRestore(restore) + return ReversibleStep(label: label) { repository in + let again = try await repository.restoreVersion(of: restore.path, at: restore.commit, message: message) + return restoredVersion(label: label, restore: again, message: message) + } + } + } + static func discardedLines(label: String, path: String, patch: String, stash: String?, message: String) -> ReversibleStep { ReversibleStep(label: label) { repository in try await repository.restoreDiscardedLines(patch) diff --git a/Kaern/Repository/RepositoryModel.swift b/Kaern/Repository/RepositoryModel.swift index b9082cd..c3dd7fb 100644 --- a/Kaern/Repository/RepositoryModel.swift +++ b/Kaern/Repository/RepositoryModel.swift @@ -289,7 +289,9 @@ final class RepositoryModel: Identifiable { /// Review mode: the center shows the selection's diff instead of the graph (`nil`: graph). var review: ReviewState? { didSet { - reviewInputs += 1 + // Of Review's state the files are made from the compare alone: showing another file, or one file + // instead of all, makes no new ones. + if review?.compare != oldValue?.compare { reviewInputs += 1 } if review != nil, screen != nil { screen = nil } if review?.compare != oldValue?.compare { diffsAreStale = true @@ -1520,6 +1522,10 @@ final class RepositoryModel: Identifiable { } catch is CancellationError { // Stopped on purpose. center.finish(taskID, result: "Stopped") + } catch let error as GitError where GitFailure.explain(arguments: error.arguments, errorOutput: error.message, + status: error.status) == .promptCancelled { + // You cancelled what Kaern asked for ssh (a passphrase, a new host). + center.finish(taskID, result: "Cancelled") } catch { let failure = (error as? GitError).flatMap { GitFailure.explain(arguments: $0.arguments, errorOutput: $0.message, status: $0.status) } center.finish(taskID, result: error.localizedDescription, failure: failure, failed: true) diff --git a/Kaern/Settings/AppSettings.swift b/Kaern/Settings/AppSettings.swift index b62e841..4acc0c9 100644 --- a/Kaern/Settings/AppSettings.swift +++ b/Kaern/Settings/AppSettings.swift @@ -55,6 +55,7 @@ nonisolated enum SettingsKey { // Diff static let diffContext = "KaernDiffContext" static let diffWords = "KaernDiffWords" + static let diffSyntax = "KaernDiffSyntax" static let diffWrap = "KaernDiffWrap" /// Repositories (paths) whose Git LFS files download when opened (ScreenMarks › Always Download). static let lfsAlwaysDownload = "KaernLFSAlwaysDownload" @@ -161,6 +162,7 @@ enum AppSettings { } static var diffWords: Bool { store.object(forKey: SettingsKey.diffWords) as? Bool ?? true } + static var diffSyntax: Bool { store.object(forKey: SettingsKey.diffSyntax) as? Bool ?? true } static var usesSSHAgent: Bool { store.object(forKey: SettingsKey.sshAgent) as? Bool ?? true } static var watchesFiles: Bool { store.object(forKey: SettingsKey.watchFiles) as? Bool ?? true } diff --git a/Kaern/Settings/SettingsWindow.swift b/Kaern/Settings/SettingsWindow.swift index 6ceb8b0..3e10956 100644 --- a/Kaern/Settings/SettingsWindow.swift +++ b/Kaern/Settings/SettingsWindow.swift @@ -960,6 +960,7 @@ private struct DiffPane: View { @AppStorage(DiffPreferences.layoutKey, store: .kaern) private var layout = DiffLayout.split @AppStorage(SettingsKey.diffContext, store: .kaern) private var context = 3 @AppStorage(SettingsKey.diffWords, store: .kaern) private var words = true + @AppStorage(SettingsKey.diffSyntax, store: .kaern) private var syntax = true @AppStorage(SettingsKey.diffWrap, store: .kaern) private var wraps = true @AppStorage(DiffPreferences.ignoreWhitespaceKey, store: .kaern) private var ignoresWhitespace = false @AppStorage(SettingsKey.diffFontName, store: .kaern) private var fontName = "" @@ -988,6 +989,7 @@ private struct DiffPane: View { SettingsRow(label: "Display:") { VStack(alignment: .leading, spacing: 0) { Checkbox("Highlight the changed words in a line", isOn: $words) + Checkbox("Color the code: keywords, strings, comments", isOn: $syntax) Checkbox("Wrap long lines", isOn: $wraps) Checkbox("Ignore whitespace-only changes", isOn: $ignoresWhitespace) } @@ -1151,6 +1153,7 @@ private struct AdvancedPane: View { if sshAgent != launchSSHAgent { Hint("Applies the next time Kaern opens.") } + SavedPassphrasesRow() } SettingsRow(label: "File changes:") { Checkbox("Refresh as soon as files change on disk", isOn: $watchFiles) @@ -1241,3 +1244,26 @@ enum Relauncher { NSApp.terminate(nil) } } + +/// Settings › Advanced › SSH: what Kaern does when ssh asks for a key's passphrase, the keys whose passphrase it +/// remembers in your Keychain (`SSHPassphrases`), and Forget. +private struct SavedPassphrasesRow: View { + @State private var keys: [String] = [] + + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: z(8)) { + Hint(keys.isEmpty + ? "When ssh asks for a key’s passphrase or about a new server, Kaern asks you, and can remember the passphrase in your Keychain." + : "Kaern remembers the passphrase of " + keys.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ") + + " in your Keychain.") + if !keys.isEmpty { + Button("Forget") { + SSHPassphrases.forgetAll() + keys = SSHPassphrases.keys + } + .controlSize(.small) + } + } + .onAppear { keys = SSHPassphrases.keys } + } +} diff --git a/Kaern/Views/CommandLog/CommandLogWindow.swift b/Kaern/Views/CommandLog/CommandLogWindow.swift index 63675fd..d5b5bdd 100644 --- a/Kaern/Views/CommandLog/CommandLogWindow.swift +++ b/Kaern/Views/CommandLog/CommandLogWindow.swift @@ -391,7 +391,8 @@ private struct CommandDetail: View { meta("Triggered by", record.trigger.map { $0.action + ($0.isBackground ? " (background)" : "") } ?? "Kaern (background)") meta("Exit code", record.status.map { String($0) + (record.wasStopped ? " · stopped" : "") } ?? "—") meta("Git", AppModel.shared.git.map { ($0.version ?? "?") + " · " + $0.url.path(percentEncoded: false) } ?? "—") - meta("Environment", "GIT_TERMINAL_PROMPT=0 · GIT_OPTIONAL_LOCKS=0 · LC_ALL=en_US.UTF-8 · GIT_EDITOR=true") + meta("Environment", "GIT_TERMINAL_PROMPT=0 · GIT_OPTIONAL_LOCKS=0 · LC_ALL=en_US.UTF-8 · GIT_EDITOR=true" + + (record.usedLoginPath ? " · PATH from your login shell" : "")) if record.hasInput { meta("Input", "Sent on standard input (a message or a patch), not kept") } } .padding(.top, z(14)) diff --git a/Kaern/Views/Common/PlainPress.swift b/Kaern/Views/Common/PlainPress.swift new file mode 100644 index 0000000..d89caec --- /dev/null +++ b/Kaern/Views/Common/PlainPress.swift @@ -0,0 +1,46 @@ +import SwiftUI + +/// Makes a view act as the label of a plain button without a `Button` around it: held down it dims as that label +/// does, letting go over it runs the action, letting go elsewhere doesn't, and disabled it is dimmed and takes no +/// press. +/// +/// For buttons in lists that scroll. A `Button` takes part in the window's keyboard focus order, and each one that +/// comes into a lazy list or leaves it has SwiftUI work that order out again over every control in the window: a +/// diff of many small hunks spent a quarter of its scrolling on the hunks' buttons, All Files a quarter on the file +/// headers'. The price: these aren't stops of Full Keyboard Access's Tab. VoiceOver has them as buttons. +private struct PlainPress: ViewModifier { + /// The view's size: the pointer has to be over it still when it's let go. + let size: CGSize + let action: () -> Void + @Environment(\.isEnabled) private var isEnabled + /// The pointer is down on it, and still over it. + @GestureState private var isPressed = false + + func body(content: Content) -> some View { + content + .contentShape(Rectangle()) + // A plain button's label: three quarters while pressed, half when disabled. + .opacity(isEnabled ? (isPressed ? 0.75 : 1) : 0.5) + .gesture(press, isEnabled: isEnabled) + .accessibilityElement(children: .combine) + .accessibilityAddTraits(.isButton) + .accessibilityAction { if isEnabled { action() } } + } + + private var press: some Gesture { + let bounds = CGRect(origin: .zero, size: size) + return DragGesture(minimumDistance: 0) + .updating($isPressed) { value, pressed, _ in pressed = bounds.contains(value.location) } + .onEnded { value in + if bounds.contains(value.location) { action() } + } + } +} + +extension View { + /// The view acts as a plain button's label (`PlainPress`). `size`: the view's own, for telling whether the + /// pointer is still over it. + func plainPress(size: CGSize, action: @escaping () -> Void) -> some View { + modifier(PlainPress(size: size, action: action)) + } +} diff --git a/Kaern/Views/Explore/ExploreViews.swift b/Kaern/Views/Explore/ExploreViews.swift index 922a722..09f3c1d 100644 --- a/Kaern/Views/Explore/ExploreViews.swift +++ b/Kaern/Views/Explore/ExploreViews.swift @@ -8,6 +8,9 @@ struct ExploreView: View { @Bindable var repository: RepositoryModel @AppStorage(DiffPreferences.layoutKey, store: .kaern) private var layout = DiffLayout.split @AppStorage(SettingsKey.diffWords, store: .kaern) private var words = true + @AppStorage(SettingsKey.diffSyntax, store: .kaern) private var syntax = true + /// The rows of the version shown, kept from one pass to the next (`DiffRowCache`). + @State private var rowCache = DiffRowCache(capacity: 4) var body: some View { VStack(spacing: 0) { @@ -166,7 +169,7 @@ struct ExploreView: View { if let file = repository.historyReviewFile, repository.fileHistoryDiff?.key.hasPrefix((state.selected ?? "") + ":") == true { ScrollView { LazyVStack(spacing: 0) { - ForEach(DiffRowItem.rows(for: file, layout: layout, limit: 4_000, words: words)) { item in + ForEach(rowCache.rows(for: file, layout: layout, limit: 4_000, words: words, syntax: syntax)) { item in DiffRowView(item: item, repository: repository) } } diff --git a/Kaern/Views/Menus/ContextMenus.swift b/Kaern/Views/Menus/ContextMenus.swift index 332d863..fb65a72 100644 --- a/Kaern/Views/Menus/ContextMenus.swift +++ b/Kaern/Views/Menus/ContextMenus.swift @@ -410,6 +410,11 @@ enum ContextMenus { if let release { NSWorkspace.shared.open(release) } }) menu.addItem(.separator()) + menu.addItem(item("Delete", key: "\u{8}", enabled: idle) { r.from("Tag menu") { r.deleteTag(name) } }) + menu.addItem(item("Delete Here and on \(remote ?? "origin")…", hint: remote == nil ? "No remote" : nil, enabled: idle && remote != nil) { + r.from("Tag menu") { r.deleteTagEverywhere(name) } + }) + menu.addItem(.separator()) menu.addItem(item("Copy Tag Name") { r.copy(name, toast: "Copied \(name)") }) return menu } @@ -501,6 +506,9 @@ enum ContextMenus { menu.addItem(item("Blame at \(String(version.commit.prefix(7)))") { r.showBlame(version.path, at: version.commit) }) menu.addItem(.separator()) openItems(opening, r).forEach(menu.addItem) + menu.addItem(item("Restore Version at \(String(version.commit.prefix(7)))", enabled: r.activity == nil) { + r.from("Commit file menu") { r.restoreVersion(version) } + }) let file = r.existingFile(path) menu.addItem(item("Show in Finder", enabled: file != nil) { if let file { OpenIn.reveal(file) } }) menu.addItem(item("Copy Path") { r.copy(path, toast: "Copied \(path)") }) diff --git a/Kaern/Views/Review/DiffViews.swift b/Kaern/Views/Review/DiffViews.swift index 571c48a..e6873b5 100644 --- a/Kaern/Views/Review/DiffViews.swift +++ b/Kaern/Views/Review/DiffViews.swift @@ -191,36 +191,40 @@ typealias WordMarks = [Range] /// One line of a rendered diff (flattened, so a long file scrolls lazily). enum DiffRowItem: Identifiable { case header(ReviewHunk) - case unified(String, DiffLine, ReviewHunk, marks: WordMarks?) - case split(String, left: DiffLine?, right: DiffLine?, hunk: ReviewHunk, leftMarks: WordMarks?, rightMarks: WordMarks?) + case unified(String, DiffLine, ReviewHunk, marks: WordMarks?, syntax: HunkSyntax?) + case split(String, left: DiffLine?, right: DiffLine?, hunk: ReviewHunk, leftMarks: WordMarks?, rightMarks: WordMarks?, + syntax: HunkSyntax?) case note(String, String) case more(String, hidden: Int) var id: String { switch self { case .header(let hunk): "h:" + hunk.id - case .unified(let id, _, _, _), .split(let id, _, _, _, _, _), .note(let id, _), .more(let id, _): id + case .unified(let id, _, _, _, _), .split(let id, _, _, _, _, _, _), .note(let id, _), .more(let id, _): id } } /// Rows of one file: at most `limit` rows of lines, and a "Show More" row for the rest. - /// `words`: mark the changed words of edited lines. - static func rows(for file: ReviewFile, layout: DiffLayout, limit: Int, words: Bool = false) -> [DiffRowItem] { + /// `words`: mark the changed words of edited lines. `syntax`: color the code by its language (each row carries + /// where to ask for its colors, `HunkSyntax`: they're worked out when the row is drawn). + static func rows(for file: ReviewFile, layout: DiffLayout, limit: Int, words: Bool = false, syntax: Bool = false) -> [DiffRowItem] { if let note = file.note { return [.note(file.path + ":note", note)] } var rows: [DiffRowItem] = [] var budget = limit var consumed = 0 let total = file.hunks.reduce(0) { $0 + $1.hunk.lines.count } + let language = syntax && file.special == nil ? SyntaxHighlighter.language(forPath: file.path) : nil hunks: for hunk in file.hunks { guard budget > 0 else { break } rows.append(.header(hunk)) let prefix = hunk.id + ":" let marks = words ? InlineDiff.highlights(for: hunk.hunk.lines.map { ($0.id, $0.kind, $0.text) }) : [:] + let code = language.map { HunkSyntax(hunk.hunk.lines, in: $0) } switch layout { case .unified: for line in hunk.hunk.lines { guard budget > 0 else { break hunks } - rows.append(.unified(prefix + "\(line.id)", line, hunk, marks: marks[line.id])) + rows.append(.unified(prefix + "\(line.id)", line, hunk, marks: marks[line.id], syntax: code)) budget -= 1 consumed += 1 } @@ -234,7 +238,8 @@ enum DiffRowItem: Identifiable { let left = row < deletions.count ? deletions[row] : nil let right = row < additions.count ? additions[row] : nil rows.append(.split(prefix + "p\(index)", left: left, right: right, hunk: hunk, - leftMarks: left.flatMap { marks[$0.id] }, rightMarks: right.flatMap { marks[$0.id] })) + leftMarks: left.flatMap { marks[$0.id] }, rightMarks: right.flatMap { marks[$0.id] }, + syntax: code)) index += 1 budget -= 1 consumed += (left == nil ? 0 : 1) + (right == nil ? 0 : 1) @@ -249,7 +254,8 @@ enum DiffRowItem: Identifiable { case .context: flush() guard budget > 0 else { break hunks } - rows.append(.split(prefix + "p\(index)", left: line, right: line, hunk: hunk, leftMarks: nil, rightMarks: nil)) + rows.append(.split(prefix + "p\(index)", left: line, right: line, hunk: hunk, leftMarks: nil, rightMarks: nil, + syntax: code)) index += 1 budget -= 1 consumed += 1 @@ -267,6 +273,99 @@ enum DiffRowItem: Identifiable { } } +/// The colored code of a hunk's lines, worked out when a row of the hunk is drawn, and then only as far down the +/// hunk as that row: the rows of a whole file are made to show the screenful that fits, and coloring all of them +/// first is what kept a big file from showing at once. +/// +/// The old side (unchanged and deleted lines) and the new side (unchanged and added lines) are each read in order, +/// so a comment or string carries over lines removed or added on the other side. Unchanged lines take the new side's. +final class HunkSyntax { + private let lines: [DiffLine] + private let language: SyntaxLanguage + /// The two sides, and where each line of the hunk is in the side it takes its colors from. Made at the first ask. + private var sides: (old: SyntaxLines, new: SyntaxLines, places: [Int])? + + init(_ lines: [DiffLine], in language: SyntaxLanguage) { + self.lines = lines + self.language = language + } + + /// The colored pieces of `line`, one of the hunk's. + func spans(of line: DiffLine) -> [SyntaxSpan]? { + guard line.kind != .noNewline, let index = index(of: line) else { return nil } + if sides == nil { sides = makeSides() } + let place = sides!.places[index] + return line.kind == .deletion ? sides!.old.spans(at: place) : sides!.new.spans(at: place) + } + + /// A line's id is its position in its hunk (`DiffLine.id`); looked up only if it ever isn't. + private func index(of line: DiffLine) -> Int? { + lines.indices.contains(line.id) && lines[line.id].id == line.id ? line.id : lines.firstIndex { $0.id == line.id } + } + + private func makeSides() -> (old: SyntaxLines, new: SyntaxLines, places: [Int]) { + var old: [String] = [], new: [String] = [] + var places = [Int](repeating: 0, count: lines.count) + for (index, line) in lines.enumerated() { + switch line.kind { + case .context: + places[index] = new.count + old.append(line.text) + new.append(line.text) + case .addition: + places[index] = new.count + new.append(line.text) + case .deletion: + places[index] = old.count + old.append(line.text) + case .noNewline: + break + } + } + return (SyntaxLines(old, in: language), SyntaxLines(new, in: language), places) + } +} + +/// The rows of the files a diff view shows, kept while the file, the layout and the limits stay the same: the diff +/// of a file is cut into rows (its edited lines compared word by word) once, not on every pass of the view, and the +/// colors a row has asked for (`HunkSyntax`) stay with it. +final class DiffRowCache { + private var entries: [String: (file: ReviewFile, layout: DiffLayout, limit: Int, words: Bool, syntax: Bool, rows: [DiffRowItem])] = [:] + /// How many files' rows it keeps: all of them are dropped when one more comes. + private let capacity: Int + + init(capacity: Int = 400) { + self.capacity = capacity + } + + func rows(for file: ReviewFile, layout: DiffLayout, limit: Int, words: Bool, syntax: Bool) -> [DiffRowItem] { + if let entry = entries[file.path], entry.layout == layout, entry.limit == limit, entry.words == words, entry.syntax == syntax, + entry.file == file { + return entry.rows + } + let rows = DiffRowItem.rows(for: file, layout: layout, limit: limit, words: words, syntax: syntax) + if entries[file.path] == nil, entries.count >= capacity { entries.removeAll() } + entries[file.path] = (file, layout, limit, words, syntax, rows) + return rows + } +} + +extension SyntaxKind { + /// Its color in a diff (`K.syn…`). + var color: Color { + switch self { + case .keyword, .constant: K.synKeyword + case .string: K.synString + case .comment: K.synComment + case .number: K.synNumber + case .type, .tag: K.synType + case .function, .property: K.synFunction + case .attribute, .variable: K.synAttribute + case .preprocessor: K.synPreprocessor + } + } +} + // MARK: - Rows /// Line picking in one working-copy file of Review: which lines can be picked and what a click does. @@ -299,10 +398,11 @@ struct DiffRowView: View { switch item { case .header(let hunk): HunkHeaderRow(hunk: hunk, repository: repository) - case .unified(_, let line, let hunk, let marks): - UnifiedLineRow(line: line, hunk: hunk, picking: picking, marks: marks) - case .split(_, let left, let right, let hunk, let leftMarks, let rightMarks): - SplitLineRow(left: left, right: right, hunk: hunk, picking: picking, leftMarks: leftMarks, rightMarks: rightMarks) + case .unified(_, let line, let hunk, let marks, let syntax): + UnifiedLineRow(line: line, hunk: hunk, picking: picking, marks: marks, syntax: syntax?.spans(of: line)) + case .split(_, let left, let right, let hunk, let leftMarks, let rightMarks, let syntax): + SplitLineRow(left: left, right: right, hunk: hunk, picking: picking, leftMarks: leftMarks, rightMarks: rightMarks, + leftSyntax: left.flatMap { syntax?.spans(of: $0) }, rightSyntax: right.flatMap { syntax?.spans(of: $0) }) case .note(_, let text): Text(text) .font(.system(size: z(12))) @@ -359,7 +459,8 @@ private struct HunkHeaderRow: View { } } -/// `.hbtn`: Stage Hunk (outlined) or Unstage Hunk (filled, the hunk is staged). +/// `.hbtn`: Stage Hunk (outlined) or Unstage Hunk (filled, the hunk is staged). Not a `Button`: a diff of many +/// small hunks has one every few rows (`plainPress`). private struct HunkButton: View { let title: String let isOn: Bool @@ -367,24 +468,33 @@ private struct HunkButton: View { @Environment(\.isEnabled) private var isEnabled var body: some View { - Button(action: action) { - Text(title) - .font(.system(size: z(11.5), weight: .semibold)) - .foregroundStyle(isOn ? Color.white : K.accentText) - .padding(.horizontal, z(9)) - .frame(height: z(22)) - .background(RoundedRectangle(cornerRadius: z(6), style: .continuous).fill(isOn ? K.accent : K.content)) - .overlay { - if !isOn { - RoundedRectangle(cornerRadius: z(6), style: .continuous).strokeBorder(K.sepStrong, lineWidth: 0.5) - } + Text(title) + .font(.system(size: z(11.5), weight: .semibold)) + .foregroundStyle(isOn ? Color.white : K.accentText) + .padding(.horizontal, z(9)) + .frame(height: z(22)) + .background(RoundedRectangle(cornerRadius: z(6), style: .continuous).fill(isOn ? K.accent : K.content)) + .overlay { + if !isOn { + RoundedRectangle(cornerRadius: z(6), style: .continuous).strokeBorder(K.sepStrong, lineWidth: 0.5) } - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .opacity(isEnabled ? 1 : 0.5) - .fixedSize() + } + .plainPress(size: Self.size(of: title), action: action) + .opacity(isEnabled ? 1 : 0.5) + .fixedSize() + } + + /// The label's size: its text in the label's font, and the room around it. + private static func size(of title: String) -> CGSize { + let key = "\(title) \(z(1))" + if let size = sizes[key] { return size } + let text = NSAttributedString(string: title, attributes: [.font: NSFont.systemFont(ofSize: z(11.5), weight: .semibold)]) + let size = CGSize(width: text.size().width.rounded(.up) + z(9) * 2, height: z(22)) + sizes[key] = size + return size } + + private static var sizes: [String: CGSize] = [:] } /// Line text as shown: tabs as four spaces, no carriage return. @@ -397,45 +507,45 @@ nonisolated func displayText(_ text: String) -> String { /// `.dl`: old number, new number, (✓ staged), marker, text. A picked line gets the accent /// edge and tint (`.dl.lsel`). +/// +/// A line row is its text over one drawing (`DiffRowDrawing`). As views (numbers, marks, gutters and fills in nested +/// stacks, some forty a row) making and measuring the rows was most of what scrolling a diff cost. private struct UnifiedLineRow: View { let line: DiffLine let hunk: ReviewHunk let picking: LinePicking? var marks: WordMarks? + var syntax: [SyntaxSpan]? @Environment(\.diffStyle) private var style var body: some View { - let colors = DiffColors(kind: line.kind) let pick = picking?.pick(for: line, in: hunk) let picked = picking?.isPicked(pick) ?? false - HStack(alignment: .top, spacing: 0) { - LineNumber(number: line.oldNumber, width: 36, trailing: 10, gutter: colors.gutter, picked: picked) - LineNumber(number: line.newNumber, width: 36, trailing: 10, gutter: colors.gutter, picked: picked) - if picking != nil { - StagedMark(shows: hunk.stage == .staged && line.isChange) - } - Text(line.kind == .addition ? "+" : line.kind == .deletion ? "−" : "") - .foregroundStyle(line.kind == .addition ? K.add : K.del) - .frame(width: z(18)) + let metrics = DiffRowMetrics(split: false, marksColumn: picking != nil) + DiffRowLayout(metrics: metrics) { DiffLineText(text: line.kind == .noNewline ? "No newline at end of file" : line.text, kind: line.kind, - marks: marks, color: line.kind == .noNewline ? K.label2 : K.code) - .padding(.trailing, z(16)) + marks: marks, syntax: line.kind == .noNewline ? nil : syntax, color: line.kind == .noNewline ? K.label2 : K.code) } .font(style.font) .lineSpacing(style.lineSpacing) - .frame(minHeight: z(20)) - .background(picked ? K.accentSoft : colors.line) - .overlay(alignment: .leading) { if picked { K.accent.frame(width: z(3)) } } + .background { + DiffRowDrawing(metrics: metrics, font: style.font, + left: DiffRowDrawing.Side(kind: line.kind, old: line.oldNumber, new: line.newNumber, picked: picked, + staged: hunk.stage == .staged && line.isChange), + right: nil) + .equatable() + } .pickable(pick, picking: picking) } } -/// A line's text: wrapped or on one line (Settings › Diff › Wrap long lines), with its changed -/// words marked. On one line, the text scrolls sideways with the rest of the diff. +/// A line's text: wrapped or on one line (Settings › Diff › Wrap long lines), with its code colored and +/// its changed words marked. On one line, the text scrolls sideways with the rest of the diff. struct DiffLineText: View { let text: String let kind: DiffLine.Kind var marks: WordMarks? + var syntax: [SyntaxSpan]? var color: Color = K.code @Environment(\.diffStyle) private var style @Environment(\.diffSideScroll) private var side @@ -452,31 +562,42 @@ struct DiffLineText: View { .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) .clipped() .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { side.noteColumn(width: $0) } + } else if style.wraps { + // The row's layout gives the text its column's width, and takes the height it wraps to. + content + .foregroundStyle(color) } else { content .foregroundStyle(color) - .lineLimit(style.wraps ? nil : 1) + .lineLimit(1) .truncationMode(.tail) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity, alignment: .leading) - .help(style.wraps ? "" : text) + .help(text) } } private var content: Text { let shown = displayText(text) - guard let marks, !marks.isEmpty, kind == .addition || kind == .deletion else { return Text(shown) } + let words = kind == .addition || kind == .deletion ? marks ?? [] : [] + let code = syntax ?? [] + guard !words.isEmpty || !code.isEmpty else { return Text(shown) } var attributed = AttributedString(shown) - let characters = Array(shown) + let length = shown.count // Ranges count Characters of the raw text; tabs became four spaces. let offsets = Self.displayOffsets(text) - for range in marks { + func shownRange(_ range: Range) -> Range? { let lower = offsets[min(range.lowerBound, offsets.count - 1)] let upper = offsets[min(range.upperBound, offsets.count - 1)] - guard lower < upper, upper <= characters.count else { continue } + guard lower < upper, upper <= length else { return nil } let start = attributed.index(attributed.startIndex, offsetByCharacters: lower) - let end = attributed.index(attributed.startIndex, offsetByCharacters: upper) - attributed[start.. some View { - if let line { - let colors = DiffColors(kind: changed ? line.kind : .context) - let pick = changed ? picking?.pick(for: line, in: hunk) : nil - let picked = picking?.isPicked(pick) ?? false - HStack(alignment: .top, spacing: 0) { - LineNumber(number: number, width: 35, trailing: 9, gutter: colors.gutter, picked: picked) - if picking != nil { - StagedMark(shows: changed && hunk.stage == .staged) - } - DiffLineText(text: line.text, kind: changed ? line.kind : .context, marks: changed ? marks : nil) - .padding(.leading, picking == nil ? z(8) : z(2)) - .padding(.trailing, z(12)) +/// Where the pieces of a line row are: the design's sizes, at the zoom. +nonisolated private struct DiffRowMetrics: Equatable { + /// The old side and the new side next to each other (`false`: one line with both numbers). + let split: Bool + /// The row has the column of ✓ marks: a working-copy file whose lines can be picked. + let marksColumn: Bool + let numberWidth: CGFloat + let numberTrailing: CGFloat + let markWidth: CGFloat + /// Unified: the "+" or "−" before the text. + let markerWidth: CGFloat + let textLeading: CGFloat + let textTrailing: CGFloat + let minHeight: CGFloat + /// The accent edge of a picked line. + let pickedEdge: CGFloat + + init(split: Bool, marksColumn: Bool) { + self.split = split + self.marksColumn = marksColumn + numberWidth = z(split ? 35 : 36) + numberTrailing = z(split ? 9 : 10) + markWidth = marksColumn ? z(14) : 0 + markerWidth = split ? 0 : z(18) + textLeading = split ? (marksColumn ? z(2) : z(8)) : 0 + textTrailing = z(split ? 12 : 16) + minHeight = z(20) + pickedEdge = z(3) + } + + /// A split side has its own number, a unified line the old and the new one. + var numbers: Int { split ? 1 : 2 } + var numberCell: CGFloat { numberWidth + numberTrailing } + var textStart: CGFloat { CGFloat(numbers) * numberCell + markWidth + markerWidth + textLeading } + + /// A split row's sides share what the line between them leaves, half each, and each piece goes to the whole pixel + /// nearest to where that puts it, as the views did. On a width that leaves half a pixel over, the drawing gives + /// that pixel to the old side in every row, so the line between the sides is straight. (As a stack of two views, + /// the side whose text could stretch less took it: the line stepped a pixel left and right from row to row.) + func sideWidth(in width: CGFloat) -> CGFloat { split ? (width - 1) / 2 : width } + func sideX(_ side: Int, in width: CGFloat) -> CGFloat { side == 0 ? 0 : sideWidth(in: width) + 1 } + /// The room a side's text has. + func column(in width: CGFloat) -> CGFloat { max(0, sideWidth(in: width) - textStart - textTrailing) } +} + +/// What a view in a line row is: a side's text, or the area of a side that a click picks. +nonisolated private enum DiffRowPart: Equatable { + case text(Int) + case area(Int) +} + +nonisolated private struct DiffRowPartKey: LayoutValueKey { + static let defaultValue = DiffRowPart.text(0) +} + +/// Puts a line row's texts in their columns, from the top, and makes the row as tall as the taller one (20 pt of the +/// design at least). The texts are measured once each, at their column's width. +private struct DiffRowLayout: Layout { + let metrics: DiffRowMetrics + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + // A list gives the row its width; asked for its own, the row is as wide as its texts need. + let width = proposal.width ?? ownWidth(subviews) + let column = ProposedViewSize(width: metrics.column(in: width), height: nil) + var height = metrics.minHeight + for subview in subviews { + if case .text = subview[DiffRowPartKey.self] { height = max(height, subview.sizeThatFits(column).height) } + } + return CGSize(width: width, height: height) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + let column = ProposedViewSize(width: metrics.column(in: bounds.width), height: nil) + for subview in subviews { + switch subview[DiffRowPartKey.self] { + case .text(let side): + subview.place(at: CGPoint(x: bounds.minX + metrics.sideX(side, in: bounds.width) + metrics.textStart, y: bounds.minY), + anchor: .topLeading, proposal: column) + case .area(let side): + subview.place(at: CGPoint(x: bounds.minX + metrics.sideX(side, in: bounds.width), y: bounds.minY), anchor: .topLeading, + proposal: ProposedViewSize(width: metrics.sideWidth(in: bounds.width), height: bounds.height)) } - .frame(maxWidth: .infinity, minHeight: z(20), maxHeight: .infinity, alignment: .topLeading) - .background(picked ? K.accentSoft : colors.line) - .overlay(alignment: .leading) { if picked { K.accent.frame(width: z(3)) } } - .pickable(pick, picking: picking) - } else { - StripeFill() - .frame(maxWidth: .infinity, minHeight: z(20), maxHeight: .infinity) } } + + private func ownWidth(_ subviews: Subviews) -> CGFloat { + var widest: CGFloat = 0 + for subview in subviews { + if case .text = subview[DiffRowPartKey.self] { widest = max(widest, subview.sizeThatFits(.unspecified).width) } + } + let side = metrics.textStart + widest + metrics.textTrailing + return metrics.split ? side * 2 + 1 : side + } } -/// A line number in its gutter; bold accent on the accent tint when the line is picked. -struct LineNumber: View { - let number: Int? - let width: CGFloat - let trailing: CGFloat - let gutter: Color - let picked: Bool +/// The side of a split row that a click picks (the caller reads ⇧ and ⌘). +private struct PickArea: View { + let pick: LinePick + let picking: LinePicking var body: some View { - Text(number.map(String.init) ?? "") - .fontWeight(picked ? .bold : .regular) - .foregroundStyle(picked ? K.accentText : K.label2) - .frame(width: z(width), alignment: .trailing) - .padding(.trailing, z(trailing)) - .frame(maxHeight: .infinity, alignment: .top) - .background(picked ? K.accentSoft : gutter) + Color.clear + .contentShape(Rectangle()) + .onTapGesture { picking.pick(pick) } + .pointerStyle(.link) } } -/// `.lmk`: a ✓ on lines that are staged. -private struct StagedMark: View { - let shows: Bool +/// What a line row shows besides its text, in one drawing: the fill of each side, its gutter with the line number, +/// the ✓ of a staged line, a unified line's "+" or "−", the stripes of a side that has no line, the accent edge and +/// tint of a picked line, and the line between the two sides. Every piece is where the views it replaced were, to +/// the pixel (compared row by row when it was written: in each state, at several widths, light and dark). +private struct DiffRowDrawing: View, Equatable { + struct Side: Equatable { + /// Decides the colors: a split side that isn't the changed one is drawn as an unchanged line. + var kind: DiffLine.Kind + /// A split side's own number, or a unified line's old one. + var old: Int? + /// A unified line's new number. + var new: Int? + var picked: Bool + /// Shows the ✓. + var staged: Bool + } + + let metrics: DiffRowMetrics + let font: Font + let left: Side? + /// The new side of a split row. + let right: Side? var body: some View { - Text(shows ? "✓" : "") - .font(.system(size: z(10), weight: .heavy)) - .foregroundStyle(K.add) - .frame(width: z(14)) + Canvas { context, size in + draw(in: &context, size: size) + } + .accessibilityElement() + .accessibilityLabel(spoken) + } + + /// The numbers and the ✓, which were texts of their own: "Old line 14, new line 14, staged". + private var spoken: String { + var parts: [String] = [] + if let number = left?.old { parts.append("Old line \(number)") } + if let number = metrics.split ? right?.old : left?.new { parts.append("New line \(number)") } + if left?.staged == true || right?.staged == true { parts.append("staged") } + return parts.joined(separator: ", ") + } + + private func draw(in context: inout GraphicsContext, size: CGSize) { + // Views are placed on whole pixels: so is every piece here. + let scale = context.environment.displayScale + func snapped(_ value: CGFloat) -> CGFloat { (value * scale).rounded() / scale } + let sideWidth = metrics.sideWidth(in: size.width) + for (index, side) in [left, right].enumerated() where index == 0 || metrics.split { + let origin = metrics.sideX(index, in: size.width) + let minX = snapped(origin), maxX = snapped(origin + sideWidth) + let rect = CGRect(x: minX, y: 0, width: maxX - minX, height: size.height) + guard let side else { + stripes(in: &context, rect) + continue + } + let colors = DiffColors(kind: side.kind) + let isColored = side.picked || side.kind == .addition || side.kind == .deletion + if isColored { context.fill(Path(rect), with: .color(side.picked ? K.accentSoft : colors.line)) } + var x = origin + for number in metrics.split ? [side.old] : [side.old, side.new] { + if isColored { + let cell = CGRect(x: snapped(x), y: 0, width: snapped(x + metrics.numberCell) - snapped(x), height: size.height) + context.fill(Path(cell), with: .color(side.picked ? K.accentSoft : colors.gutter)) + } + if let number { + let text = context.resolve(Text(String(number)).font(font).fontWeight(side.picked ? .bold : .regular) + .foregroundStyle(side.picked ? K.accentText : K.label2)) + let width = text.measure(in: CGSize(width: CGFloat.infinity, height: .infinity)).width + if width <= metrics.numberWidth { + context.draw(text, at: CGPoint(x: snapped(x + metrics.numberWidth - width), y: 0), anchor: .topLeading) + } else { + // A number wider than its column (line 10,000 on, or a big font) is drawn narrower, clear of + // a picked line's edge. As a view it wrapped, and its row was two lines tall. + var narrow = context + narrow.translateBy(x: snapped(x + metrics.numberWidth), y: 0) + narrow.scaleBy(x: (metrics.numberWidth - metrics.pickedEdge - 1) / width, y: 1) + narrow.draw(text, at: .zero, anchor: .topTrailing) + } + } + x += metrics.numberCell + } + if metrics.marksColumn { + if side.staged { + centered(Text("✓").font(.system(size: z(10), weight: .heavy)).foregroundStyle(K.add), in: &context, + from: x, width: metrics.markWidth, snapped: snapped) + } + x += metrics.markWidth + } + if !metrics.split, side.kind == .addition || side.kind == .deletion { + centered(Text(side.kind == .addition ? "+" : "−").font(font).foregroundStyle(side.kind == .addition ? K.add : K.del), + in: &context, from: x, width: metrics.markerWidth, snapped: snapped) + } + if side.picked { + context.fill(Path(CGRect(x: minX, y: 0, width: snapped(origin + metrics.pickedEdge) - minX, height: size.height)), with: .color(K.accent)) + } + } + if metrics.split { + let x = snapped(sideWidth) + context.fill(Path(CGRect(x: x, y: 0, width: snapped(sideWidth + 1) - x, height: size.height)), with: .color(K.sep)) + } + } + + /// A short text in the middle of its column, at the top. + private func centered(_ text: Text, in context: inout GraphicsContext, from x: CGFloat, width: CGFloat, snapped: (CGFloat) -> CGFloat) { + let resolved = context.resolve(text) + let size = resolved.measure(in: CGSize(width: CGFloat.infinity, height: .infinity)) + context.draw(resolved, at: CGPoint(x: snapped(x + (width - size.width) / 2), y: 0), anchor: .topLeading) + } + + /// The side without a line: 5 pt diagonal stripes every 10 pt (`.sd.empty`). + private func stripes(in context: inout GraphicsContext, _ rect: CGRect) { + context.drawLayer { layer in + layer.clip(to: Path(rect)) + layer.translateBy(x: rect.minX, y: rect.minY) + let step: CGFloat = z(10) * 2.0.squareRoot() + var offset: CGFloat = -rect.height + var path = Path() + while offset < rect.width + rect.height { + path.move(to: CGPoint(x: offset, y: rect.height)) + path.addLine(to: CGPoint(x: offset + rect.height, y: 0)) + offset += step + } + layer.stroke(path, with: .color(K.emptyA), lineWidth: 5) + } } } diff --git a/Kaern/Views/Review/FileOpenButton.swift b/Kaern/Views/Review/FileOpenButton.swift index b1e55f0..0ba99e3 100644 --- a/Kaern/Views/Review/FileOpenButton.swift +++ b/Kaern/Views/Review/FileOpenButton.swift @@ -22,34 +22,29 @@ struct FileOpenButton: View { let enabled = file != nil || opening.version != nil let app = enabled ? OpenIn.app(forFile: file ?? URL(filePath: opening.path), chosen: editorID) : nil HStack(spacing: 0) { - Button { repository.open(opening, in: app) } label: { - Group { - if let app { - Image(nsImage: app.icon(16)).resizable().interpolation(.high) - } else { - Icon(Icons.file, size: 13).foregroundStyle(K.label3) - } + // Labels that act as plain buttons, not `Button`s: every file header of All Files has the two (`plainPress`). + Group { + if let app { + Image(nsImage: app.icon(16)).resizable().interpolation(.high) + } else { + Icon(Icons.file, size: 13).foregroundStyle(K.label3) } - .frame(width: z(15), height: z(15)) - .frame(width: z(26), height: z(24)) - .background(RoundedRectangle(cornerRadius: z(6), style: .continuous).fill(hovering && enabled ? K.hover : .clear)) - .contentShape(Rectangle()) } - .buttonStyle(.plain) + .frame(width: z(15), height: z(15)) + .frame(width: z(26), height: z(24)) + .background(RoundedRectangle(cornerRadius: z(6), style: .continuous).fill(hovering && enabled ? K.hover : .clear)) + .plainPress(size: CGSize(width: z(26), height: z(24))) { repository.open(opening, in: app) } .disabled(!enabled) .onHover { hovering = $0 } .help(app.map { "Open in \($0.name)" + (shortcut.map { " (\($0))" } ?? "") } ?? "\(opening.name) isn’t on disk") .accessibilityLabel(app.map { "Open \(opening.name) in \($0.name)" } ?? "\(opening.name) isn’t on disk") .debugFrame("openFile \(repository.path) \(opening.path)") - Button { showMenu() } label: { - Icon(Icons.chevronDown, size: 8) - .foregroundStyle(K.label2) - .frame(width: z(14), height: z(24)) - .background(RoundedRectangle(cornerRadius: z(6), style: .continuous).fill(menuHovering ? K.hover : .clear)) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .onHover { menuHovering = $0 } + Icon(Icons.chevronDown, size: 8) + .foregroundStyle(K.label2) + .frame(width: z(14), height: z(24)) + .background(RoundedRectangle(cornerRadius: z(6), style: .continuous).fill(menuHovering ? K.hover : .clear)) + .plainPress(size: CGSize(width: z(14), height: z(24))) { showMenu() } + .onHover { menuHovering = $0 } .help("Open In") .accessibilityLabel("Open \(opening.name) in another app") .debugFrame("openFileMenu \(repository.path) \(opening.path)") diff --git a/Kaern/Views/Review/FocusDrawer.swift b/Kaern/Views/Review/FocusDrawer.swift index ae98124..0766f18 100644 --- a/Kaern/Views/Review/FocusDrawer.swift +++ b/Kaern/Views/Review/FocusDrawer.swift @@ -11,7 +11,10 @@ struct FocusDrawer: View { let close: () -> Void @AppStorage(DiffPreferences.layoutKey, store: .kaern) private var layout = DiffLayout.split @AppStorage(SettingsKey.diffWords, store: .kaern) private var words = true + @AppStorage(SettingsKey.diffSyntax, store: .kaern) private var syntax = true @State private var expanded: Set = [] + /// The rows of the files looked at, kept from one pass to the next (`DiffRowCache`). + @State private var rowCache = DiffRowCache(capacity: 12) /// The file list has keyboard focus: ↑ ↓ show the file above or below. @FocusState private var filesFocused: Bool @@ -46,7 +49,7 @@ struct FocusDrawer: View { ScrollView { LazyVStack(spacing: 0) { let limit = expanded.contains(current.path) ? Int.max : 2_000 - ForEach(DiffRowItem.rows(for: current, layout: layout, limit: limit, words: words)) { item in + ForEach(rowCache.rows(for: current, layout: layout, limit: limit, words: words, syntax: syntax)) { item in DiffRowView(item: item, repository: repository) { expanded.insert(current.path) } } } diff --git a/Kaern/Views/Review/ReviewView.swift b/Kaern/Views/Review/ReviewView.swift index 67d13e8..f578fec 100644 --- a/Kaern/Views/Review/ReviewView.swift +++ b/Kaern/Views/Review/ReviewView.swift @@ -8,6 +8,7 @@ struct ReviewView: View { @Bindable var repository: RepositoryModel @AppStorage(DiffPreferences.layoutKey, store: .kaern) private var layout = DiffLayout.split @AppStorage(SettingsKey.diffWords, store: .kaern) private var words = true + @AppStorage(SettingsKey.diffSyntax, store: .kaern) private var syntax = true /// Files whose "Show More Lines" was clicked: how many lines they show. @State private var limits: [String: Int] = [:] /// How many files All Files has rows for: the first ones, and more as the list is scrolled to @@ -124,7 +125,7 @@ struct ReviewView: View { if let special = file.special { SpecialFileView(file: file, special: special, repository: repository, inList: true) } else { - let rows = rowCache.rows(for: file, layout: layout, limit: limits[file.path] ?? Self.lineLimit, words: words) + let rows = rowCache.rows(for: file, layout: layout, limit: limits[file.path] ?? Self.lineLimit, words: words, syntax: syntax) let picking = picking(for: file) ForEach(rows) { item in DiffRowView(item: item, repository: repository, picking: picking) { @@ -473,21 +474,3 @@ struct LinePickBar: View { .fixedSize() } } - -/// The rows of the files Review shows, kept while the file, the layout and the limits stay the same: -/// the diff of a file is cut into rows (and its edited lines compared word by word) once, not on -/// every pass of the view. -@MainActor -private final class DiffRowCache { - private var entries: [String: (file: ReviewFile, layout: DiffLayout, limit: Int, words: Bool, rows: [DiffRowItem])] = [:] - - func rows(for file: ReviewFile, layout: DiffLayout, limit: Int, words: Bool) -> [DiffRowItem] { - if let entry = entries[file.path], entry.layout == layout, entry.limit == limit, entry.words == words, entry.file == file { - return entry.rows - } - let rows = DiffRowItem.rows(for: file, layout: layout, limit: limit, words: words) - if entries.count >= 400 { entries.removeAll() } - entries[file.path] = (file, layout, limit, words, rows) - return rows - } -} diff --git a/Kaern/Views/Stash/StashViews.swift b/Kaern/Views/Stash/StashViews.swift index 2156183..0754f5b 100644 --- a/Kaern/Views/Stash/StashViews.swift +++ b/Kaern/Views/Stash/StashViews.swift @@ -8,7 +8,10 @@ struct StashView: View { @Bindable var repository: RepositoryModel @AppStorage(DiffPreferences.layoutKey, store: .kaern) private var layout = DiffLayout.split @AppStorage(SettingsKey.diffWords, store: .kaern) private var words = true + @AppStorage(SettingsKey.diffSyntax, store: .kaern) private var syntax = true @State private var limits: [String: Int] = [:] + /// The rows of the stash's files, kept from one pass to the next (`DiffRowCache`). + @State private var rowCache = DiffRowCache() var body: some View { VStack(spacing: 0) { @@ -20,7 +23,7 @@ struct StashView: View { LazyVStack(spacing: 0, pinnedViews: [.sectionHeaders]) { ForEach(files) { file in Section { - let rows = DiffRowItem.rows(for: file, layout: layout, limit: limits[file.path] ?? 2_000, words: words) + let rows = rowCache.rows(for: file, layout: layout, limit: limits[file.path] ?? 2_000, words: words, syntax: syntax) ForEach(rows) { item in DiffRowView(item: item, repository: repository) { limits[file.path] = Int.max } } diff --git a/Packages/KaernKit/Sources/KaernKit/Git/CommitStream.swift b/Packages/KaernKit/Sources/KaernKit/Git/CommitStream.swift index daa64ef..48c2137 100644 --- a/Packages/KaernKit/Sources/KaernKit/Git/CommitStream.swift +++ b/Packages/KaernKit/Sources/KaernKit/Git/CommitStream.swift @@ -189,7 +189,7 @@ public final class CommitStream: @unchecked Sendable { let process = Process() process.executableURL = runner.executableURL process.arguments = GitRunner.baseArguments + arguments - process.environment = runner.environment + process.environment = runner.searchPath?.applied(to: runner.environment) ?? runner.environment process.currentDirectoryURL = directory let output = Pipe() let errors = Pipe() diff --git a/Packages/KaernKit/Sources/KaernKit/Git/GitAskpass.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitAskpass.swift new file mode 100644 index 0000000..cca2ef7 --- /dev/null +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitAskpass.swift @@ -0,0 +1,153 @@ +import Foundation + +/// How ssh asks Kaern what it would ask in a terminal: an SSH key's passphrase, whether to trust a host it hasn't +/// seen, a security key's PIN or touch. git starts ssh with no terminal, so ssh runs the program `SSH_ASKPASS` names +/// (`SSH_ASKPASS_REQUIRE=force`): Kaern's own, which hands the question to the running app over a Unix socket (with a +/// token) and prints the answer. Without it, ssh had no one to ask: a locked key and a new host failed, and Kaern +/// said the server didn't accept the key. +/// +/// A command Kaern runs on its own (auto-fetch, a refresh) is marked background: the app answers it only from what it +/// remembers (a saved passphrase), never with a window. git's own HTTPS questions ("Username for…") are turned down, +/// so they fail as before and Kaern offers Sign In. `core.askPass` and `GIT_ASKPASS`, when set, still come first. +public struct GitAskpass: Sendable, Hashable { + /// Kaern's executable, which acts as the asker when started with ``Key/socket`` set. + public var program: String + public var socket: String + public var token: String + + public init(program: String, socket: String, token: String) { + self.program = program + self.socket = socket + self.token = token + } + + /// The variables the asker reads. + public enum Key { + public static let socket = "KAERN_ASKPASS" + public static let token = "KAERN_ASKPASS_TOKEN" + /// What the user did ("Fetch", "Push"); empty for a background command. + public static let action = "KAERN_ASKPASS_ACTION" + /// The repository's folder. + public static let repository = "KAERN_ASKPASS_REPOSITORY" + } + + /// What the asker writes on ssh's standard error when it gives no answer (it ends up in git's), so a failure can + /// be told from a key the server turned down (`GitFailure`). + public enum Note { + public static let cancelled = "Kaern: cancelled." + public static let locked = "Kaern: the SSH key is locked, and Kaern asks for its passphrase only when you start the command." + public static let newHost = "Kaern: the server's host key isn't known yet, and Kaern asks about it only when you start the command." + } + + /// One command's variables. + func environment(trigger: GitCommandTrigger?, directory: URL?) -> [String: String] { + [ + "SSH_ASKPASS": program, + "SSH_ASKPASS_REQUIRE": "force", + Key.socket: socket, + Key.token: token, + Key.action: trigger.flatMap { $0.isBackground ? nil : $0.action } ?? "", + Key.repository: directory?.path(percentEncoded: false) ?? "", + ] + } +} + +/// Which ssh was given which passphrase for which key, a moment ago, and from that what to do when one asks: +/// ssh asks again when a passphrase didn't unlock the key (up to three times), so a second question from the same +/// ssh for the same key means the answer it got was wrong. +/// +/// Kept per ssh and per key. Two commands at once that use one key (a fetch in each of two tabs) ask in turn, and +/// with one note per key each one's question read as the other's first: a saved passphrase that no longer fits went +/// out again and again, and nobody was asked. And what an ssh was given is remembered (as a digest), so one that +/// was turned down with an old saved passphrase gets the new one saved since, and doesn't take that away. +public struct AskpassAttempts: Sendable { + public enum Step: Sendable, Equatable { + /// Answer with the saved passphrase. + case give(String) + /// Ask the user. `again`: this ssh was just given a passphrase that didn't unlock the key. `forget`: that + /// one is the saved one, which goes. + case ask(again: Bool, forget: Bool) + } + + private struct Asker: Hashable { + var key: String + var process: Int32 + } + + private var given: [Asker: (digest: Int, at: Date)] = [:] + /// How long after an answer the same ssh's question for the same key counts as asked again (a process number + /// comes round again only much later). + public var window: TimeInterval = 30 + + public init() {} + + /// What to do with `process` asking for `key`'s passphrase, `saved` being the one remembered for the key. + public mutating func next(key: String, process: Int32, saved: String?, at now: Date = Date()) -> Step { + let asker = Asker(key: key, process: process) + let last = given[asker].flatMap { now.timeIntervalSince($0.at) < window ? $0.digest : nil } + // A saved one this ssh hasn't just been turned down with: its first question, or another was saved since. + if let saved, last != Self.digest(saved) { + note(saved, asker, now) + return .give(saved) + } + return .ask(again: last != nil, forget: saved != nil) + } + + /// The user's answer went to `process` for `key`. + public mutating func answered(_ passphrase: String, key: String, process: Int32, at now: Date = Date()) { + note(passphrase, Asker(key: key, process: process), now) + } + + private mutating func note(_ passphrase: String, _ asker: Asker, _ now: Date) { + given = given.filter { now.timeIntervalSince($0.value.at) < window } + given[asker] = (Self.digest(passphrase), now) + } + + /// Enough to tell one passphrase from another for half a minute, without keeping it. + private static func digest(_ passphrase: String) -> Int { + var hasher = Hasher() + hasher.combine(passphrase) + return hasher.finalize() + } +} + +/// A question ssh asked, read from its prompt. +public enum AskpassQuestion: Sendable, Hashable { + /// "Enter passphrase for key '/Users/me/.ssh/id_ed25519': " + case passphrase(key: String) + /// "The authenticity of host 'github.com (140.82.112.3)' can't be established. ED25519 key fingerprint is …" + case newHost(host: String, keyType: String?, fingerprint: String?) + /// "Enter PIN for ED25519-SK key /Users/me/.ssh/id_ed25519_sk: " + case pin(key: String) + /// `SSH_ASKPASS_PROMPT=none`: "Confirm user presence for key …" — shown until ssh ends the asker. + case touch(message: String) + /// `SSH_ASKPASS_PROMPT=confirm`: a yes-or-no question (an agent's key confirmation). + case confirm(message: String) + /// git's own HTTPS question ("Username for 'https://github.com': "): turned down, Kaern signs in its own way. + case gitCredential(message: String) + /// Anything else ssh asks (a password, a one-time code), answered as typed. + case other(message: String) + + public static func read(prompt: String, mode: String?) -> AskpassQuestion { + let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines) + switch mode { + case "none": return .touch(message: text) + case "confirm": return .confirm(message: text) + default: break + } + if text.hasPrefix("Username for '") || text.hasPrefix("Password for '") { + return .gitCredential(message: text) + } + if let match = text.firstMatch(of: /Enter passphrase for (?:key )?['"](.+?)['"]/) { + return .passphrase(key: String(match.output.1)) + } + if let match = text.firstMatch(of: /The authenticity of host '([^' ]+)/) { + let key = text.firstMatch(of: /([A-Za-z0-9\-]+) key fingerprint is ([^\s]+?)\.?(?:\s|$)/) + return .newHost(host: String(match.output.1), keyType: key.map { String($0.output.1) }, fingerprint: key.map { String($0.output.2) }) + } + if let match = text.firstMatch(of: /Enter PIN for .*? key (.+?):?$/) { + return .pin(key: String(match.output.1)) + } + return .other(message: text) + } +} diff --git a/Packages/KaernKit/Sources/KaernKit/Git/GitCommandLog.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitCommandLog.swift index 5e6a545..6330568 100644 --- a/Packages/KaernKit/Sources/KaernKit/Git/GitCommandLog.swift +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitCommandLog.swift @@ -59,11 +59,14 @@ public struct GitCommandRecord: Sendable, Identifiable { public var isOutputCut: Bool /// Stopped by Kaern (Stop in the Command Log or the hook HUD, or a cancelled task). public var wasStopped: Bool + /// It ran with the login shell's PATH (`GitSearchPath`), not only Kaern's own. + public var usedLoginPath: Bool public init( id: UUID = UUID(), arguments: [String], directory: String, trigger: GitCommandTrigger?, started: Date, hasInput: Bool = false, status: Int32? = nil, duration: Duration? = nil, - output: String = "", errorOutput: String = "", isOutputCut: Bool = false, wasStopped: Bool = false + output: String = "", errorOutput: String = "", isOutputCut: Bool = false, wasStopped: Bool = false, + usedLoginPath: Bool = false ) { self.id = id self.arguments = arguments @@ -78,6 +81,7 @@ public struct GitCommandRecord: Sendable, Identifiable { self.errorOutput = errorOutput self.isOutputCut = isOutputCut self.wasStopped = wasStopped + self.usedLoginPath = usedLoginPath } public var isRunning: Bool { status == nil } diff --git a/Packages/KaernKit/Sources/KaernKit/Git/GitFailure.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitFailure.swift index cdfd725..223fbf1 100644 --- a/Packages/KaernKit/Sources/KaernKit/Git/GitFailure.swift +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitFailure.swift @@ -7,6 +7,14 @@ public enum GitFailure: Sendable, Hashable { case signIn(host: String?) /// The server didn't accept the SSH key. case sshKey(host: String?) + /// The SSH key needs its passphrase, and the command ran in the background, where Kaern doesn't ask. + case sshKeyLocked(host: String?) + /// ssh hasn't seen the server's host key yet, and nobody confirmed it (a background command). + case hostKeyUnknown(host: String?) + /// The server's host key isn't the one ssh knows for it. + case hostKeyChanged(host: String?) + /// You cancelled what Kaern asked for ssh (a passphrase, a new host): nothing went wrong. + case promptCancelled /// The server couldn't be reached (DNS, connection, timeout). case network(host: String?) /// Push refused: the remote has commits the branch doesn't. @@ -36,7 +44,19 @@ public enum GitFailure: Sendable, Hashable { || lower.contains("support for password authentication was removed") { return .signIn(host: host) } - if lower.contains("permission denied (publickey") || lower.contains("host key verification failed") { + if text.contains(GitAskpass.Note.cancelled) { + return .promptCancelled + } + if text.contains(GitAskpass.Note.locked) { + return .sshKeyLocked(host: host ?? Self.sshHost(in: text)) + } + if lower.contains("remote host identification has changed") || lower.contains("host key for ") && lower.contains(" has changed") { + return .hostKeyChanged(host: Self.changedHost(in: text) ?? host ?? Self.sshHost(in: text)) + } + if lower.contains("host key verification failed") || text.contains(GitAskpass.Note.newHost) { + return .hostKeyUnknown(host: host ?? Self.sshHost(in: text)) + } + if lower.contains("permission denied (publickey") { return .sshKey(host: host ?? Self.sshHost(in: text)) } if lower.contains("could not resolve host") || lower.contains("failed to connect to") || lower.contains("connection timed out") @@ -77,6 +97,11 @@ public enum GitFailure: Sendable, Hashable { return String(match.output.1) } + /// "github.com" in ssh's "Host key for github.com has changed and you have requested strict checking." + static func changedHost(in text: String) -> String? { + text.firstMatch(of: /Host key for \[?([A-Za-z0-9.\-]+)\]?(?::\d+)? has changed/).map { String($0.output.1) } + } + /// "github.com" in "git@github.com: Permission denied" or "ssh: connect to host github.com port 22". static func sshHost(in text: String) -> String? { if let match = text.firstMatch(of: /connect to host ([A-Za-z0-9.\-]+)/) { return String(match.output.1) } diff --git a/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Branches.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Branches.swift index faaf642..e6eac49 100644 --- a/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Branches.swift +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Branches.swift @@ -32,6 +32,17 @@ extension GitRepository { try await git(["push", "--progress", remote, "refs/tags/\(name)"], onProgress: onProgress) } + /// `git push --delete refs/tags/`, the tag named in full so a branch with its name stays. False + /// when the remote has no such tag: there was nothing to delete there. The remote is asked first (`ls-remote`), + /// because a push deleting a ref the remote doesn't have succeeds all the same. + @discardableResult + public func deleteRemoteTag(_ name: String, on remote: String, onProgress: (@Sendable (String) -> Void)? = nil) async throws -> Bool { + let advertised = try await git(["ls-remote", "--tags", remote, "refs/tags/\(name)"]).text + guard !advertised.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return false } + try await git(["push", "--progress", remote, "--delete", "refs/tags/\(name)"], onProgress: onProgress) + return true + } + /// Checks a new tag name with `git check-ref-format`. public func isValidTagName(_ name: String) async -> Bool { guard !name.isEmpty, let output = try? await git(["check-ref-format", "refs/tags/\(name)"], accepted: [0, 1, 128]) else { diff --git a/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Content.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Content.swift index 8e02d38..a4b01e1 100644 --- a/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Content.swift +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Content.swift @@ -87,7 +87,7 @@ extension GitRepository { /// content (`git lfs fetch`), so a commit that isn't checked out can show them. public func downloadLFS(_ paths: [String], at commit: String? = nil, remote: String = "origin", onProgress: (@Sendable (String) -> Void)? = nil) async throws { - guard runner.isLFSInstalled else { throw LFSNotInstalledError() } + guard runner.hasLFS else { throw LFSNotInstalledError() } // `--include` takes a comma-separated list; a comma in a name is escaped. let include = paths.map { $0.replacingOccurrences(of: ",", with: "\\,") }.joined(separator: ",") if let commit { @@ -101,7 +101,7 @@ extension GitRepository { extension GitRepository { /// Repository › Fetch LFS Files: every LFS file of the checked-out commit (`git lfs pull`). public func downloadAllLFS(onProgress: (@Sendable (String) -> Void)? = nil) async throws { - guard runner.isLFSInstalled else { throw LFSNotInstalledError() } + guard runner.hasLFS else { throw LFSNotInstalledError() } try await git(["lfs", "pull"], onProgress: onProgress) } } diff --git a/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Discard.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Discard.swift index ee261f3..7179dee 100644 --- a/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Discard.swift +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Discard.swift @@ -11,8 +11,12 @@ public struct DiscardRecord: Sendable, Hashable { public var staged: Data /// Index → working tree of the discarded tracked files. public var unstaged: Data - /// Untracked files that were deleted (their contents are in the stash's third parent). + /// Untracked and ignored files that were deleted (their contents are in the stash's third parent). public var untracked: [String] + /// Files a staged deletion had left on disk (`git rm --cached`, or a new file at a renamed one's old name). + /// Their contents are in the stash's working-tree part. Unless the staged part was kept, HEAD's file is at + /// these paths since, and ⌘Z's staged patch takes it away again before the file comes back. + public var leftOnDisk: [String] public var paths: [String] /// Only the unstaged part was discarded ("Discard Unstaged Changes"). public var keptStaged: Bool @@ -21,37 +25,85 @@ public struct DiscardRecord: Sendable, Hashable { extension GitRepository { /// Throws away the changes of `paths` after keeping a copy in the stash list (`message`). /// - /// - Parameters: - /// - untracked: The paths among `paths` git doesn't track; they're deleted. - /// - keepingStaged: Only the unstaged changes go; what's staged stays. - public func discard(paths: [String], untracked: [String], keepingStaged: Bool, message: String) async throws -> DiscardRecord { - let untrackedSet = Set(untracked) - let tracked = paths.filter { !untrackedSet.contains($0) } + /// What each path is comes from git here, not from the caller's list. `git status` says less than there can be: + /// a path is in it twice when a staged deletion left the file on disk (`git rm --cached`, or a new file at a + /// renamed one's old name), an ignored file isn't in it at all, and neither is what a folder in a deleted + /// file's place holds. `git restore` writes over all of those without a word, so a file the index doesn't + /// have is kept as a file of its own, and where something else would go, nothing is discarded. + /// + /// - Parameter keepingStaged: Only the unstaged changes go; what's staged stays. + public func discard(paths: [String], keepingStaged: Bool, message: String) async throws -> DiscardRecord { + let places = try await places(of: paths) + let tracked = paths.filter { places.head.contains($0) || places.index.contains($0) } + // What `git restore` writes: the index's files when the staged part stays, HEAD's otherwise. + let written = tracked.filter { (keepingStaged ? places.index : places.head).contains($0) } + // The patches hold what the index has of `paths`, so such a file can be in the way: it comes back. + let inPatches = Set(tracked).intersection(places.index) + for path in written { + if let obstacle = obstacle(toWriting: path, besides: inPatches) { + throw GitError(arguments: ["restore"], status: -1, message: obstacle) + } + } + // The files the index doesn't have: one HEAD has was left by a staged deletion, the others are untracked + // or ignored. + let leftOnDisk = paths.filter { places.loose.contains($0) && places.head.contains($0) } + let untracked = paths.filter { places.loose.contains($0) && !places.head.contains($0) } let staged = keepingStaged || tracked.isEmpty ? Data() : try await patch(paths: tracked, staged: true) let unstaged = tracked.isEmpty ? Data() : try await patch(paths: tracked, staged: false) let stash = try await snapshotStash(paths: paths, message: message, includeUntracked: !untracked.isEmpty) - if !tracked.isEmpty { - if keepingStaged { - try await discardUnstaged(tracked) - } else { - try await discardAll(tracked) - } + // git makes no stash before the first commit. + guard stash != nil || (untracked.isEmpty && leftOnDisk.isEmpty && staged.isEmpty && unstaged.isEmpty) else { + throw GitError(arguments: ["stash"], status: -1, + message: "Kaern can't keep a copy before the first commit, so it discarded nothing.") + } + if keepingStaged { + try await discardUnstaged(written) + } else { + // The files HEAD hasn't go first. A folder of them can be where one of HEAD's files was, and once + // git has put that file in the index, it finds no such paths there any more and stops. + try await discardAll(tracked.filter { !places.head.contains($0) }) + try await discardAll(written) } - for path in untracked { + // HEAD's file is at a staged deletion's path by now, unless the deletion stayed staged. + for path in untracked + (keepingStaged ? leftOnDisk : []) { try FileManager.default.removeItem(at: root.appending(path: path)) } - return DiscardRecord(stash: stash, staged: staged, unstaged: unstaged, untracked: untracked, paths: paths, - keptStaged: keepingStaged) + return DiscardRecord(stash: stash, staged: staged, unstaged: unstaged, untracked: untracked, leftOnDisk: leftOnDisk, + paths: paths, keptStaged: keepingStaged) + } + + /// Where git has each of `paths`: in HEAD, in the index, and on disk without being in the index (`loose`). + private func places(of paths: [String]) async throws -> (head: Set, index: Set, loose: Set) { + guard !paths.isEmpty else { return ([], [], []) } + let asked = Set(paths) + let literal = Self.literal(paths) + let index = Set(Records.splitNUL(try await git(["ls-files", "-z", "--"] + literal).stdout)).intersection(asked) + var head: Set = [] + if await resolve("HEAD") != nil { + head = Set(Records.splitNUL(try await git(["ls-tree", "-r", "-z", "--name-only", "HEAD", "--"] + literal).stdout)) + } + // The disk is asked for these, not `ls-files --others`: `git restore` writes to the file the disk finds at + // a path, which on a disk that takes `Config` and `config` for one name can be spelled another way by now. + let loose = asked.filter { + guard !index.contains($0), let type = Self.fileType(at: root.appending(path: $0)) else { return false } + return type != .typeDirectory + } + return (head.intersection(asked), index, loose) } /// Puts discarded changes back and drops the stash entry Discard made. public func restore(_ record: DiscardRecord) async throws { - let existing = record.untracked.filter { - FileManager.default.fileExists(atPath: root.appending(path: $0).path(percentEncoded: false)) - } - guard existing.isEmpty else { - throw GitError(arguments: ["restore"], status: -1, - message: "\(existing[0]) exists again, so Kaern can't put the discarded copy back.") + // Where Discard put HEAD's file itself, a file is there, and the staged patch takes it away. + let rewritten = record.keptStaged ? [] : Set(record.leftOnDisk) + for path in record.untracked + record.leftOnDisk { + // A link counts as there whatever it points to, so this doesn't follow one. + if !rewritten.contains(path), Self.fileType(at: root.appending(path: path)) != nil { + throw GitError(arguments: ["restore"], status: -1, + message: "\(path) exists again, so Kaern can't put the discarded copy back.") + } + if let obstacle = obstacle(toWriting: path) { + throw GitError(arguments: ["restore"], status: -1, message: obstacle) + } } if !record.staged.isEmpty { try await apply(patchData: record.staged, index: true) @@ -60,7 +112,10 @@ extension GitRepository { try await apply(patchData: record.unstaged) } if !record.untracked.isEmpty, let stash = record.stash { - try await git(["restore", "--source=\(stash)^3", "--worktree", "--"] + record.untracked.map { ":(literal)" + $0 }) + try await git(["restore", "--source=\(stash)^3", "--worktree", "--"] + Self.literal(record.untracked)) + } + if !record.leftOnDisk.isEmpty, let stash = record.stash { + try await git(["restore", "--source=\(stash)", "--worktree", "--"] + Self.literal(record.leftOnDisk)) } if let object = record.stash, let entry = await stash(withObject: object) { try await dropStash(entry) @@ -69,7 +124,7 @@ extension GitRepository { /// Discard again after ⌘Z (the same paths, as they are now). public func discardAgain(_ record: DiscardRecord, message: String) async throws -> DiscardRecord { - try await discard(paths: record.paths, untracked: record.untracked, keepingStaged: record.keptStaged, message: message) + try await discard(paths: record.paths, keepingStaged: record.keptStaged, message: message) } /// Keeps a copy of the changes of one file in the stash list, then throws away picked lines @@ -89,6 +144,113 @@ extension GitRepository { } } +// MARK: - Restore a file as a commit has it + +/// What Restore Version did to one file: what it took away first (`record`, nil when the file had no changes) and +/// the version it wrote, for ⌘Z. +public struct VersionRestore: Sendable, Hashable { + public var path: String + public var commit: String + /// The file's own changes, kept in the stash list as Discard keeps them. + public var record: DiscardRecord? + /// The version's blob: ⌘Z takes the file back only while it's still that. + public var blob: String +} + +extension GitRepository { + /// Puts the version `commit` has of `path` in the working tree, unstaged: the index keeps HEAD's. The file's own + /// changes go to the stash list first (`message`), as Discard keeps them. + public func restoreVersion(of path: String, at commit: String, message: String) async throws -> VersionRestore { + guard let blob = await resolve("\(commit):\(path)") else { + throw GitError(arguments: ["restore"], status: -1, message: "\(path) isn't in \(commit.prefix(7)).") + } + if let obstacle = obstacle(toWriting: path) { + throw GitError(arguments: ["restore"], status: -1, message: obstacle) + } + let status = try await git(["status", "--porcelain=v2", "-z", "--untracked-files=all", "--", ":(literal)" + path]) + // Two entries when a staged deletion left the file on disk: the deletion, and the file as an untracked one. + let entries = StatusParser.parse(status.stdout).entries.filter { $0.path == path } + guard !entries.contains(where: \.isConflicted) else { + throw GitError(arguments: ["restore"], status: -1, message: "\(path) has conflicts. Resolve them first.") + } + var keeps = !entries.isEmpty + if !keeps, Self.fileType(at: root.appending(path: path)) != nil { + // A file the index doesn't have and status didn't list: an ignored one (a config taken out of the + // repository, say). What's in it is the user's own, as an untracked file's is. + keeps = try await git(["ls-files", "-z", "--", ":(literal)" + path]).stdout.isEmpty + } + var record: DiscardRecord? + if keeps { + let paths = Set(entries.flatMap { [$0.path, $0.originalPath].compactMap { $0 } }).union([path]).sorted() + record = try await discard(paths: paths, keepingStaged: false, message: message) + } + try await git(["restore", "--source=\(commit)", "--worktree", "--", ":(literal)" + path]) + return VersionRestore(path: path, commit: commit, record: record, blob: blob) + } + + /// ⌘Z of Restore Version: the file as HEAD has it again (gone when HEAD hasn't it), then its own changes back. + /// Refused once the file isn't that version any more. + public func undoRestore(_ restore: VersionRestore) async throws { + guard await workingBlob(of: restore.path) == restore.blob else { + throw GitError(arguments: ["restore"], status: -1, + message: "\(restore.path) changed since, so Kaern won't take that version back.") + } + if await resolve("HEAD:\(restore.path)") != nil { + try await git(["restore", "--source=HEAD", "--staged", "--worktree", "--", ":(literal)" + restore.path]) + } else { + try await git(["rm", "--cached", "--quiet", "--ignore-unmatch", "--", ":(literal)" + restore.path]) + try FileManager.default.removeItem(at: root.appending(path: restore.path)) + } + if let record = restore.record { try await self.restore(record) } + } + + /// What is in the way of a file at `path`, as a sentence, `nil` when nothing is. `git restore` puts a file where + /// it's told whatever is there: a folder at the path goes with all that's in it, and a file or a link where one + /// of the path's folders has to be goes too, tracked or not, without a word. A folder with no file in it isn't + /// in the way, and neither is a file among `kept`, which the caller puts back itself. + private func obstacle(toWriting path: String, besides kept: Set = []) -> String? { + let parts = path.split(separator: "/").map(String.init) + var folder = "" + for part in parts.dropLast() { + folder += (folder.isEmpty ? "" : "/") + part + // Not there: git makes the folders. + guard let type = Self.fileType(at: root.appending(path: folder)) else { return nil } + if type != .typeDirectory { + return kept.contains(folder) ? nil : "\(folder) isn't a folder any more, and \(path) needs it to be one. Move it away first." + } + } + let place = root.appending(path: path).path(percentEncoded: false) + guard Self.fileType(at: root.appending(path: path)) == .typeDirectory, + let inside = FileManager.default.enumerator(atPath: place) else { return nil } + // Links aren't followed: one to a folder is a file here, as it is to git. + for case let name as String in inside { + let file = path + "/" + name + if Self.fileType(at: root.appending(path: file)) != .typeDirectory, !kept.contains(file) { + return "\(path) is a folder now. Move it away first." + } + } + return nil + } + + /// What is at `url` itself (a link isn't followed), `nil` when nothing is. + static func fileType(at url: URL) -> FileAttributeType? { + (try? FileManager.default.attributesOfItem(atPath: url.path(percentEncoded: false)))?[.type] as? FileAttributeType + } + + /// The blob the file in the working tree would be stored as, `nil` without one. A symbolic link's blob is where + /// it points, not what is there (which `git hash-object ` would read, or fail to for a link to nowhere). + private func workingBlob(of path: String) async -> String? { + let file = root.appending(path: path).path(percentEncoded: false) + let output: GitOutput? + if let target = try? FileManager.default.destinationOfSymbolicLink(atPath: file) { + output = try? await git(["hash-object", "--stdin"], input: Data(target.utf8)) + } else { + output = try? await git(["hash-object", "--path=\(path)", "--", path]) + } + return output?.text.trimmingCharacters(in: .whitespacesAndNewlines) + } +} + // MARK: - .gitignore /// A line added to the repository's `.gitignore`, with what the file held before (for ⌘Z). diff --git a/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Indicators.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Indicators.swift index ce225c5..58832a9 100644 --- a/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Indicators.swift +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Indicators.swift @@ -134,8 +134,11 @@ public struct LFSPointer: Sendable, Hashable { public var oid: String public var size: Int + /// How the line that makes a file a pointer starts. + static let versionPrefix = "version https://git-lfs.github.com/spec/" + public static func parse(_ lines: [String]) -> LFSPointer? { - guard lines.contains(where: { $0.hasPrefix("version https://git-lfs.github.com/spec/") }) else { return nil } + guard lines.contains(where: { $0.hasPrefix(versionPrefix) }) else { return nil } let oid = lines.first { $0.hasPrefix("oid ") }.map { String($0.dropFirst(4)) } ?? "" let size = lines.first { $0.hasPrefix("size ") }.flatMap { Int($0.dropFirst(5)) } ?? 0 return LFSPointer(oid: oid, size: size) @@ -145,6 +148,9 @@ public struct LFSPointer: Sendable, Hashable { extension FileDiff { /// The old and new pointers when the diff is of a file stored in Git LFS. public var lfsChange: (old: LFSPointer?, new: LFSPointer?)? { + // Nearly every diff is of something else: its lines are looked through for a pointer's first line before + // any are copied. Review asks this of each file it lists, twice, every time what it shows changes. + guard hunks.contains(where: { hunk in hunk.lines.contains { $0.text.hasPrefix(LFSPointer.versionPrefix) } }) else { return nil } let lines = hunks.flatMap(\.lines) let old = LFSPointer.parse(lines.filter { $0.kind != .addition }.map(\.text)) let new = LFSPointer.parse(lines.filter { $0.kind != .deletion }.map(\.text)) diff --git a/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Undo.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Undo.swift index c94daad..5e268bc 100644 --- a/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Undo.swift +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Undo.swift @@ -62,9 +62,11 @@ extension GitRepository { /// Keeps a copy of the changes of `paths` in the stash list without changing anything: the /// stash commit is built with a scratch index (`git stash store` adds it to the list), so the /// working tree and the index are never touched. Staged and unstaged changes of `paths` go - /// in like `git stash push -- ` would put them; with `includeUntracked`, untracked - /// files among `paths` go in the stash's third parent. Returns the stash's object name, - /// `nil` when there was nothing to keep. + /// in like `git stash push -- ` would put them; with `includeUntracked`, the untracked + /// and the ignored files among `paths` go in the stash's third parent. A file a staged deletion + /// left on disk (`git rm --cached`) is kept as a change to HEAD's file, in the working-tree part, + /// so the stash list shows the path once. Returns the stash's object name, `nil` when there was + /// nothing to keep. public func snapshotStash(paths: [String], message: String, includeUntracked: Bool) async throws -> String? { // The Command Log shows the `git stash store` under the action; the plumbing that builds // the entry is filed as that action's background work. @@ -81,43 +83,57 @@ extension GitRepository { private func snapshotCommit(paths: [String], message: String, includeUntracked: Bool) async throws -> (id: String, title: String)? { guard !paths.isEmpty, let head = await resolve("HEAD") else { return nil } let literal = paths.map { ":(literal)" + $0 } - let untracked = includeUntracked - ? Records.splitNUL(try await git(["ls-files", "-z", "--others", "--exclude-standard", "--"] + literal).stdout) - : [] - let untrackedSet = Set(untracked) - let tracked = paths.filter { !untrackedSet.contains($0) } let branch = await currentBranchName() ?? "(no branch)" let subject = (try? await git(["log", "-1", "--format=%h %s", head, "--"]).text.trimmingCharacters(in: .whitespacesAndNewlines)) ?? "" let scratch = gitDirectory.appending(path: "kaern-snapshot-\(UUID().uuidString).index") defer { try? FileManager.default.removeItem(at: scratch) } let env = ["GIT_INDEX_FILE": scratch.path(percentEncoded: false)] - // The index part: HEAD with the real index's entries for the tracked paths. try await git(["read-tree", head], environment: env) + // The files neither the index nor HEAD has. Without the standard excludes, `--others` lists the ignored + // ones too; only the paths themselves count, since under one that is a folder on disk it lists what the + // folder holds. A file HEAD has stays with the tracked ones below. + var untracked: [String] = [] + if includeUntracked { + let asked = Set(paths) + untracked = Records.splitNUL(try await git(["ls-files", "-z", "--others", "--"] + literal).stdout).filter { asked.contains($0) } + } + if !untracked.isEmpty { + // The scratch index is HEAD here. + let inHead = Set(Records.splitNUL(try await git(["ls-files", "-z", "--"] + untracked.map { ":(literal)" + $0 }, environment: env).stdout)) + untracked.removeAll { inHead.contains($0) } + } + let untrackedSet = Set(untracked) + + // The index part: HEAD with the real index's entries for the paths. One the index doesn't have leaves. var entries: [String] = [] var inIndex = Set() - if !tracked.isEmpty { - let staged = try await git(["ls-files", "-s", "-z", "--"] + tracked.map { ":(literal)" + $0 }).stdout - for record in Records.splitNUL(staged) { - // SP SP TAB - guard let tab = record.firstIndex(of: "\t") else { continue } - let fields = record[.. SP SP TAB + guard let tab = record.firstIndex(of: "\t") else { continue } + let fields = record[.. Void)? = nil ) { _ = GitRunner.ignoreSIGPIPE self.executableURL = executableURL + self.searchPath = searchPath + self.askpass = askpass self.onCommand = onCommand var env = ProcessInfo.processInfo.environment @@ -208,8 +223,19 @@ public struct GitRunner: Sendable { environment extra: [String: String] = [:], onProgress: (@Sendable (String) -> Void)? = nil ) async throws -> GitOutput { + var environment = extra.isEmpty ? self.environment : self.environment.merging(extra) { _, new in new } + let subcommand = GitRunner.subcommand(of: arguments) + // The login shell's PATH first, as in Terminal; a command that can start a hook waits while it's being read. + var usedLoginPath = false + if let searchPath, let login = await searchPath.folders(waiting: GitSearchPath.waits(for: arguments)) { + environment["PATH"] = GitSearchPath.merged(login, before: environment["PATH"]) + usedLoginPath = true + } + if let askpass { + environment.merge(askpass.environment(trigger: GitCommandTrigger.current, directory: directory)) { _, new in new } + } let start = ContinuousClock.now - let lfsArguments = isLFSInstalled || GitRunner.subcommand(of: arguments) == "add" ? [] : GitRunner.lfsFiltersOff + let lfsArguments = hasLFS || subcommand == "add" ? [] : GitRunner.lfsFiltersOff let onCommand = onCommand var record = onCommand.map { _ in GitCommandRecord( @@ -217,7 +243,8 @@ public struct GitRunner: Sendable { directory: directory?.path(percentEncoded: false) ?? "", trigger: GitCommandTrigger.current, started: Date(), - hasInput: input != nil + hasInput: input != nil, + usedLoginPath: usedLoginPath ) } // A task that asked for progress (Activity's bars) hears every progress line too. @@ -244,7 +271,7 @@ public struct GitRunner: Sendable { executableURL: executableURL, arguments: GitRunner.baseArguments + lfsArguments + arguments, directory: directory, - environment: extra.isEmpty ? environment : environment.merging(extra) { _, new in new }, + environment: environment, input: input, stopGrace: stopGrace, onProgress: progress, diff --git a/Packages/KaernKit/Sources/KaernKit/Git/GitSearchPath.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitSearchPath.swift new file mode 100644 index 0000000..4b06768 --- /dev/null +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitSearchPath.swift @@ -0,0 +1,91 @@ +import Foundation +import Synchronization + +/// Where git and what it starts (hooks, credential helpers, ssh, git-lfs) find programs: the PATH your login shell +/// has, as in Terminal, once the app has read it, ahead of the PATH Kaern was started with. A Mac app gets a short +/// one, so a hook that runs a tool from nvm, mise, asdf, pyenv or `~/.local/bin` (husky, lint-staged, pre-commit) +/// would say "command not found" in Kaern only. Every copy of a runner shares one (`GitRunner.searchPath`). +public final class GitSearchPath: Sendable { + private struct State { + var login: [String]? + var providesLFS = false + var pending = false + var waiters: [CheckedContinuation] = [] + } + + private let state = Mutex(State()) + + public init() {} + + /// The app has started reading the login shell's PATH: a command that may run hooks waits for it. + public func expect() { + state.withLock { $0.pending = true } + } + + /// The login shell's PATH (`nil` when it couldn't be read: git keeps Kaern's own). Wakes whoever waited. + public func provide(_ path: String?) { + let folders = path.map { $0.split(separator: ":").map(String.init).filter { !$0.isEmpty } } + let lfs = folders?.contains { FileManager.default.isExecutableFile(atPath: "\($0)/git-lfs") } ?? false + let waiters = state.withLock { state -> [CheckedContinuation] in + if let folders { + state.login = folders + state.providesLFS = lfs + } + state.pending = false + let waiters = state.waiters + state.waiters = [] + return waiters + } + waiters.forEach { $0.resume() } + } + + /// Whether `git-lfs` is in one of the login shell's folders. + public var providesLFS: Bool { + state.withLock { $0.providesLFS } + } + + /// `environment` with the login shell's folders first in its PATH, when they're known (no waiting). + public func applied(to environment: [String: String]) -> [String: String] { + guard let login = state.withLock({ $0.login }) else { return environment } + var result = environment + result["PATH"] = GitSearchPath.merged(login, before: environment["PATH"]) + return result + } + + /// The login shell's folders, `nil` until known. With `waiting`, first waits while the app is still reading them. + func folders(waiting: Bool) async -> [String]? { + if waiting { + await withCheckedContinuation { (continuation: CheckedContinuation) in + let ready = state.withLock { state -> Bool in + guard state.pending else { return true } + state.waiters.append(continuation) + return false + } + if ready { continuation.resume() } + } + } + return state.withLock { $0.login } + } + + /// `path` with the login shell's folders first, then its own that they don't have. + static func merged(_ login: [String], before path: String?) -> String { + var seen = Set() + let rest = (path ?? "").split(separator: ":").map(String.init) + return (login + rest).filter { !$0.isEmpty && seen.insert($0).inserted }.joined(separator: ":") + } + + /// The commands that can start a hook (or a tool a hook would): these wait for the login shell's PATH while + /// the app reads it, so one started in Kaern's first moments doesn't fail where Terminal wouldn't. + static let hookCommands: Set = ["commit", "merge", "rebase", "cherry-pick", "revert", "am", "push", "pull", + "checkout", "switch", "worktree", "clone"] + + /// Whether a command waits for the login shell's PATH: one of ``hookCommands``, and of `git worktree` only + /// `add`, which checks out. `git worktree list` is part of every repository's first load: waiting there kept + /// each tab from showing its history until the login shell had answered, at every launch. + static func waits(for arguments: [String]) -> Bool { + guard let index = GitRunner.subcommandIndex(of: arguments) else { return false } + let command = arguments[index] + if command == "worktree" { return arguments.dropFirst(index + 1).first == "add" } + return hookCommands.contains(command) + } +} diff --git a/Packages/KaernKit/Sources/KaernKit/Models/Syntax.swift b/Packages/KaernKit/Sources/KaernKit/Models/Syntax.swift new file mode 100644 index 0000000..70c9731 --- /dev/null +++ b/Packages/KaernKit/Sources/KaernKit/Models/Syntax.swift @@ -0,0 +1,982 @@ +import Foundation + +/// What a piece of code is, for its color in a diff (Settings › Diff › Highlight syntax). +public enum SyntaxKind: UInt8, Sendable, Hashable, CaseIterable { + case keyword, string, comment, number, type, function, attribute, preprocessor, tag, property, constant, variable +} + +/// A colored stretch of one line: Characters of the line's raw text, counted as `WordMarks` count them. +public struct SyntaxSpan: Sendable, Hashable { + public var range: Range + public var kind: SyntaxKind + + public init(_ range: Range, _ kind: SyntaxKind) { + self.range = range + self.kind = kind + } +} + +/// A language as the highlighter reads it: its words, comments and strings, and the few rules of its own that a +/// line-by-line reading can follow. It colors what a diff shows, a few lines of a file at a time, so it reads lines, +/// not a whole program: a comment or string that goes on carries to the next line of the hunk. +public struct SyntaxLanguage: Sendable, Hashable { + public struct Quote: Sendable, Hashable { + var open: String + var close: String + var multiline = false + var escapes = true + } + + public enum Structure: Sendable, Hashable { case code, markup, markdown } + + public var name: String + var structure: Structure = .code + var keywords: Set = [] + var types: Set = [] + var constants: Set = [] + var lineComments: [String] = [] + var blockComments: [[String]] = [] + var quotes: [Quote] = [] + var caseInsensitive = false + /// A quote right after a letter or digit starts no string (YAML's `Kaern's tests`, a shell's `don't`). + var quotesAfterWords = true + /// "#" starts a comment only at the start of a line or after a space ("a#b" in a shell isn't one). + var hashCommentNeedsSpace = false + /// "@name": an attribute or decorator (Swift, Java, Python…), or what `atKind` says (Ruby's variables). + var atNames = false + var atKind: SyntaxKind = .attribute + /// A line starting with "#" is a preprocessor directive (C, C++, Objective-C, C#). + var preprocessorLines = false + /// "#name" is a compiler directive (Swift's #if, #available). + var hashDirectives = false + /// "$name", "${…}" and "$(…)" are variables (shell, PHP, Make). + var dollarVariables = false + /// A capitalized name is a type. + var capitalizedTypes = true + /// A name followed by "(" is a function. + var functionCalls = true + /// Characters a name has besides letters, digits and "_". + var nameExtras: Set = [] + /// `key:` (YAML, a Makefile target) or `key =` (TOML, INI) at the start of a line, colored `lineKeyKind`. + var lineKey: Character? + var lineKeyKind: SyntaxKind = .property + /// `[section]` at the start of a line (TOML, INI). + var sections = false + /// A string followed by ":" is a key (JSON). + var stringKeys = false + /// CSS: a name before ":" on a line without "{" is a property; "#fff" is a number; "@media" a keyword. + var css = false + /// Rust: 'a is a lifetime, name! a macro, #[…] an attribute. + var rust = false + +} + +/// Colors lines of code (`SyntaxLanguage`). +public enum SyntaxHighlighter { + /// Lines longer than this aren't colored: minified code, data. + public static let longestLine = 1_500 + + /// What goes on from one line to the next. + enum State: Equatable { + case normal + case comment(close: String) + case string(close: String, escapes: Bool) + /// Markup: inside a tag, among its attributes. + case tag + } + + /// The language of a file, from its name; `nil` for one Kaern doesn't color. + public static func language(forPath path: String) -> SyntaxLanguage? { + let name = (path as NSString).lastPathComponent + let lower = name.lowercased() + if let language = Languages.byName[lower] { return language } + if lower.hasPrefix("dockerfile") || lower.hasSuffix(".dockerfile") { return Languages.dockerfile } + if lower.hasPrefix("makefile") || lower.hasSuffix(".mk") { return Languages.make } + let ext = (lower as NSString).pathExtension + return ext.isEmpty ? nil : Languages.byExtension[ext] + } + + /// The lines of one side of a hunk, in order; a comment or string that goes on carries to the next line. + public static func highlight(_ lines: [String], in language: SyntaxLanguage) -> [[SyntaxSpan]] { + var state = State.normal + return lines.map { highlight(line: $0, language, &state) } + } + + /// One line, after the lines before it (`state`: what they left open). A line too long to color starts over. + static func highlight(line text: String, _ language: SyntaxLanguage, _ state: inout State) -> [SyntaxSpan] { + // Bytes first: counting them costs nothing, and a line has no more Characters than bytes. + guard text.utf8.count <= longestLine || text.count <= longestLine else { + state = .normal + return [] + } + var reader = Reader(text: Array(text), language: language) + switch language.structure { + case .code: reader.code(&state) + case .markup: reader.markup(&state) + case .markdown: reader.markdown(&state) + } + return reader.spans + } +} + +/// The lines of one side of a hunk, colored as they're asked for. A diff shows a screenful of a file whose hunk may +/// run to thousands of lines, so the reading stops a little past the line asked for and goes on from there the next +/// time: what a line is depends on the lines before it (a comment or string that goes on), never on those after. +public struct SyntaxLines: Sendable { + /// How many lines past the one asked for are read with it: the next ones to scroll into view. + public static let ahead = 100 + + private let lines: [String] + private let language: SyntaxLanguage + private var state = SyntaxHighlighter.State.normal + private var spans: [[SyntaxSpan]] = [] + + public init(_ lines: [String], in language: SyntaxLanguage) { + self.lines = lines + self.language = language + } + + /// How many lines have been read so far. + public var readCount: Int { spans.count } + + /// The colored pieces of line `index`, after reading the lines up to it that weren't read yet. + public mutating func spans(at index: Int) -> [SyntaxSpan] { + guard lines.indices.contains(index) else { return [] } + if index >= spans.count { + let end = min(lines.count, index + 1 + Self.ahead) + spans.reserveCapacity(end) + for line in lines[spans.count.. start else { return } + spans.append(SyntaxSpan(start.. Bool { + var offset = position + for character in token { + guard offset < count, text[offset] == character else { return false } + offset += 1 + } + return true + } + + func find(_ token: String, from position: Int) -> Int? { + guard let first = token.first else { return nil } + var offset = position + while offset < count { + if text[offset] == first, at(token, offset) { return offset } + offset += 1 + } + return nil + } + + /// Where a string that `close` ends, ends (past `close`), from `position`; `nil` when not on this line. + func stringEnd(_ close: String, escapes: Bool, from position: Int) -> Int? { + var offset = position + while offset < count { + if escapes, text[offset] == "\\" { + offset += 2 + continue + } + if at(close, offset) { return offset + close.count } + offset += 1 + } + return nil + } + + func isNameStart(_ character: Character) -> Bool { + character.isLetter || character == "_" || character == "$" && language.nameExtras.contains("$") + } + + func isName(_ character: Character) -> Bool { + character.isLetter || character.isNumber || character == "_" || language.nameExtras.contains(character) + } + + func nameEnd(from position: Int) -> Int { + var offset = position + while offset < count, isName(text[offset]) { offset += 1 } + return offset + } + + func nextNonSpace(from position: Int) -> Int? { + var offset = position + while offset < count, text[offset] == " " || text[offset] == "\t" { offset += 1 } + return offset < count ? offset : nil + } + + var firstNonSpace: Int? { nextNonSpace(from: 0) } + + // MARK: Code + + /// Picks up a comment or string the last line left open. + mutating func carry(_ state: inout SyntaxHighlighter.State) -> Bool { + switch state { + case .comment(let close): + if let end = find(close, from: 0) { + add(0, end + close.count, .comment) + index = end + close.count + state = .normal + } else { + add(0, count, .comment) + return false + } + case .string(let close, let escapes): + if let end = stringEnd(close, escapes: escapes, from: 0) { + add(0, end, .string) + index = end + state = .normal + } else { + add(0, count, .string) + return false + } + case .normal, .tag: + break + } + return true + } + + mutating func code(_ state: inout SyntaxHighlighter.State) { + guard carry(&state) else { return } + let start = firstNonSpace + if language.preprocessorLines, let start, text[start] == "#", index <= start { + add(start, count, .preprocessor) + return + } + if let key = language.lineKey, index == 0 { _ = lineKey(key) } + if language.sections, let start, text[start] == "[", index <= start { + var end = (find("]", from: start) ?? count - 1) + 1 + if end < count, text[end] == "]" { end += 1 } + add(start, end, .keyword) + index = max(index, end) + } + while index < count { + let character = text[index] + if character == " " || character == "\t" { + index += 1 + continue + } + // A block comment before a line one: Lua's `--[[` starts with its `--`. + if blockComment(&state) { if case .comment = state { return } else { continue } } + if lineComment() { return } + // Rust's 'a (a lifetime) before quotes take it for a char. + if language.rust, rustSpecial() { continue } + if quoted(&state) { if case .string = state { return } else { continue } } + if character.isNumber || character == "." && index + 1 < count && text[index + 1].isNumber { + number() + continue + } + if character == "@", language.atNames, index + 1 < count, isNameStart(text[index + 1]) { + let end = nameEnd(from: index + 1) + add(index, end, language.atKind) + index = end + continue + } + if character == "#" { + if language.hashDirectives, index + 1 < count, text[index + 1].isLetter { + let end = nameEnd(from: index + 1) + add(index, end, .preprocessor) + index = end + continue + } + if language.css, index + 1 < count, text[index + 1].isHexDigit { + let end = nameEnd(from: index + 1) + add(index, end, .number) + index = end + continue + } + } + if character == "$", language.dollarVariables { + variable() + continue + } + if character == "@", language.css, index + 1 < count, text[index + 1].isLetter { + let end = nameEnd(from: index + 1) + add(index, end, .keyword) + index = end + continue + } + if isNameStart(character) || character == "-" && language.css && index + 1 < count && text[index + 1] == "-" { + word() + continue + } + index += 1 + } + } + + /// `key:` / `key =` at the line's start (after spaces and YAML's "- "). + mutating func lineKey(_ separator: Character) -> Bool { + guard var start = firstNonSpace else { return false } + if separator == ":", text[start] == "-", start + 1 < count, text[start + 1] == " ", let next = nextNonSpace(from: start + 1) { + start = next + } + guard isNameStart(text[start]) || text[start].isNumber || text[start] == "\"" || text[start] == "'" else { return false } + var end = start + if text[start] == "\"" || text[start] == "'" { + guard let close = stringEnd(String(text[start]), escapes: true, from: start + 1) else { return false } + end = close + } else { + while end < count, isName(text[end]) || text[end] == "." || text[end] == "-" || text[end] == "/" || text[end] == "$" { + end += 1 + } + } + let after = nextNonSpace(from: end) + guard let after, text[after] == separator else { return false } + if separator == ":", after + 1 < count, text[after + 1] != " ", text[after + 1] != "\t" { return false } + add(start, end, language.lineKeyKind) + index = after + 1 + return true + } + + mutating func lineComment() -> Bool { + for token in language.lineComments where at(token, index) { + if token == "#", language.hashCommentNeedsSpace, index > 0, text[index - 1] != " ", text[index - 1] != "\t" { continue } + add(index, count, .comment) + index = count + return true + } + return false + } + + mutating func blockComment(_ state: inout SyntaxHighlighter.State) -> Bool { + for pair in language.blockComments where at(pair[0], index) { + if let end = find(pair[1], from: index + pair[0].count) { + add(index, end + pair[1].count, .comment) + index = end + pair[1].count + } else { + add(index, count, .comment) + index = count + state = .comment(close: pair[1]) + } + return true + } + return false + } + + /// The quotes are listed longer first, so `"""` wins over `"`. + mutating func quoted(_ state: inout SyntaxHighlighter.State) -> Bool { + if !language.quotesAfterWords, index > 0, text[index - 1].isLetter || text[index - 1].isNumber { return false } + for quote in language.quotes where at(quote.open, index) { + let start = index + if let end = stringEnd(quote.close, escapes: quote.escapes, from: index + quote.open.count) { + var kind = SyntaxKind.string + if language.stringKeys, let next = nextNonSpace(from: end), text[next] == ":" { kind = .property } + add(start, end, kind) + index = end + } else { + add(start, count, .string) + index = count + if quote.multiline { state = .string(close: quote.close, escapes: quote.escapes) } + } + return true + } + return false + } + + mutating func number() { + let start = index + if text[index] == "0", index + 1 < count, "xXbBoO".contains(text[index + 1]) { + index += 2 + while index < count, text[index].isHexDigit || text[index] == "_" { index += 1 } + } else { + while index < count { + let character = text[index] + if character.isNumber || character == "_" || character == "." && index + 1 < count && text[index + 1].isNumber { + index += 1 + } else if (character == "e" || character == "E"), index + 1 < count, + text[index + 1].isNumber || (text[index + 1] == "-" || text[index + 1] == "+") && index + 2 < count && text[index + 2].isNumber { + index += 2 + } else { + break + } + } + } + // Units and suffixes: 10px, 1.5em, 100%, 10u, 2.0f. + while index < count, text[index].isLetter || text[index] == "%" { index += 1 } + add(start, index, .number) + } + + mutating func variable() { + let start = index + index += 1 + if index < count, text[index] == "{" || text[index] == "(" { + let close: Character = text[index] == "{" ? "}" : ")" + while index < count, text[index] != close { index += 1 } + index = min(index + 1, count) + } else { + while index < count, isName(text[index]) || "@#?$!*-".contains(text[index]) && index == start + 1 { index += 1 } + } + add(start, index, .variable) + } + + mutating func word() { + let start = index + index = nameEnd(from: index) + let word = String(text[start.. Bool { + let character = text[index] + if character == "'", index + 1 < count, isNameStart(text[index + 1]) { + let end = nameEnd(from: index + 1) + if end >= count || text[end] != "'" { + add(index, end, .attribute) + index = end + return true + } + } + if character == "#", index + 1 < count, text[index + 1] == "[" || text[index + 1] == "!" && index + 2 < count && text[index + 2] == "[" { + let end = (find("]", from: index) ?? count - 1) + 1 + add(index, end, .attribute) + index = end + return true + } + if isNameStart(character) { + let end = nameEnd(from: index) + if end < count, text[end] == "!", !language.keywords.contains(String(text[index..", from: index + 4) { + add(index, end + 3, .comment) + index = end + 3 + } else { + add(index, count, .comment) + state = .comment(close: "-->") + return + } + continue + } + if at("", from: index).map { $0 + 3 } ?? count + add(index, end, .string) + index = end + continue + } + if text[index] == "<", index + 1 < count, isNameStart(text[index + 1]) || "/!?".contains(text[index + 1]) { + let start = index + index += 1 + if index < count, "/!?".contains(text[index]) { index += 1 } + while index < count, isName(text[index]) || ":-.".contains(text[index]) { index += 1 } + add(start, index, .tag) + state = .tag + attributes(&state) + continue + } + if text[index] == "&", let end = find(";", from: index), end - index < 10 { + add(index, end + 1, .constant) + index = end + 1 + continue + } + index += 1 + } + } + + /// Inside a tag: names, "=" and values, up to its end (which may be on a later line). + mutating func attributes(_ state: inout SyntaxHighlighter.State) { + while index < count { + let character = text[index] + if character == ">" || character == "/" && index + 1 < count && text[index + 1] == ">" || character == "?" && index + 1 < count && text[index + 1] == ">" { + let end = character == ">" ? index + 1 : index + 2 + add(index, end, .tag) + index = end + state = .normal + return + } + if character == "\"" || character == "'" { + let end = stringEnd(String(character), escapes: false, from: index + 1) ?? count + add(index, end, .string) + index = end + continue + } + if isNameStart(character) { + let start = index + while index < count, isName(text[index]) || ":-.".contains(text[index]) { index += 1 } + add(start, index, .property) + continue + } + index += 1 + } + } + + // MARK: Markdown + + mutating func markdown(_ state: inout SyntaxHighlighter.State) { + guard let start = firstNonSpace else { return } + // A fenced block: its fences and lines are code. + if at("```", start) || at("~~~", start) { + add(start, count, .string) + if case .string = state { state = .normal } else { state = .string(close: String(text[start.." { + add(start, count, .comment) + return + } + index = start + if "-*+".contains(text[start]), start + 1 < count, text[start + 1] == " " { + add(start, start + 1, .keyword) + index = start + 2 + } else if text[start].isNumber, let dot = find(". ", from: start), dot - start <= 3, text[start.. Set { + Set(text.split(whereSeparator: { $0 == " " || $0 == "\n" }).map(String.init)) + } + + private static let cQuotes = [SyntaxLanguage.Quote(open: "\"", close: "\""), SyntaxLanguage.Quote(open: "'", close: "'")] + + static let swift = SyntaxLanguage( + name: "Swift", + keywords: words(""" + associatedtype class deinit enum extension fileprivate func import init inout internal let open operator private + precedencegroup protocol public rethrows static struct subscript typealias var break case catch continue default + defer do else fallthrough for guard if in repeat return throw switch where while as is try await async throws + some any super self Self actor nonisolated isolated consuming borrowing mutating nonmutating override required + convenience dynamic final lazy optional unowned weak indirect willSet didSet get set package sending macro + """), + constants: words("true false nil"), + lineComments: ["//"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "\"\"\"", close: "\"\"\"", multiline: true), .init(open: "\"", close: "\"")], + atNames: true, hashDirectives: true) + + static let objectiveC = SyntaxLanguage( + name: "Objective-C", + keywords: words(""" + auto break case char const continue default do double else enum extern float for goto if inline int long + register restrict return short signed sizeof static struct switch typedef union unsigned void volatile while + id self super nil Nil YES NO in out inout bycopy byref oneway instancetype nonatomic atomic strong weak copy + assign readonly readwrite nullable nonnull class bool true false NULL + interface implementation end property synthesize dynamic protocol optional required selector encode + autoreleasepool try catch finally throw import + """), + lineComments: ["//"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "@\"", close: "\""), .init(open: "\"", close: "\""), .init(open: "'", close: "'")], + atNames: true, atKind: .keyword, preprocessorLines: true) + + static let c = SyntaxLanguage( + name: "C", + keywords: words(""" + auto break case char const continue default do double else enum extern float for goto if inline int long + register restrict return short signed sizeof static struct switch typedef union unsigned void volatile while + _Bool _Complex _Atomic _Noreturn _Static_assert alignas alignof bool + class namespace template typename public private protected virtual override final friend operator new delete + this throw try catch using constexpr consteval constinit decltype explicit mutable noexcept nullptr + static_cast dynamic_cast reinterpret_cast const_cast co_await co_return co_yield concept requires export module + """), + constants: words("true false NULL nullptr"), + lineComments: ["//"], blockComments: [["/*", "*/"]], quotes: cQuotes, preprocessorLines: true) + + static let csharp = SyntaxLanguage( + name: "C#", + keywords: words(""" + abstract as base bool break byte case catch char checked class const continue decimal default delegate do double + else enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is + lock long namespace new object operator out override params private protected public readonly ref return sbyte + sealed short sizeof stackalloc static string struct switch this throw try typeof uint ulong unchecked unsafe + ushort using virtual void volatile while var async await dynamic get set init record yield when where with + """), + constants: words("true false null"), + lineComments: ["//"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "@\"", close: "\"", multiline: true, escapes: false), .init(open: "$\"", close: "\""), + .init(open: "\"", close: "\""), .init(open: "'", close: "'")], + preprocessorLines: true) + + static let java = SyntaxLanguage( + name: "Java", + keywords: words(""" + abstract assert boolean break byte case catch char class const continue default do double else enum extends final + finally float for goto if implements import instanceof int interface long native new package private protected + public return short static strictfp super switch synchronized this throw throws transient try void volatile while + var record sealed permits non-sealed yield + """), + constants: words("true false null"), + lineComments: ["//"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "\"\"\"", close: "\"\"\"", multiline: true), .init(open: "\"", close: "\""), .init(open: "'", close: "'")], + atNames: true) + + static let kotlin = SyntaxLanguage( + name: "Kotlin", + keywords: words(""" + as break class continue do else for fun if in interface is object package return super this throw try typealias + typeof val var when while by catch constructor delegate dynamic field file finally get import init param property + receiver set setparam where abstract actual annotation companion const crossinline data enum expect external final + infix inline inner internal lateinit noinline open operator out override private protected public reified sealed + suspend tailrec vararg value + """), + constants: words("true false null"), + lineComments: ["//"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "\"\"\"", close: "\"\"\"", multiline: true, escapes: false), .init(open: "\"", close: "\""), + .init(open: "'", close: "'")], + atNames: true) + + static let scala = SyntaxLanguage( + name: "Scala", + keywords: words(""" + abstract case catch class def do else extends final finally for forSome if implicit import lazy match new object + override package private protected return sealed super this throw trait try type val var while with yield given + using enum then export extension + """), + constants: words("true false null"), + lineComments: ["//"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "\"\"\"", close: "\"\"\"", multiline: true, escapes: false), .init(open: "\"", close: "\"")], + atNames: true) + + static let groovy = SyntaxLanguage( + name: "Groovy", + keywords: words(""" + abstract as assert boolean break byte case catch char class const continue def default do double else enum extends + final finally float for goto if implements import in instanceof int interface long native new package private + protected public return short static super switch synchronized this throw throws trait transient try void + volatile while var + """), + constants: words("true false null"), + lineComments: ["//"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "'''", close: "'''", multiline: true), .init(open: "\"\"\"", close: "\"\"\"", multiline: true), + .init(open: "\"", close: "\""), .init(open: "'", close: "'")], + atNames: true) + + static let dart = SyntaxLanguage( + name: "Dart", + keywords: words(""" + abstract as assert async await base break case catch class const continue covariant default deferred do dynamic + else enum export extends extension external factory final finally for Function get hide if implements import in + interface is late library mixin new on operator part required rethrow return sealed set show static super switch + sync this throw try typedef var void when while with yield + """), + constants: words("true false null"), + lineComments: ["//"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "'''", close: "'''", multiline: true), .init(open: "\"\"\"", close: "\"\"\"", multiline: true), + .init(open: "\"", close: "\""), .init(open: "'", close: "'")], + atNames: true) + + static let go = SyntaxLanguage( + name: "Go", + keywords: words(""" + break case chan const continue default defer else fallthrough for func go goto if import interface map package + range return select struct switch type var + """), + types: words(""" + bool byte complex64 complex128 error float32 float64 int int8 int16 int32 int64 rune string uint uint8 uint16 + uint32 uint64 uintptr any comparable + """), + constants: words("true false nil iota"), + lineComments: ["//"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "`", close: "`", multiline: true, escapes: false), .init(open: "\"", close: "\""), .init(open: "'", close: "'")], + capitalizedTypes: false) + + static let rust = SyntaxLanguage( + name: "Rust", + keywords: words(""" + as async await break const continue crate dyn else enum extern fn for if impl in let loop match mod move mut pub + ref return self Self static struct super trait type unsafe use where while union macro_rules + """), + types: words("i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64 bool char str String Vec Option Result Box"), + constants: words("true false None Some Ok Err"), + lineComments: ["//"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "r#\"", close: "\"#", multiline: true, escapes: false), .init(open: "r\"", close: "\"", multiline: true, escapes: false), + .init(open: "b\"", close: "\""), .init(open: "\"", close: "\"", multiline: true), .init(open: "'", close: "'")], + rust: true) + + static let javascript = SyntaxLanguage( + name: "JavaScript", + keywords: words(""" + async await break case catch class const continue debugger default delete do else export extends finally for + from function get if import in instanceof let new of return set static super switch this throw try typeof var + void while with yield as satisfies + """), + constants: words("true false null undefined NaN Infinity"), + lineComments: ["//"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "`", close: "`", multiline: true), .init(open: "\"", close: "\""), .init(open: "'", close: "'")], + atNames: true, nameExtras: ["$"]) + + static let typescript: SyntaxLanguage = { + var language = javascript + language.name = "TypeScript" + language.keywords.formUnion(words(""" + abstract declare enum implements interface keyof namespace private protected public readonly type infer is + asserts override accessor module + """)) + language.types = words("string number boolean any unknown never void object symbol bigint") + return language + }() + + static let python = SyntaxLanguage( + name: "Python", + keywords: words(""" + and as assert async await break class continue def del elif else except finally for from global if import in is + lambda nonlocal not or pass raise return try while with yield match case type print self cls + """), + constants: words("True False None"), + lineComments: ["#"], + quotes: ["f\"\"\"", "r\"\"\"", "b\"\"\"", "\"\"\"", "f'''", "r'''", "b'''", "'''"].map { + .init(open: $0, close: String($0.suffix(3)), multiline: true, escapes: !$0.hasPrefix("r")) + } + ["f\"", "r\"", "b\"", "u\"", "rb\"", "br\"", "fr\"", "rf\"", "\"", "f'", "r'", "b'", "u'", "rb'", "br'", "fr'", "rf'", "'"].map { + .init(open: $0, close: String($0.suffix(1)), escapes: !$0.contains("r")) + }, + atNames: true) + + static let ruby = SyntaxLanguage( + name: "Ruby", + keywords: words(""" + BEGIN END alias and begin break case class def defined? do else elsif end ensure for if in module next not or redo + rescue retry return self super then undef unless until when while yield require require_relative include extend + attr_reader attr_writer attr_accessor private protected public raise lambda proc puts + """), + constants: words("true false nil"), + lineComments: ["#"], blockComments: [["=begin", "=end"]], + quotes: [.init(open: "\"", close: "\""), .init(open: "'", close: "'"), .init(open: "`", close: "`")], + atNames: true, atKind: .variable, dollarVariables: true, nameExtras: ["?", "!"]) + + static let php = SyntaxLanguage( + name: "PHP", + keywords: words(""" + abstract and array as break callable case catch class clone const continue declare default do echo else elseif + empty enddeclare endfor endforeach endif endswitch endwhile enum extends final finally fn for foreach function + global goto if implements include include_once instanceof insteadof interface isset list match namespace new or + print private protected public readonly require require_once return static switch throw trait try unset use var + while xor yield php + """), + constants: words("true false null TRUE FALSE NULL"), + lineComments: ["//", "#"], blockComments: [["/*", "*/"]], quotes: cQuotes, + dollarVariables: true) + + static let shell = SyntaxLanguage( + name: "Shell", + keywords: words(""" + if then else elif fi case esac for select while until do done in function time coproc return exit export local + readonly declare typeset unset shift source alias set trap eval exec break continue echo printf cd test + """), + constants: words("true false"), + lineComments: ["#"], + quotes: [.init(open: "\"", close: "\"", multiline: true), .init(open: "'", close: "'", multiline: true, escapes: false)], + quotesAfterWords: false, hashCommentNeedsSpace: true, dollarVariables: true, capitalizedTypes: false, + functionCalls: false, nameExtras: ["-"]) + + static let powershell = SyntaxLanguage( + name: "PowerShell", + keywords: words(""" + begin break catch class continue data define do dynamicparam else elseif end enum exit filter finally for foreach + from function if in param process return switch throw trap try until using var while + """), + lineComments: ["#"], blockComments: [["<#", "#>"]], + quotes: [.init(open: "\"", close: "\""), .init(open: "'", close: "'", escapes: false)], + caseInsensitive: true, quotesAfterWords: false, dollarVariables: true, capitalizedTypes: false, nameExtras: ["-"]) + + static let sql = SyntaxLanguage( + name: "SQL", + keywords: words(""" + select from where and or not insert into values update set delete create table alter drop index view trigger + primary key foreign references unique default null is in like between exists join left right inner outer full + cross on as order by group having limit offset union all distinct case when then else end begin commit rollback + transaction if returns return function procedure declare with recursive grant revoke database schema column + constraint check cascade asc desc count sum avg min max cast coalesce + """), + types: words("int integer bigint smallint text varchar char boolean bool date time timestamp timestamptz numeric decimal float real double serial uuid json jsonb blob"), + constants: words("true false"), + lineComments: ["--"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "'", close: "'", escapes: false), .init(open: "\"", close: "\"", escapes: false)], + caseInsensitive: true, capitalizedTypes: false) + + static let lua = SyntaxLanguage( + name: "Lua", + keywords: words("and break do else elseif end for function goto if in local not or repeat return then until while"), + constants: words("true false nil"), + lineComments: ["--"], blockComments: [["--[[", "]]"]], + quotes: [.init(open: "[[", close: "]]", multiline: true, escapes: false), .init(open: "\"", close: "\""), .init(open: "'", close: "'")]) + + static let markup = SyntaxLanguage(name: "Markup", structure: .markup, capitalizedTypes: false, functionCalls: false) + + static let css = SyntaxLanguage( + name: "CSS", + constants: words("important inherit initial unset none auto"), + lineComments: [], blockComments: [["/*", "*/"]], quotes: cQuotes, + capitalizedTypes: false, functionCalls: true, nameExtras: ["-"], css: true) + + static let scss: SyntaxLanguage = { + var language = css + language.name = "SCSS" + language.lineComments = ["//"] + language.dollarVariables = true + return language + }() + + static let json = SyntaxLanguage( + name: "JSON", + constants: words("true false null"), + lineComments: ["//"], blockComments: [["/*", "*/"]], + quotes: [.init(open: "\"", close: "\"")], + capitalizedTypes: false, functionCalls: false, stringKeys: true) + + static let yaml = SyntaxLanguage( + name: "YAML", + constants: words("true false null yes no on off True False Null Yes No On Off TRUE FALSE NULL ~"), + lineComments: ["#"], + quotes: [.init(open: "\"", close: "\""), .init(open: "'", close: "'", escapes: false)], + quotesAfterWords: false, hashCommentNeedsSpace: true, capitalizedTypes: false, functionCalls: false, + nameExtras: ["-"], lineKey: ":") + + static let toml = SyntaxLanguage( + name: "TOML", + constants: words("true false"), + lineComments: ["#"], + quotes: [.init(open: "\"\"\"", close: "\"\"\"", multiline: true), .init(open: "'''", close: "'''", multiline: true, escapes: false), + .init(open: "\"", close: "\""), .init(open: "'", close: "'", escapes: false)], + quotesAfterWords: false, capitalizedTypes: false, functionCalls: false, nameExtras: ["-"], lineKey: "=", sections: true) + + static let ini = SyntaxLanguage( + name: "INI", + constants: words("true false yes no on off"), + lineComments: ["#", ";"], + quotes: [.init(open: "\"", close: "\"")], + quotesAfterWords: false, capitalizedTypes: false, functionCalls: false, nameExtras: ["-", "."], lineKey: "=", + sections: true) + + static let markdown = SyntaxLanguage(name: "Markdown", structure: .markdown, capitalizedTypes: false, functionCalls: false) + + static let dockerfile = SyntaxLanguage( + name: "Dockerfile", + keywords: words(""" + from run cmd label maintainer expose env add copy entrypoint volume user workdir arg onbuild stopsignal healthcheck + shell as + """), + lineComments: ["#"], quotes: cQuotes, + caseInsensitive: true, quotesAfterWords: false, hashCommentNeedsSpace: true, dollarVariables: true, + capitalizedTypes: false, functionCalls: false) + + static let make = SyntaxLanguage( + name: "Make", + keywords: words("ifeq ifneq ifdef ifndef else endif include define endef export override unexport vpath"), + lineComments: ["#"], quotes: cQuotes, + quotesAfterWords: false, dollarVariables: true, capitalizedTypes: false, functionCalls: false, nameExtras: ["-", "."], + lineKey: ":", lineKeyKind: .function) + + static let byExtension: [String: SyntaxLanguage] = { + var map: [String: SyntaxLanguage] = [:] + func add(_ language: SyntaxLanguage, _ extensions: String) { + for ext in extensions.split(separator: " ") { map[String(ext)] = language } + } + add(swift, "swift swiftinterface") + add(objectiveC, "m mm") + add(c, "c h cc cpp cxx c++ hpp hh hxx h++ ino metal cu") + add(csharp, "cs csx") + add(java, "java") + add(kotlin, "kt kts") + add(scala, "scala sc") + add(groovy, "groovy gradle gvy") + add(dart, "dart") + add(go, "go") + add(rust, "rs") + add(javascript, "js mjs cjs jsx") + add(typescript, "ts mts cts tsx") + add(python, "py pyi pyw") + add(ruby, "rb rake gemspec podspec ru") + add(php, "php") + add(shell, "sh bash zsh fish ksh command bats") + add(powershell, "ps1 psm1 psd1") + add(sql, "sql") + add(lua, "lua") + add(markup, "html htm xhtml xml svg plist xib storyboard xcscheme xcworkspacedata entitlements vue svelte xaml csproj resx") + add(css, "css") + add(scss, "scss less sass") + add(json, "json jsonc json5 resolved xcstrings har webmanifest") + add(yaml, "yml yaml") + add(toml, "toml") + add(ini, "ini cfg conf properties editorconfig gitconfig gitmodules npmrc env") + add(markdown, "md markdown mdx") + return map + }() + + static let byName: [String: SyntaxLanguage] = [ + "gemfile": ruby, "podfile": ruby, "fastfile": ruby, "appfile": ruby, "rakefile": ruby, "brewfile": ruby, "dangerfile": ruby, + "vagrantfile": ruby, ".zshrc": shell, ".bashrc": shell, ".bash_profile": shell, ".zprofile": shell, ".profile": shell, + ".gitconfig": ini, ".gitmodules": ini, ".editorconfig": ini, ".npmrc": ini, ".env": ini, "package.resolved": json, + "cmakelists.txt": make, "jenkinsfile": groovy, "podfile.lock": yaml, + ] +} diff --git a/Packages/KaernKit/Tests/KaernKitTests/AskpassTests.swift b/Packages/KaernKit/Tests/KaernKitTests/AskpassTests.swift new file mode 100644 index 0000000..f91754b --- /dev/null +++ b/Packages/KaernKit/Tests/KaernKitTests/AskpassTests.swift @@ -0,0 +1,139 @@ +import Foundation +import Testing +@testable import KaernKit + +/// What ssh asks, read from its prompts; the failures that follow; and the variables ssh and the asker get. +@Suite("SSH questions", .hangGuard) +struct AskpassTests { + /// One ssh: the saved passphrase first; asked again, it was wrong, so it goes and the user is asked; asked a + /// third time, the user's answer was wrong too. + @Test func aSavedPassphraseThatIsTurnedDownGoes() { + var attempts = AskpassAttempts() + let start = Date() + #expect(attempts.next(key: "id", process: 7, saved: "old", at: start) == .give("old")) + #expect(attempts.next(key: "id", process: 7, saved: "old", at: start + 1) == .ask(again: true, forget: true)) + attempts.answered("typo", key: "id", process: 7, at: start + 5) + // Saved with the window's checkbox before ssh could say it was wrong. + #expect(attempts.next(key: "id", process: 7, saved: "typo", at: start + 6) == .ask(again: true, forget: true)) + // Nothing saved, nothing given: just asked. + #expect(attempts.next(key: "id", process: 8, saved: nil, at: start + 7) == .ask(again: false, forget: false)) + // Long after, the same process number is another ssh. + #expect(attempts.next(key: "id", process: 7, saved: "new", at: start + 120) == .give("new")) + } + + /// Two fetches at once with one key, whose saved passphrase no longer fits: each ssh's second question is its + /// own retry, whichever asks in between. (With one note per key, each read as the other's first, the saved one + /// went out six times and nobody was asked.) + @Test func twoAskersWithOneKeyEachGetTheirOwnRetry() { + var attempts = AskpassAttempts() + let start = Date() + #expect(attempts.next(key: "id", process: 1, saved: "old", at: start) == .give("old")) + #expect(attempts.next(key: "id", process: 2, saved: "old", at: start + 0.1) == .give("old")) + #expect(attempts.next(key: "id", process: 1, saved: "old", at: start + 0.2) == .ask(again: true, forget: true)) + // The first one's retry took the saved passphrase away; the second is turned down too. + #expect(attempts.next(key: "id", process: 2, saved: nil, at: start + 0.3) == .ask(again: true, forget: false)) + // Another key is another matter. + #expect(attempts.next(key: "other", process: 1, saved: "old", at: start + 0.4) == .give("old")) + } + + /// An ssh turned down with the old saved passphrase gets the one saved since: it isn't asked, and the new one + /// isn't taken for the one that failed. + @Test func aNewerSavedPassphraseIsTriedNotForgotten() { + var attempts = AskpassAttempts() + let start = Date() + #expect(attempts.next(key: "id", process: 1, saved: "old", at: start) == .give("old")) + #expect(attempts.next(key: "id", process: 2, saved: "old", at: start + 0.1) == .give("old")) + #expect(attempts.next(key: "id", process: 1, saved: "old", at: start + 0.2) == .ask(again: true, forget: true)) + attempts.answered("new", key: "id", process: 1, at: start + 4) + #expect(attempts.next(key: "id", process: 2, saved: "new", at: start + 4.1) == .give("new")) + // And if that one is wrong as well, it goes. + #expect(attempts.next(key: "id", process: 2, saved: "new", at: start + 4.2) == .ask(again: true, forget: true)) + } + + @Test func readsWhatSSHAsks() { + #expect(AskpassQuestion.read(prompt: "Enter passphrase for key '/Users/me/.ssh/id_ed25519': ", mode: nil) + == .passphrase(key: "/Users/me/.ssh/id_ed25519")) + let host = """ + The authenticity of host 'github.com (140.82.112.3)' can't be established. + ED25519 key fingerprint is SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU. + This key is not known by any other names. + Are you sure you want to continue connecting (yes/no/[fingerprint])? + """ + #expect(AskpassQuestion.read(prompt: host, mode: nil) + == .newHost(host: "github.com", keyType: "ED25519", fingerprint: "SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU")) + #expect(AskpassQuestion.read(prompt: "Enter PIN for ED25519-SK key /Users/me/.ssh/id_ed25519_sk: ", mode: nil) + == .pin(key: "/Users/me/.ssh/id_ed25519_sk")) + #expect(AskpassQuestion.read(prompt: "Confirm user presence for key ED25519-SK SHA256:abc", mode: "none") + == .touch(message: "Confirm user presence for key ED25519-SK SHA256:abc")) + #expect(AskpassQuestion.read(prompt: "Allow use of key /k?", mode: "confirm") == .confirm(message: "Allow use of key /k?")) + #expect(AskpassQuestion.read(prompt: "Username for 'https://github.com': ", mode: nil) + == .gitCredential(message: "Username for 'https://github.com':")) + #expect(AskpassQuestion.read(prompt: "(git@example.com) Password: ", mode: nil) == .other(message: "(git@example.com) Password:")) + } + + @Test func tellsTheSSHFailuresApart() { + func explain(_ text: String) -> GitFailure? { + GitFailure.explain(arguments: ["fetch", "--all"], errorOutput: text, status: 128) + } + #expect(explain(GitAskpass.Note.cancelled + "\nHost key verification failed.\nfatal: Could not read from remote repository.") + == .promptCancelled) + #expect(explain(GitAskpass.Note.locked + "\ngit@github.com: Permission denied (publickey).") == .sshKeyLocked(host: "github.com")) + #expect(explain(GitAskpass.Note.newHost + "\nHost key verification failed.") == .hostKeyUnknown(host: nil)) + #expect(explain(""" + @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ + @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + Host key for github.com has changed and you have requested strict checking. + Host key verification failed. + """) == .hostKeyChanged(host: "github.com")) + #expect(explain("Host key verification failed.\nfatal: Could not read from remote repository.") == .hostKeyUnknown(host: nil)) + #expect(explain("git@github.com: Permission denied (publickey).\nfatal: Could not read from remote repository.") + == .sshKey(host: "github.com")) + } + + @Test func gitsOwnQuestionTurnedDownReadsAsBefore() { + let error = GitError(arguments: ["fetch"], status: 128, message: """ + error: unable to read askpass response from '/Applications/Kaern.app/Contents/MacOS/Kaern' + fatal: could not read Username for 'https://github.com': terminal prompts disabled + """) + #expect(error.errorDescription == "could not read Username for 'https://github.com': terminal prompts disabled") + #expect(GitFailure.explain(arguments: ["fetch"], errorOutput: error.message, status: 128) == .signIn(host: "github.com")) + } + + /// The variables reach ssh: what asks, that it must, and what the user did (empty in the background). + @Test func sshGetsTheAskerAndWhatTheUserDid() async throws { + let folder = FileManager.default.temporaryDirectory.appending(path: "kaern-askpass-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let seen = folder.appending(path: "seen").path(percentEncoded: false) + // A stand-in ssh: writes what it was given, then gives up as ssh does without an answer. + let ssh = folder.appending(path: "fake-ssh") + try Data(""" + #!/bin/sh + printf '%s|%s|%s|%s\\n' "$SSH_ASKPASS" "$SSH_ASKPASS_REQUIRE" "$KAERN_ASKPASS_TOKEN" "$KAERN_ASKPASS_ACTION" >> \(seen) + echo "Host key verification failed." >&2 + exit 255 + + """.utf8).write(to: ssh) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: ssh.path(percentEncoded: false)) + + var runner = RepositoryTests.runner + runner.askpass = GitAskpass(program: "/kaern/asker", socket: "/tmp/socket", token: "t0k3n") + let url = FileManager.default.temporaryDirectory.appending(path: "kaern-tests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + let repository = try await GitRepository.initialize(at: url, defaultBranch: "main", runner: runner) + defer { TestRepositories.remove(repository) } + try await repository.git(["config", "core.sshCommand", ssh.path(percentEncoded: false)]) + try await repository.git(["config", "ssh.variant", "simple"]) + try await repository.git(["remote", "add", "far", "kaern-check.invalid:/nowhere.git"]) + + await #expect(throws: GitError.self) { + try await GitCommandTrigger.$current.withValue(GitCommandTrigger("Fetch")) { try await repository.fetch(remote: "far") } + } + await #expect(throws: GitError.self) { + try await GitCommandTrigger.$current.withValue(.background("Auto-fetch")) { try await repository.fetch(remote: "far") } + } + let lines = try String(contentsOfFile: seen, encoding: .utf8).split(separator: "\n") + #expect(lines == ["/kaern/asker|force|t0k3n|Fetch", "/kaern/asker|force|t0k3n|"]) + } +} diff --git a/Packages/KaernKit/Tests/KaernKitTests/BranchTagTests.swift b/Packages/KaernKit/Tests/KaernKitTests/BranchTagTests.swift index fa01efb..483d7a6 100644 --- a/Packages/KaernKit/Tests/KaernKitTests/BranchTagTests.swift +++ b/Packages/KaernKit/Tests/KaernKitTests/BranchTagTests.swift @@ -43,6 +43,37 @@ struct BranchTagTests { #expect(after.tags.map(\.name) == ["v1.0.1"]) } + @Test func deletesATagHereAndOnTheRemoteAndBringsItBack() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("a\n", to: "a.txt") + let head = try await repository.commitAll("base") + let remote = FileManager.default.temporaryDirectory.appending(path: "kaern-remote-\(UUID().uuidString).git") + defer { try? FileManager.default.removeItem(at: remote) } + try await RepositoryTests.runner.run(["init", "-q", "--bare", "-b", "main", remote.path(percentEncoded: false)], in: nil) + try await repository.addRemote("origin", url: remote.path(percentEncoded: false)) + try await repository.createTag("v1.0", at: head, message: "One") + try await repository.pushTag("v1.0", to: "origin") + // A branch with the tag's name on the remote: deleting the tag leaves it. + try await repository.git(["push", "-q", "origin", "\(head):refs/heads/v1.0"]) + + // Here: deleted, then made again from its object, still annotated (what ⌘Z does). + let object = try #require(await repository.resolve("refs/tags/v1.0")) + try await repository.deleteTag("v1.0") + #expect(await repository.resolve("refs/tags/v1.0") == nil) + try await repository.restoreTag("v1.0", object: object) + #expect(await repository.resolve("refs/tags/v1.0") == object) + #expect(try await repository.git(["cat-file", "-t", "v1.0"]).text.trimmingCharacters(in: .whitespacesAndNewlines) == "tag") + + // On the remote. + #expect(try await repository.deleteRemoteTag("v1.0", on: "origin")) + let left = try await repository.git(["ls-remote", "origin"]).text + #expect(!left.contains("refs/tags/v1.0")) + #expect(left.contains("refs/heads/v1.0")) + // Not there any more: nothing to delete, not a failure. + #expect(try await repository.deleteRemoteTag("v1.0", on: "origin") == false) + } + @Test func listsTagsNewestFirstWithDates() async throws { let repository = try await TestRepositories.make() defer { TestRepositories.remove(repository) } diff --git a/Packages/KaernKit/Tests/KaernKitTests/DiscardTests.swift b/Packages/KaernKit/Tests/KaernKitTests/DiscardTests.swift index 4a569af..74e5066 100644 --- a/Packages/KaernKit/Tests/KaernKitTests/DiscardTests.swift +++ b/Packages/KaernKit/Tests/KaernKitTests/DiscardTests.swift @@ -24,8 +24,8 @@ struct DiscardTests { try repository.write("other\n", to: "c.txt") // not discarded let before = try await repository.status() - let record = try await repository.discard(paths: ["a.txt", "b.txt", "notes/[draft].md"], untracked: ["notes/[draft].md"], - keepingStaged: false, message: "Before discarding 3 files") + let record = try await repository.discard(paths: ["a.txt", "b.txt", "notes/[draft].md"], keepingStaged: false, + message: "Before discarding 3 files") #expect(record.stash != nil) #expect(repository.read("a.txt") == "one\ntwo\nthree\n") #expect(repository.read("b.txt") == "x\n") @@ -54,7 +54,7 @@ struct DiscardTests { try repository.write("ONE\ntwo\nthree\nfour\n", to: "a.txt") // partially staged let before = try await repository.status() - let record = try await repository.discard(paths: ["a.txt"], untracked: [], keepingStaged: true, message: "Before discarding a.txt") + let record = try await repository.discard(paths: ["a.txt"], keepingStaged: true, message: "Before discarding a.txt") #expect(repository.read("a.txt") == "one\ntwo\nthree\nfour\n") let middle = try await repository.status() #expect(middle.entries.first?.stageState == .staged) @@ -73,7 +73,7 @@ struct DiscardTests { let repository = try await makeRepository() defer { TestRepositories.remove(repository) } try repository.write("draft\n", to: "new.txt") - let record = try await repository.discard(paths: ["new.txt"], untracked: ["new.txt"], keepingStaged: false, message: "Before discarding new.txt") + let record = try await repository.discard(paths: ["new.txt"], keepingStaged: false, message: "Before discarding new.txt") try repository.write("something else\n", to: "new.txt") await #expect(throws: GitError.self) { try await repository.restore(record) @@ -82,6 +82,296 @@ struct DiscardTests { } } +/// What is at a path isn't always what git's list says of it. Discard puts HEAD's files back with `git restore`, +/// which writes over whatever is there, so whatever it would take has to be in the copy first, or stay. +@Suite("Discard, and what else is at a file's place (integration)", .hangGuard) +struct DiscardInTheWayTests { + /// `git rm --cached` takes a file out of the index and leaves it on disk, a file of its own from then on: git + /// lists the path a second time as untracked, or only the deletion when the file is ignored. Discarding the + /// deletion puts HEAD's file there, so the one on disk goes in the copy, and ⌘Z brings it back. + @Test(arguments: [false, true]) func keepsTheFileAStagedDeletionLeftOnDisk(ignored: Bool) async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("shared settings\n", to: "config.local") + try await repository.commitAll("add the config") + if ignored { + try repository.write("config.local\n", to: ".gitignore") + try await repository.commitAll("the config is everyone's own") + } + try await repository.git(["rm", "-q", "--cached", "config.local"]) + try repository.write("my own settings\n", to: "config.local") + let before = try await repository.status() + #expect(before.entries.map(\.isUntracked) == (ignored ? [false] : [false, true])) + + let record = try await repository.discard(paths: ["config.local"], keepingStaged: false, + message: "Before discarding config.local") + #expect(repository.read("config.local") == "shared settings\n") + #expect(try await repository.status().entries.isEmpty) + + try await repository.restore(record) + #expect(repository.read("config.local") == "my own settings\n") + #expect(try await repository.status().entries == before.entries) + #expect(try await repository.stashes().isEmpty) + + // ⇧⌘Z and ⌘Z once more. + let again = try await repository.discardAgain(record, message: "Before discarding config.local") + #expect(repository.read("config.local") == "shared settings\n") + try await repository.restore(again) + #expect(repository.read("config.local") == "my own settings\n") + #expect(try await repository.status().entries == before.entries) + } + + /// The copy in Stashes shows the path once, as a change to HEAD's file, and `git stash apply` reads it. + @Test func theCopyOfSuchAFileAppliesByHand() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("shared settings\n", to: "config.local") + try await repository.commitAll("add the config") + try await repository.git(["rm", "-q", "--cached", "config.local"]) + try repository.write("my own settings\n", to: "config.local") + + let record = try await repository.discard(paths: ["config.local"], keepingStaged: false, + message: "Before discarding config.local") + let stash = try #require(record.stash) + #expect(try await repository.git(["stash", "show", "--include-untracked", "--name-only", stash]).text == "config.local\n") + try await repository.git(["stash", "apply", "--index", stash]) + #expect(repository.read("config.local") == "my own settings\n") + #expect(try await repository.git(["ls-files", "--", "config.local"]).text.isEmpty) + } + + /// HEAD's file is at the path after Discard. Once it has changed, ⌘Z leaves it and the copy stays in Stashes. + @Test func undoLeavesAChangedFileAtTheStagedDeletionsPath() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("shared settings\n", to: "config.local") + try await repository.commitAll("add the config") + try await repository.git(["rm", "-q", "--cached", "config.local"]) + try repository.write("my own settings\n", to: "config.local") + + let record = try await repository.discard(paths: ["config.local"], keepingStaged: false, message: "x") + try repository.write("edited since\n", to: "config.local") + await #expect(throws: GitError.self) { try await repository.restore(record) } + #expect(repository.read("config.local") == "edited since\n") + #expect(try await repository.stashes().count == 1) + } + + /// On a disk that doesn't tell `Config` from `config`, the file left there can have another case by now. It is + /// the same file to the disk, so HEAD's file goes over it all the same. + @Test func keepsTheFileLeftOnDiskUnderAnotherCase() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("shared settings\n", to: "Config.local") + try await repository.commitAll("add the config") + try await repository.git(["rm", "-q", "--cached", "Config.local"]) + let folder = repository.root.path(percentEncoded: false) + try FileManager.default.moveItem(atPath: folder + "/Config.local", toPath: folder + "/config.tmp") + try FileManager.default.moveItem(atPath: folder + "/config.tmp", toPath: folder + "/config.local") + try repository.write("my own settings\n", to: "config.local") + // A disk that tells the two names apart has no file at the staged deletion's path: nothing to keep. + guard repository.read("Config.local") != nil else { return } + + let record = try await repository.discard(paths: ["Config.local"], keepingStaged: false, message: "x") + #expect(repository.read("Config.local") == "shared settings\n") + try await repository.restore(record) + #expect(repository.read("config.local") == "my own settings\n") + #expect(try await repository.git(["ls-files", "--", "Config.local"]).text.isEmpty) + } + + /// Names git would read as patterns or as its own notation are names here, and a link is kept as a link. + @Test func keepsFilesWithNamesGitReadsAsPatterns() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + let names = ["notes/[draft].md", ":odd", "notes/*.md"] + for name in names { try repository.write("shared \(name)\n", to: name) } + try repository.write("shared d\n", to: "notes/d.md") + try repository.write("the target\n", to: "target.txt") + try await repository.commitAll("base") + try await repository.git(["rm", "-q", "--cached", "--"] + names.map { ":(literal)" + $0 }) + for name in names.dropLast() { try repository.write("my own \(name)\n", to: name) } + let link = repository.root.appending(path: "notes/*.md").path(percentEncoded: false) + try FileManager.default.removeItem(atPath: link) + try FileManager.default.createSymbolicLink(atPath: link, withDestinationPath: "../target.txt") + try repository.write("d, edited\n", to: "notes/d.md") // matches both patterns; not discarded + let before = try await repository.status() + + let record = try await repository.discard(paths: names, keepingStaged: false, message: "x") + for name in names { #expect(repository.read(name) == "shared \(name)\n") } + #expect(repository.read("notes/d.md") == "d, edited\n") + #expect(try await repository.status().entries.map(\.path) == ["notes/d.md"]) + + try await repository.restore(record) + for name in names.dropLast() { #expect(repository.read(name) == "my own \(name)\n") } + #expect(try FileManager.default.destinationOfSymbolicLink(atPath: link) == "../target.txt") + #expect(repository.read("target.txt") == "the target\n") + #expect(try await repository.status().entries == before.entries) + } + + /// Discard Unstaged Changes there: the deletion stays staged, and the file on disk is the unstaged part. + @Test func discardUnstagedTakesOnlyTheFileOnDisk() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("shared settings\n", to: "config.local") + try await repository.commitAll("add the config") + try await repository.git(["rm", "-q", "--cached", "config.local"]) + try repository.write("my own settings\n", to: "config.local") + let before = try await repository.status() + + let record = try await repository.discard(paths: ["config.local"], keepingStaged: true, + message: "Before discarding config.local") + #expect(repository.read("config.local") == nil) + #expect(try await repository.status().entries.map { "\($0.indexStatus)\($0.worktreeStatus)" } == ["D."]) + + try await repository.restore(record) + #expect(repository.read("config.local") == "my own settings\n") + #expect(try await repository.status().entries == before.entries) + #expect(try await repository.stashes().isEmpty) + } + + /// A staged rename takes the file from its old name too. A new file put there is one of those files. + @Test func keepsANewFileAtARenamedFilesOldName() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("the old file\n", to: "old.txt") + try await repository.commitAll("base") + try await repository.git(["mv", "old.txt", "new.txt"]) + try repository.write("a new file at the old name\n", to: "old.txt") + let before = try await repository.status() + + let record = try await repository.discard(paths: ["new.txt", "old.txt"], keepingStaged: false, + message: "Before discarding new.txt") + #expect(repository.read("old.txt") == "the old file\n") + #expect(repository.read("new.txt") == nil) + #expect(try await repository.status().entries.isEmpty) + + try await repository.restore(record) + #expect(repository.read("old.txt") == "a new file at the old name\n") + #expect(repository.read("new.txt") == "the old file\n") + #expect(try await repository.status().entries == before.entries) + } + + /// Where a deleted file was there is a folder now, with files of its own: git would take the folder and all + /// in it away for the file. Discard leaves it, and goes through once those files are discarded themselves. + @Test func leavesAFolderWhereADeletedFileWas() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("one\n", to: "data") + try await repository.commitAll("data is a file") + try FileManager.default.removeItem(at: repository.root.appending(path: "data")) + try repository.write("my notes\n", to: "data/notes.txt") + let before = try await repository.status() + + for keepingStaged in [false, true] { + await #expect(throws: GitError.self) { + _ = try await repository.discard(paths: ["data"], keepingStaged: keepingStaged, message: "x") + } + #expect(repository.read("data/notes.txt") == "my notes\n") + } + await #expect(throws: GitError.self) { + _ = try await repository.discard(paths: ["data", "data/notes.txt"], keepingStaged: false, message: "x") + } + #expect(repository.read("data/notes.txt") == "my notes\n") + #expect(try await repository.stashes().isEmpty) + + let notes = try await repository.discard(paths: ["data/notes.txt"], keepingStaged: false, message: "x") + let file = try await repository.discard(paths: ["data"], keepingStaged: false, message: "x") + #expect(repository.read("data") == "one\n") + try await repository.restore(file) + try await repository.restore(notes) + #expect(repository.read("data/notes.txt") == "my notes\n") + #expect(try await repository.status().entries == before.entries) + } + + /// The same for the folders a deleted file was in: a file of that name now would go for the folder. + @Test func leavesAFileWhereADeletedFilesFolderWas() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("the guide\n", to: "docs/guide/a.md") + try await repository.commitAll("a guide") + try FileManager.default.removeItem(at: repository.root.appending(path: "docs")) + try repository.write("my own file\n", to: "docs") + + await #expect(throws: GitError.self) { + _ = try await repository.discard(paths: ["docs/guide/a.md"], keepingStaged: false, message: "x") + } + #expect(repository.read("docs") == "my own file\n") + await #expect(throws: GitError.self) { + _ = try await repository.discard(paths: ["docs", "docs/guide/a.md"], keepingStaged: false, message: "x") + } + #expect(repository.read("docs") == "my own file\n") + #expect(try await repository.stashes().isEmpty) + } + + /// A file that became a folder, all of it staged, is in the patches whole: nothing is in the way there. + @Test func discardsAFileThatBecameAFolderOfTrackedFiles() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("one\n", to: "a") + try await repository.commitAll("a is a file") + try await repository.git(["rm", "-q", "a"]) + try repository.write("inside\n", to: "a/b.txt") + try await repository.stage(["a/b.txt"]) + try repository.write("inside, edited\n", to: "a/b.txt") + let before = try await repository.status() + + let record = try await repository.discard(paths: ["a", "a/b.txt"], keepingStaged: false, message: "x") + #expect(repository.read("a") == "one\n") + #expect(try await repository.status().entries.isEmpty) + + try await repository.restore(record) + #expect(repository.read("a/b.txt") == "inside, edited\n") + #expect(try await repository.status().entries == before.entries) + } + + /// And the other way round: a folder of tracked files that became one file. + @Test func discardsAFolderThatBecameATrackedFile() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("inside\n", to: "a/b.txt") + try await repository.commitAll("a is a folder") + try await repository.git(["rm", "-q", "a/b.txt"]) + try repository.write("one\n", to: "a") + try await repository.stage(["a"]) + try repository.write("one, edited\n", to: "a") + let before = try await repository.status() + + let record = try await repository.discard(paths: ["a", "a/b.txt"], keepingStaged: false, message: "x") + #expect(repository.read("a/b.txt") == "inside\n") + #expect(try await repository.status().entries.isEmpty) + + try await repository.restore(record) + #expect(repository.read("a") == "one, edited\n") + #expect(try await repository.status().entries == before.entries) + } + + /// Without a commit git has nothing to make a stash from, so there is no copy: nothing is thrown away then. + @Test func discardsNothingItCannotKeepACopyOf() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("a draft\n", to: "draft.txt") + + await #expect(throws: GitError.self) { + _ = try await repository.discard(paths: ["draft.txt"], keepingStaged: false, message: "x") + } + #expect(repository.read("draft.txt") == "a draft\n") + } + + /// ⌘Z puts a discarded untracked file back with `git restore` too: a file where its folder was stays. + @Test func undoLeavesAFileWhereTheDiscardedFilesFolderWas() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("base\n", to: "a.txt") + try await repository.commitAll("base") + try repository.write("a draft\n", to: "notes/draft.md") + let record = try await repository.discard(paths: ["notes/draft.md"], keepingStaged: false, message: "x") + try FileManager.default.removeItem(at: repository.root.appending(path: "notes")) + try repository.write("something else\n", to: "notes") + + await #expect(throws: GitError.self) { try await repository.restore(record) } + #expect(repository.read("notes") == "something else\n") + #expect(try await repository.stashes().count == 1) + } +} + @Suite("Ignore", .hangGuard) struct IgnoreTests { @Test func patternsForAPath() { @@ -127,3 +417,189 @@ struct IgnoreTests { #expect(repository.read(".gitignore") == nil) } } + +/// Restore Version: a file as a commit has it, unstaged, after keeping the file's own changes; ⌘Z puts it back. +@Suite("Restore a file's version (integration)", .hangGuard) +struct RestoreVersionTests { + @Test func restoresAVersionUnstagedAndTakesItBack() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("one\n", to: "a.txt") + let first = try await repository.commitAll("one") + try repository.write("two\n", to: "a.txt") + try await repository.commitAll("two") + + let restore = try await repository.restoreVersion(of: "a.txt", at: first, message: "Before restoring a.txt") + #expect(restore.record == nil) + #expect(repository.read("a.txt") == "one\n") + let status = try await repository.status() + #expect(status.entries.map { "\($0.indexStatus)\($0.worktreeStatus) \($0.path)" } == [".M a.txt"]) + + try await repository.undoRestore(restore) + #expect(repository.read("a.txt") == "two\n") + #expect(try await repository.status().entries.isEmpty) + } + + @Test func keepsTheFilesOwnChangesAndBringsThemBack() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("one\n", to: "a.txt") + let first = try await repository.commitAll("one") + try repository.write("two\n", to: "a.txt") + try await repository.commitAll("two") + try repository.write("staged\n", to: "a.txt") + try await repository.stage(["a.txt"]) + try repository.write("local\n", to: "a.txt") + + let restore = try await repository.restoreVersion(of: "a.txt", at: first, message: "Before restoring a.txt") + #expect(restore.record?.stash != nil) + #expect(repository.read("a.txt") == "one\n") + #expect(try await repository.git(["show", ":a.txt"]).text == "two\n") + #expect(try await repository.stashes().first?.message.hasSuffix("Before restoring a.txt") == true) + + try await repository.undoRestore(restore) + #expect(repository.read("a.txt") == "local\n") + #expect(try await repository.git(["show", ":a.txt"]).text == "staged\n") + #expect(try await repository.stashes().isEmpty) + } + + @Test func bringsBackAFileHeadDeletedAndRefusesOnceItChanged() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("keep\n", to: "k.txt") + try repository.write("gee\n", to: "g.txt") + let first = try await repository.commitAll("add g") + try await repository.git(["rm", "-q", "g.txt"]) + try await repository.commit(message: "remove g", amend: false) + + let restore = try await repository.restoreVersion(of: "g.txt", at: first, message: "Before restoring g.txt") + #expect(repository.read("g.txt") == "gee\n") + #expect(try await repository.status().entries.map(\.isUntracked) == [true]) + try repository.write("edited\n", to: "g.txt") + await #expect(throws: GitError.self) { try await repository.undoRestore(restore) } + try repository.write("gee\n", to: "g.txt") + try await repository.undoRestore(restore) + #expect(repository.read("g.txt") == nil) + #expect(try await repository.status().entries.isEmpty) + + await #expect(throws: GitError.self) { _ = try await repository.restoreVersion(of: "missing.txt", at: first, message: "x") } + } + + /// A file git once tracked and now ignores (a config taken out of the repository) can be there with contents of + /// its own. `git status` doesn't list ignored files, so it has to be looked for: its contents are kept like any + /// file's changes, and ⌘Z brings them back. + @Test func keepsAnIgnoredFileThatIsInTheWay() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("shared settings\n", to: "config.local") + let first = try await repository.commitAll("add the config") + try await repository.git(["rm", "-q", "--cached", "config.local"]) + try repository.write("config.local\n", to: ".gitignore") + try await repository.commitAll("the config is everyone's own") + try repository.write("my own settings\n", to: "config.local") + #expect(try await repository.status().entries.isEmpty) + + let restore = try await repository.restoreVersion(of: "config.local", at: first, message: "Before restoring config.local") + #expect(repository.read("config.local") == "shared settings\n") + #expect(restore.record?.stash != nil) + #expect(try await repository.stashes().first?.message.hasSuffix("Before restoring config.local") == true) + + try await repository.undoRestore(restore) + #expect(repository.read("config.local") == "my own settings\n") + #expect(try await repository.stashes().isEmpty) + #expect(try await repository.status().entries.isEmpty) + } + + /// `git rm --cached` leaves the file on disk, a file of its own by then, next to the staged deletion (listed a + /// second time as untracked, or not at all when it's ignored). Its contents are kept, and ⌘Z brings them back. + @Test(arguments: [false, true]) func keepsTheFileAStagedDeletionLeftOnDisk(ignored: Bool) async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("shared settings\n", to: "config.local") + let first = try await repository.commitAll("add the config") + try repository.write("shared settings, newer\n", to: "config.local") + if ignored { try repository.write("config.local\n", to: ".gitignore") } + try await repository.git(["add", "-f", "config.local"]) + try await repository.commitAll("newer settings") + try await repository.git(["rm", "-q", "--cached", "config.local"]) + try repository.write("my own settings\n", to: "config.local") + let before = try await repository.status() + #expect(before.entries.map(\.isUntracked) == (ignored ? [false] : [false, true])) + + let restore = try await repository.restoreVersion(of: "config.local", at: first, message: "Before restoring config.local") + #expect(repository.read("config.local") == "shared settings\n") + #expect(try await repository.stashes().first?.message.hasSuffix("Before restoring config.local") == true) + + try await repository.undoRestore(restore) + #expect(repository.read("config.local") == "my own settings\n") + #expect(try await repository.status().entries == before.entries) + #expect(try await repository.stashes().isEmpty) + } + + /// Where the file was, there is a folder now, with files git doesn't list one by one at that path: git would + /// put the file there and take the folder and all in it away. Kaern leaves it. + @Test func leavesAFolderThatIsInTheWay() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("one\n", to: "data") + let first = try await repository.commitAll("data is a file") + try await repository.git(["rm", "-q", "data"]) + try await repository.commit(message: "no data", amend: false) + try FileManager.default.createDirectory(at: repository.root.appending(path: "data"), withIntermediateDirectories: true) + try repository.write("my notes\n", to: "data/notes.txt") + + await #expect(throws: GitError.self) { _ = try await repository.restoreVersion(of: "data", at: first, message: "x") } + #expect(repository.read("data/notes.txt") == "my notes\n") + #expect(try await repository.stashes().isEmpty) + } + + /// The same for the folders the file was in: a file of that name now, or a link, would go for the folder. + @Test func leavesAFileOrALinkWhereItsFolderWas() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("one\n", to: "docs/guide/a.md") + let first = try await repository.commitAll("a guide") + try await repository.git(["rm", "-rq", "docs"]) + try await repository.commit(message: "no docs", amend: false) + + try repository.write("my own file\n", to: "docs") + await #expect(throws: GitError.self) { _ = try await repository.restoreVersion(of: "docs/guide/a.md", at: first, message: "x") } + #expect(repository.read("docs") == "my own file\n") + + let docs = repository.root.appending(path: "docs").path(percentEncoded: false) + try FileManager.default.removeItem(atPath: docs) + try FileManager.default.createDirectory(atPath: docs, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(atPath: docs + "/guide", withDestinationPath: "elsewhere") + await #expect(throws: GitError.self) { _ = try await repository.restoreVersion(of: "docs/guide/a.md", at: first, message: "x") } + #expect(try FileManager.default.destinationOfSymbolicLink(atPath: docs + "/guide") == "elsewhere") + + // With the folders as folders, or not there at all, it goes through. + try FileManager.default.removeItem(atPath: docs) + _ = try await repository.restoreVersion(of: "docs/guide/a.md", at: first, message: "x") + #expect(repository.read("docs/guide/a.md") == "one\n") + } + + /// A symbolic link's blob is where it points, not what is there: ⌘Z still knows the link it restored, a link + /// that points nowhere too. + @Test func takesBackARestoredSymbolicLink() async throws { + let repository = try await TestRepositories.make() + defer { TestRepositories.remove(repository) } + try repository.write("the target\n", to: "target.txt") + try FileManager.default.createSymbolicLink(atPath: repository.root.appending(path: "link").path(percentEncoded: false), + withDestinationPath: "target.txt") + try FileManager.default.createSymbolicLink(atPath: repository.root.appending(path: "nowhere").path(percentEncoded: false), + withDestinationPath: "missing.txt") + let first = try await repository.commitAll("links") + try await repository.git(["rm", "-q", "link", "nowhere"]) + try await repository.commit(message: "no links", amend: false) + + for name in ["link", "nowhere"] { + let restore = try await repository.restoreVersion(of: name, at: first, message: "Before restoring \(name)") + let path = repository.root.appending(path: name).path(percentEncoded: false) + #expect(try FileManager.default.destinationOfSymbolicLink(atPath: path) == (name == "link" ? "target.txt" : "missing.txt")) + try await repository.undoRestore(restore) + #expect((try? FileManager.default.destinationOfSymbolicLink(atPath: path)) == nil) + } + #expect(try await repository.status().entries.isEmpty) + } +} diff --git a/Packages/KaernKit/Tests/KaernKitTests/IndicatorTests.swift b/Packages/KaernKit/Tests/KaernKitTests/IndicatorTests.swift index 57143d4..b8ae4bd 100644 --- a/Packages/KaernKit/Tests/KaernKitTests/IndicatorTests.swift +++ b/Packages/KaernKit/Tests/KaernKitTests/IndicatorTests.swift @@ -33,6 +33,23 @@ struct IndicatorTests { #expect(change?.old?.size == 48_200_000) #expect(change?.new?.size == 51_000_000) #expect(FileDiff(path: "a.txt", hunks: []).lfsChange == nil) + // An ordinary file, and one that only mentions a pointer's first line inside a line. + let code = DiffHunk(id: 0, oldStart: 1, oldCount: 2, newStart: 1, newCount: 2, section: "", lines: [ + line(.context, "let name = \"Kaern\"", 0), + line(.deletion, "// see version https://git-lfs.github.com/spec/v1", 1), + line(.addition, "let count = 2", 2), + ]) + #expect(FileDiff(path: "a.swift", hunks: [code]).lfsChange == nil) + // A file that became a pointer: only its new side is one. + let moved = DiffHunk(id: 0, oldStart: 1, oldCount: 1, newStart: 1, newCount: 3, section: "", lines: [ + line(.deletion, "plain text", 0), + line(.addition, "version https://git-lfs.github.com/spec/v1", 1), + line(.addition, "oid sha256:ccc", 2), + line(.addition, "size 12", 3), + ]) + let became = FileDiff(path: "Assets/a.bin", hunks: [moved]).lfsChange + #expect(became?.old == nil) + #expect(became?.new?.size == 12) } @Test func listsWorktrees() async throws { diff --git a/Packages/KaernKit/Tests/KaernKitTests/RepositoryTests.swift b/Packages/KaernKit/Tests/KaernKitTests/RepositoryTests.swift index 3d5e7ca..421fbb7 100644 --- a/Packages/KaernKit/Tests/KaernKitTests/RepositoryTests.swift +++ b/Packages/KaernKit/Tests/KaernKitTests/RepositoryTests.swift @@ -289,3 +289,79 @@ final class LockedLines: Sendable { func append(_ line: String) { lines.withLock { $0.append(line) } } var count: Int { lines.withLock { $0.count } } } + +/// Git and its hooks find programs on the login shell's PATH once the app has it, as in Terminal. +@Suite("The login shell's PATH (integration)", .hangGuard) +struct SearchPathTests { + @Test func aHookFindsAProgramOnlyTheLoginShellHas() async throws { + let tools = FileManager.default.temporaryDirectory.appending(path: "kaern-tools-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tools, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tools) } + let tool = tools.appending(path: "kaern-hook-tool") + try Data("#!/bin/sh\nexit 0\n".utf8).write(to: tool) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: tool.path(percentEncoded: false)) + + let searchPath = GitSearchPath() + var runner = RepositoryTests.runner + runner.searchPath = searchPath + let url = FileManager.default.temporaryDirectory.appending(path: "kaern-tests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + let repository = try await GitRepository.initialize(at: url, defaultBranch: "main", runner: runner) + defer { TestRepositories.remove(repository) } + try repository.write("#!/bin/sh\nkaern-hook-tool\n", to: ".git/hooks/pre-commit") + try FileManager.default.setAttributes([.posixPermissions: 0o755], + ofItemAtPath: url.appending(path: ".git/hooks/pre-commit").path(percentEncoded: false)) + try repository.write("a\n", to: "a.txt") + try await repository.stageAll() + + // Kaern's own PATH: the hook can't find the tool. + await #expect(throws: GitError.self) { try await repository.commit(message: "first", amend: false) } + + // While the app reads the login shell's PATH, a commit waits for it, then the hook finds the tool. + searchPath.expect() + let answer = Task { + try await Task.sleep(for: .milliseconds(300)) + searchPath.provide(tools.path(percentEncoded: false) + ":/usr/bin:/bin") + } + try await repository.commit(message: "first", amend: false) + try await answer.value + #expect(try await repository.git(["log", "-1", "--format=%s"]).text.trimmingCharacters(in: .whitespacesAndNewlines) == "first") + + // A command that runs no hook doesn't wait; the folders come first in its PATH, Kaern's after. + let merged = GitSearchPath.merged(["/a", "/b"], before: "/b:/c::/a") + #expect(merged == "/a:/b:/c") + } + + /// Reading a repository waits for nothing: its worktrees are listed on every first load, while the app may + /// still be reading the login shell's PATH. + @Test func onlyCommandsThatStartHooksWait() async throws { + #expect(GitSearchPath.waits(for: ["commit", "-m", "x"])) + #expect(GitSearchPath.waits(for: ["-c", "core.hooksPath=/dev/null", "switch", "main"])) + #expect(GitSearchPath.waits(for: ["worktree", "add", "--detach", "/tmp/a", "HEAD"])) + #expect(!GitSearchPath.waits(for: ["worktree", "list", "--porcelain"])) + #expect(!GitSearchPath.waits(for: ["worktree", "remove", "/tmp/a"])) + #expect(!GitSearchPath.waits(for: ["status", "--porcelain=v2"])) + #expect(!GitSearchPath.waits(for: ["log", "--format=%H", "worktree"])) + #expect(!GitSearchPath.waits(for: [])) + + // The login shell hasn't answered: a repository's worktrees are listed all the same. + let searchPath = GitSearchPath() + searchPath.expect() + var runner = RepositoryTests.runner + runner.searchPath = searchPath + let url = FileManager.default.temporaryDirectory.appending(path: "kaern-tests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + let repository = try await GitRepository.initialize(at: url, defaultBranch: "main", runner: runner) + defer { TestRepositories.remove(repository) } + #expect(await repository.worktrees().count == 1) + searchPath.provide(nil) + } + + @Test func nothingChangesWhenTheLoginShellCantBeRead() async throws { + let searchPath = GitSearchPath() + searchPath.expect() + searchPath.provide(nil) + #expect(await searchPath.folders(waiting: true) == nil) + #expect(searchPath.applied(to: ["PATH": "/usr/bin"]) == ["PATH": "/usr/bin"]) + } +} diff --git a/Packages/KaernKit/Tests/KaernKitTests/SyntaxTests.swift b/Packages/KaernKit/Tests/KaernKitTests/SyntaxTests.swift new file mode 100644 index 0000000..23b5cf4 --- /dev/null +++ b/Packages/KaernKit/Tests/KaernKitTests/SyntaxTests.swift @@ -0,0 +1,145 @@ +import Foundation +import Testing +@testable import KaernKit + +/// Diff lines colored by their language, a line at a time with what goes on carried along. +@Suite("Syntax highlighting") +struct SyntaxTests { + /// The colored pieces of each line, as text and kind. + private func colored(_ lines: [String], _ path: String) throws -> [[String]] { + let language = try #require(SyntaxHighlighter.language(forPath: path)) + return zip(lines, SyntaxHighlighter.highlight(lines, in: language)).map { line, spans in + let characters = Array(line) + return spans.map { "\($0.kind):" + String(characters[$0.range]) } + } + } + + @Test func findsTheLanguageByName() { + #expect(SyntaxHighlighter.language(forPath: "Kaern/App/main.swift")?.name == "Swift") + #expect(SyntaxHighlighter.language(forPath: ".github/workflows/ci.yml")?.name == "YAML") + #expect(SyntaxHighlighter.language(forPath: "Package.resolved")?.name == "JSON") + #expect(SyntaxHighlighter.language(forPath: "ios/Podfile")?.name == "Ruby") + #expect(SyntaxHighlighter.language(forPath: "Dockerfile")?.name == "Dockerfile") + #expect(SyntaxHighlighter.language(forPath: "Makefile")?.name == "Make") + #expect(SyntaxHighlighter.language(forPath: "web/App.tsx")?.name == "TypeScript") + #expect(SyntaxHighlighter.language(forPath: "notes.txt") == nil) + #expect(SyntaxHighlighter.language(forPath: "LICENSE") == nil) + } + + @Test func swift() throws { + #expect(try colored(["let name = \"Kaern\" // the app", "@MainActor final class Model: View {", "#if DEBUG", + " let text = \"\"\"", " two \"lines\"", " \"\"\"; run(0x1F, 2.5e3)"], "a.swift") == [ + ["keyword:let", "string:\"Kaern\"", "comment:// the app"], + ["attribute:@MainActor", "keyword:final", "keyword:class", "type:Model", "type:View"], + ["preprocessor:#if"], + ["keyword:let", "string:\"\"\""], + ["string: two \"lines\""], + ["string: \"\"\"", "function:run", "number:0x1F", "number:2.5e3"], + ]) + } + + @Test func python() throws { + #expect(try colored(["@app.route(\"/\")", "def run(path): # go", " \"\"\"Docs", " more\"\"\"", + " return f\"{path}\" if path else None"], "tool.py") == [ + ["attribute:@app", "function:route", "string:\"/\""], + ["keyword:def", "function:run", "comment:# go"], + ["string:\"\"\"Docs"], + ["string: more\"\"\""], + ["keyword:return", "string:f\"{path}\"", "keyword:if", "keyword:else", "constant:None"], + ]) + } + + @Test func javascriptAndCComments() throws { + #expect(try colored(["const total = `a", "b ${x}` /* note", "end */ + 1;"], "app.js") == [ + ["keyword:const", "string:`a"], + ["string:b ${x}`", "comment:/* note"], + ["comment:end */", "number:1"], + ]) + #expect(try colored(["#include ", "int main(void) { return 0; }"], "main.c") == [ + ["preprocessor:#include "], + ["keyword:int", "function:main", "keyword:void", "keyword:return", "number:0"], + ]) + } + + @Test func yamlKeysAndApostrophes() throws { + #expect(try colored(["name: Kaern's tests # the suite", " - run: echo \"hi\"", "on: [push]", "url: http://a#b"], "ci.yml") == [ + ["property:name", "comment:# the suite"], + ["property:run", "string:\"hi\""], + ["property:on"], + ["property:url"], + ]) + } + + @Test func shellJSONAndMarkup() throws { + #expect(try colored(["echo \"$HOME\" a#b # done", "if [ -n \"$1\" ]; then exit 1; fi"], "build.sh") == [ + ["keyword:echo", "string:\"$HOME\"", "comment:# done"], + ["keyword:if", "string:\"$1\"", "keyword:then", "keyword:exit", "number:1", "keyword:fi"], + ]) + #expect(try colored([" \"name\": \"kaern\", \"count\": 2, \"ok\": true"], "package.json") == [ + ["property:\"name\"", "string:\"kaern\"", "property:\"count\"", "number:2", "property:\"ok\"", "constant:true"], + ]) + #expect(try colored(["