From dbc9f782461e6a45b0bc89dd1a1518b23cd2032b Mon Sep 17 00:00:00 2001 From: progresshans Date: Mon, 30 Nov 2026 15:42:28 +0900 Subject: [PATCH 01/15] feat: delete a tag here, or here and on its remote MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A tag's right-click menu (the sidebar's Tags, a tag's label in the history) had no way to delete it: only ⌘Z right after Create Tag Here… did. It now has, as a branch's menu does: - Delete (⌫): the tag goes from the repository, and ⌘Z makes it again with the object it had, so an annotated tag keeps its message and signature (⇧⌘Z deletes it again while it's still that one). The remote keeps its copy, so a fetch brings the tag back while the remote has it. - Delete Here and on origin…: asks first, since Kaern can't undo a change on a remote, then deletes it there and here. A tag the remote doesn't have goes from here only, and the toast says so. KaernKit's deleteRemoteTag names the tag in full (refs/tags/), so a branch with the same name stays, and asks the remote first with ls-remote, because a push deleting a ref the remote doesn't have succeeds all the same. Checked: a KaernKit test (delete, restore as the same annotated tag, delete on a bare remote beside a same-named branch, and again when it's gone) and the new flow check t_tags (both menu items, ⌘Z, ⇧⌘Z, the question, a tag only here); both passed. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + .../Repository/RepositoryModel+Actions.swift | 27 +++++++ Kaern/Repository/RepositoryModel+Undo.swift | 15 ++++ Kaern/Views/Menus/ContextMenus.swift | 5 ++ .../KaernKit/Git/GitRepository+Branches.swift | 11 +++ .../Tests/KaernKitTests/BranchTagTests.swift | 31 ++++++++ checks/suite.py | 1 + checks/t_tags.py | 79 +++++++++++++++++++ 8 files changed, 171 insertions(+) create mode 100644 checks/t_tags.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f6c5889..37f8917 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ 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. ### Improved diff --git a/Kaern/Repository/RepositoryModel+Actions.swift b/Kaern/Repository/RepositoryModel+Actions.swift index 2d2eec7..578805f 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?) { diff --git a/Kaern/Repository/RepositoryModel+Undo.swift b/Kaern/Repository/RepositoryModel+Undo.swift index 2103b31..93ce6ea 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, diff --git a/Kaern/Views/Menus/ContextMenus.swift b/Kaern/Views/Menus/ContextMenus.swift index 332d863..50657a7 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 } 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/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/checks/suite.py b/checks/suite.py index e9de906..4577177 100644 --- a/checks/suite.py +++ b/checks/suite.py @@ -94,6 +94,7 @@ def __init__(self, name, areas, dark=False, alone=False, samples=('base',), seco Check('t_firstload', 'launch history changes', seconds=8), Check('t_remotemore', 'sidebar', samples=('base', 'remotes-3000'), seconds=12), Check('t_openin', 'openin menus layout review changes settings', dark=True, seconds=14), + Check('t_tags', 'menus undo sidebar', seconds=8), ] BY_NAME = {c.name: c for c in CHECKS} diff --git a/checks/t_tags.py b/checks/t_tags.py new file mode 100644 index 0000000..9187631 --- /dev/null +++ b/checks/t_tags.py @@ -0,0 +1,79 @@ +"""t_tags.py [light|dark] — a tag's right-click menu deletes it. Delete takes it from here: ⌘Z makes it again with the +object it had (an annotated tag keeps its message), ⇧⌘Z deletes it again. Delete Here and on origin… asks first, then +takes it from the remote too; a tag the remote doesn't have goes from here only. Menus are read and chosen through +`menuItems` and `menuRun`.""" +import json, os, sys +sys.path.insert(0, os.path.dirname(__file__)) +from k5 import * +from k5 import _file +mode = sys.argv[1] if len(sys.argv) > 1 else 'light' +PUSHED, LOCAL = 'v-check-pushed', 'v-check-local' +WHO = ['-c', 'user.name=HH', '-c', 'user.email=hh@kaern.invalid'] + + +def prepare(): + """Two annotated tags on HEAD: one pushed to origin, one only here.""" + git(*WHO, 'tag', '-a', PUSHED, '-m', 'Pushed for the check') + git(*WHO, 'tag', '-a', LOCAL, '-m', 'Only here') + git('push', '-q', 'origin', 'refs/tags/' + PUSHED) + + +_menus = [0] + + +def menu(name): + """The tag's right-click menu: {title: (hint, enabled)}.""" + _menus[0] += 1 + os.makedirs(REPLIES, exist_ok=True) + path = os.path.join(REPLIES, 'tag-%d-%d.json' % (os.getpid(), _menus[0])) + k('menuItems', path, 'tag', name) + return {i['title']: (i['hint'], i['enabled']) for i in json.loads(_file(path)) if 'title' in i} + + +def here(name): return git('rev-parse', '--verify', '-q', 'refs/tags/' + name) +def on_origin(name): return git('ls-remote', '--tags', 'origin', 'refs/tags/' + name) != '' + + +launch_prepared(mode, prepare=prepare) +show_tab('powerlens') +settle(label='powerlens') +pushed = here(PUSHED) +assert pushed and git('cat-file', '-t', pushed) == 'tag' and on_origin(PUSHED) and here(LOCAL) and not on_origin(LOCAL) + +items = menu(PUSHED) +print('menu:', items) +assert items['Delete'] == ('', True), items +assert items['Delete Here and on origin…'] == ('', True), items + +# Delete: gone from here, still on origin; ⌘Z makes the same annotated tag again, ⇧⌘Z deletes it again. +k('menuRun', 'tag', PUSHED, '|', 'Delete') +d = settle(lambda d: not here(PUSHED), label='%s deleted here' % PUSHED) +assert toast(d) == 'Deleted %s · ⌘Z brings it back' % PUSHED, toast(d) +assert on_origin(PUSHED), 'Delete leaves the remote’s' +k('undo') +settle(lambda d: here(PUSHED) == pushed, label='⌘Z making it again') +assert git('cat-file', '-t', PUSHED) == 'tag' and 'Pushed for the check' in git('cat-file', '-p', PUSHED) +k('redo') +settle(lambda d: not here(PUSHED), label='⇧⌘Z deleting it again') +k('undo') +settle(lambda d: here(PUSHED) == pushed, label='⌘Z once more') +print('Delete, ⌘Z, ⇧⌘Z, ⌘Z: the tag as it was') + +# Delete Here and on origin…: a question, then gone from both. +k('menuRun', 'tag', PUSHED, '|', 'Delete Here and on origin…') +d = until(lambda d: (d['active']['confirmation'] or {}).get('title') == 'Delete %s here and on origin?' % PUSHED, label='the question') +snap('tags-delete-everywhere', mode) +k('confirm') +d = settle(lambda d: not here(PUSHED) and not on_origin(PUSHED), label='%s gone here and on origin' % PUSHED) +assert toast(d) == 'Deleted %s here and on origin' % PUSHED, toast(d) +print('Delete Here and on origin…:', toast(d)) + +# A tag origin doesn't have: it goes from here, and the toast says origin didn't have it. +k('menuRun', 'tag', LOCAL, '|', 'Delete Here and on origin…') +until(lambda d: (d['active']['confirmation'] or {}).get('title') == 'Delete %s here and on origin?' % LOCAL, label='the question') +k('confirm') +d = settle(lambda d: not here(LOCAL), label='%s gone here' % LOCAL) +assert toast(d) == 'Deleted %s · origin didn’t have it' % LOCAL, toast(d) +print('a tag only here:', toast(d)) +quit_app() +print('TAGS OK') From 2aae49966a19da0d6cd6963cf373947b9589d100 Mon Sep 17 00:00:00 2001 From: progresshans Date: Mon, 30 Nov 2026 15:46:44 +0900 Subject: [PATCH 02/15] feat: restore a file the way a commit has it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A commit's file (its details, Review's chips and headers) can be opened at that version, but there was no way to put the file back that way. Its right-click menu now has Restore Version at , below Open Version at: - The version goes into the working copy, unstaged: the index keeps HEAD's, so the change shows in Unstaged Files to review and stage. - The file's own changes, staged or not, go to Stashes first, as Discard keeps them ("Before restoring from "), and the toast says so. - ⌘Z takes the version back while the file is still it, then puts the file's changes back and drops the kept copy; ⇧⌘Z restores it again. A file HEAD doesn't have goes again. - A file the commit deleted restores the version before, from the parent (the version Open Version at and Blame at already use there), and comes back as a new file. KaernKit: restoreVersion(of:at:message:) (discard with a kept copy, then git restore --source= --worktree, so filters such as LFS apply) and undoRestore. A file with conflicts is refused. Checked: KaernKit tests (a clean file, one with staged and unstaged changes, a file HEAD deleted, ⌘Z refused once the file changed, a path the commit hasn't) and the new flow check t_restore (the menu item, the index, the kept copy, ⌘Z, ⇧⌘Z, a deleted file from the parent); all passed. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + .../Repository/RepositoryModel+Actions.swift | 14 +++ Kaern/Repository/RepositoryModel+Undo.swift | 12 +++ Kaern/Views/Menus/ContextMenus.swift | 3 + .../KaernKit/Git/GitRepository+Discard.swift | 53 +++++++++++ .../Tests/KaernKitTests/DiscardTests.swift | 68 ++++++++++++++ checks/suite.py | 1 + checks/t_restore.py | 91 +++++++++++++++++++ 8 files changed, 245 insertions(+) create mode 100644 checks/t_restore.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f6c5889..e9e74de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,9 @@ 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. +- 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. ### Improved diff --git a/Kaern/Repository/RepositoryModel+Actions.swift b/Kaern/Repository/RepositoryModel+Actions.swift index 2d2eec7..1df0abd 100644 --- a/Kaern/Repository/RepositoryModel+Actions.swift +++ b/Kaern/Repository/RepositoryModel+Actions.swift @@ -483,6 +483,20 @@ extension RepositoryModel { } } + /// 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+Undo.swift b/Kaern/Repository/RepositoryModel+Undo.swift index 2103b31..d03193d 100644 --- a/Kaern/Repository/RepositoryModel+Undo.swift +++ b/Kaern/Repository/RepositoryModel+Undo.swift @@ -316,6 +316,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/Views/Menus/ContextMenus.swift b/Kaern/Views/Menus/ContextMenus.swift index 332d863..101a685 100644 --- a/Kaern/Views/Menus/ContextMenus.swift +++ b/Kaern/Views/Menus/ContextMenus.swift @@ -501,6 +501,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/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Discard.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Discard.swift index ee261f3..a29151d 100644 --- a/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Discard.swift +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitRepository+Discard.swift @@ -89,6 +89,59 @@ 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)).") + } + let status = try await git(["status", "--porcelain=v2", "-z", "--untracked-files=all", "--", ":(literal)" + path]) + var record: DiscardRecord? + if let entry = StatusParser.parse(status.stdout).entries.first(where: { $0.path == path }) { + guard !entry.isConflicted else { + throw GitError(arguments: ["restore"], status: -1, message: "\(path) has conflicts. Resolve them first.") + } + let paths = Array(Set([entry.path, entry.originalPath].compactMap { $0 })).sorted() + record = try await discard(paths: paths, untracked: entry.isUntracked ? [entry.path] : [], 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 { + let now = try? await git(["hash-object", "--path=\(restore.path)", "--", restore.path]).text + .trimmingCharacters(in: .whitespacesAndNewlines) + guard now == 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) } + } +} + // MARK: - .gitignore /// A line added to the repository's `.gitignore`, with what the file held before (for ⌘Z). diff --git a/Packages/KaernKit/Tests/KaernKitTests/DiscardTests.swift b/Packages/KaernKit/Tests/KaernKitTests/DiscardTests.swift index 4a569af..82eacc8 100644 --- a/Packages/KaernKit/Tests/KaernKitTests/DiscardTests.swift +++ b/Packages/KaernKit/Tests/KaernKitTests/DiscardTests.swift @@ -127,3 +127,71 @@ 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") } + } +} diff --git a/checks/suite.py b/checks/suite.py index e9de906..e8db0b9 100644 --- a/checks/suite.py +++ b/checks/suite.py @@ -94,6 +94,7 @@ def __init__(self, name, areas, dark=False, alone=False, samples=('base',), seco Check('t_firstload', 'launch history changes', seconds=8), Check('t_remotemore', 'sidebar', samples=('base', 'remotes-3000'), seconds=12), Check('t_openin', 'openin menus layout review changes settings', dark=True, seconds=14), + Check('t_restore', 'menus changes undo', seconds=8), ] BY_NAME = {c.name: c for c in CHECKS} diff --git a/checks/t_restore.py b/checks/t_restore.py new file mode 100644 index 0000000..8b46b52 --- /dev/null +++ b/checks/t_restore.py @@ -0,0 +1,91 @@ +"""t_restore.py [light|dark] — a commit's file has Restore Version at… in its right-click menu: the file as that commit +has it goes into the working copy, unstaged (the index keeps HEAD's). Its own changes go to Stashes first, and ⌘Z puts +them back (⇧⌘Z restores again). A file the commit deleted restores the version before, from the parent. Menus are read +and chosen through `menuItems` and `menuRun`.""" +import json, os, sys +sys.path.insert(0, os.path.dirname(__file__)) +from k5 import * +from k5 import _file +mode = sys.argv[1] if len(sys.argv) > 1 else 'light' +WHO = ['-c', 'user.name=HH', '-c', 'user.email=hh@kaern.invalid'] +F, G = 'restore-check.txt', 'restore-gone.txt' +made = {} + + +def write(path, text): + with open(os.path.join(PL, path), 'w') as f: f.write(text) + + +def read(path): + full = os.path.join(PL, path) + if not os.path.exists(full): return None + with open(full) as f: return f.read() + + +def prepare(): + """Three commits on top: a adds F and G, b changes F, c deletes G. F then has a change of its own.""" + write(F, 'one\n'); write(G, 'gee\n') + git('add', '--', F, G); git(*WHO, 'commit', '-q', '-m', 'Add the restore samples', '--', F, G) + made['a'] = git('rev-parse', '--short=7', 'HEAD') + write(F, 'two\n'); git(*WHO, 'commit', '-q', '-m', 'Change the restore sample', '--', F) + made['b'] = git('rev-parse', '--short=7', 'HEAD') + git('rm', '-q', '--', G); git(*WHO, 'commit', '-q', '-m', 'Remove the second restore sample', '--', G) + made['c'] = git('rev-parse', '--short=7', 'HEAD') + write(F, 'local\n') + + +_menus = [0] + + +def titles(commit, path): + _menus[0] += 1 + os.makedirs(REPLIES, exist_ok=True) + out = os.path.join(REPLIES, 'restore-%d-%d.json' % (os.getpid(), _menus[0])) + k('menuItems', out, 'commitFile', commit, path) + return [i['title'] for i in json.loads(_file(out)) if 'title' in i] + + +def pick(commit): + k('pick', commit) + return settle(lambda d: d['active']['selection'].split()[2:] == [commit], label='commit ' + commit) + + +launch_prepared(mode, prepare=prepare) +show_tab('powerlens') +settle(label='powerlens') +a, b, c = made['a'], made['b'], made['c'] +k('review', 'off') + +# A file with a change of its own, from the commit that added it. +pick(a) +items = titles(a, F) +print('menu:', items) +assert 'Restore Version at ' + a in items, items +k('menuRun', 'commitFile %s %s | Restore Version at %s' % (a, F, a)) +d = settle(lambda d: read(F) == 'one\n', label='%s as %s has it' % (F, a)) +assert git('show', ':' + F) == 'two', 'the index keeps HEAD’s' +assert toast(d) == 'Restored %s from %s · Kaern kept your changes in Stashes' % (F, a), toast(d) +assert git('stash', 'list', '-n', '1', '--format=%s').endswith('Before restoring %s from %s' % (F, a)) +snap('restore-version', mode) +k('undo') +settle(lambda d: read(F) == 'local\n', label='⌘Z: its own change back') +assert 'Before restoring' not in git('stash', 'list', '--format=%s'), 'the kept copy is dropped' +k('redo') +settle(lambda d: read(F) == 'one\n', label='⇧⌘Z: restored again') +k('undo') +settle(lambda d: read(F) == 'local\n', label='⌘Z once more') +print('restore, ⌘Z, ⇧⌘Z, ⌘Z: %r' % read(F)) + +# A file the commit deleted: the version before, from the parent, as a new file. +pick(c) +items = titles(c, G) +assert 'Restore Version at ' + b in items, items +k('menuRun', 'commitFile %s %s | Restore Version at %s' % (c, G, b)) +d = settle(lambda d: read(G) == 'gee\n', label='%s back' % G) +assert toast(d) == 'Restored %s from %s' % (G, b), toast(d) +assert git('status', '--porcelain', '--', G) == '?? ' + G +k('undo') +settle(lambda d: read(G) is None, label='⌘Z: %s gone again' % G) +print('a deleted file: restored from %s, ⌘Z took it back' % b) +quit_app() +print('RESTORE OK') From df52bba2bbb99f823f37fbf1fa57542e23b5e49c Mon Sep 17 00:00:00 2001 From: progresshans Date: Mon, 30 Nov 2026 15:52:37 +0900 Subject: [PATCH 03/15] fix: git and its hooks run with the login shell's PATH, as in Terminal Kaern ran git with the PATH a Mac app gets (/usr/bin:/bin:/usr/sbin:/sbin) and the Homebrew folders. A hook that calls npx, lint-staged, pre-commit or anything from nvm, volta, asdf, mise, pyenv or ~/.local/bin found nothing there, and the commit failed with "command not found" in Kaern only, while Terminal committed fine. LoginPath already asks the login shell for its PATH once a launch, for the agents; git gets it too now: - KaernKit's GitSearchPath, shared by every copy of the runner (GitRunner.searchPath): the app says it's reading the PATH (expect) and hands it over (provide). Each command runs with the login shell's folders first, then Kaern's own; `git log`'s stream too. - A command that can start a hook (commit, merge, rebase, cherry-pick, revert, am, push, pull, checkout, switch, worktree, clone) waits while the PATH is being read, so one in Kaern's first moments doesn't fail where Terminal wouldn't. Others go on at once. A shell that can't be read (6 s) leaves Kaern's PATH, as before. - LoginPath is asked before the repositories open. git-lfs found only on that PATH counts as installed. - The Command Log says "PATH from your login shell" for a command that ran with it. - A test instance goes by Kaern's PATH, or by the one a check gives it (-KaernLoginPath). Checked: KaernKit tests (a pre-commit hook fails on Kaern's PATH, then waits for and finds its tool on the login shell's; an unreadable shell changes nothing; the folders' order) and the new flow check t_loginpath (a hook calling a tool only the given PATH has lets Kaern's commit through), with t_openin, t_firstload, t_activity, t_historyfail and t_isolation; all passed, and the build has no warnings. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + Kaern/App/AppDelegate.swift | 5 +- Kaern/App/AppModel.swift | 1 + Kaern/App/OpenAgents.swift | 20 ++++- Kaern/Views/CommandLog/CommandLogWindow.swift | 3 +- .../Sources/KaernKit/Git/CommitStream.swift | 2 +- .../Sources/KaernKit/Git/GitCommandLog.swift | 6 +- .../KaernKit/Git/GitRepository+Content.swift | 4 +- .../Sources/KaernKit/Git/GitRunner.swift | 23 +++++- .../Sources/KaernKit/Git/GitSearchPath.swift | 81 +++++++++++++++++++ .../Tests/KaernKitTests/RepositoryTests.swift | 51 ++++++++++++ checks/suite.py | 3 +- checks/t_loginpath.py | 42 ++++++++++ 13 files changed, 229 insertions(+), 15 deletions(-) create mode 100644 Packages/KaernKit/Sources/KaernKit/Git/GitSearchPath.swift create mode 100644 checks/t_loginpath.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f6c5889..ca36ee3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,9 @@ 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. - 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. 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..bfad4de 100644 --- a/Kaern/App/AppModel.swift +++ b/Kaern/App/AppModel.swift @@ -91,6 +91,7 @@ final class AppModel { runner = GitRunner(executableURL: resolution.url, extraEnvironment: testEnvironment, removedEnvironment: launchUsesSSHAgent ? [] : ["SSH_AUTH_SOCK"], + searchPath: LoginPath.searchPath, 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/OpenAgents.swift b/Kaern/App/OpenAgents.swift index 5b3df6e..0e0c8a3 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,27 @@ 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`). 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") { + 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() 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/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/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/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/GitRunner.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitRunner.swift index d3f4d9d..f68b3bc 100644 --- a/Packages/KaernKit/Sources/KaernKit/Git/GitRunner.swift +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitRunner.swift @@ -89,6 +89,12 @@ public struct GitRunner: Sendable { /// pointers, and git compares them as they are. `git add` keeps the filters, so staging a /// real file at an LFS path fails rather than putting the file into git itself. public let isLFSInstalled: Bool + /// The login shell's PATH once the app has read it, shared by every copy of this runner (see ``GitSearchPath``). + /// `nil`: git runs with the PATH the runner was made with. + public var searchPath: GitSearchPath? + + /// Whether `git-lfs` is on the PATH git runs with now: Kaern's own, or the login shell's. + public var hasLFS: Bool { isLFSInstalled || searchPath?.providesLFS == true } /// How long a stopped git and what it started get to end by themselves, before they are ended by force. /// Long enough for a busy Mac and for a hook that tidies up; short enough for a command that will never end. var stopGrace: Duration = .seconds(10) @@ -154,10 +160,12 @@ public struct GitRunner: Sendable { executableURL: URL = GitRunner.defaultExecutableURL, extraEnvironment: [String: String] = [:], removedEnvironment: [String] = [], + searchPath: GitSearchPath? = nil, onCommand: (@Sendable (GitCommandEvent) -> Void)? = nil ) { _ = GitRunner.ignoreSIGPIPE self.executableURL = executableURL + self.searchPath = searchPath self.onCommand = onCommand var env = ProcessInfo.processInfo.environment @@ -208,8 +216,16 @@ 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: subcommand.map(GitSearchPath.hookCommands.contains) ?? false) { + environment["PATH"] = GitSearchPath.merged(login, before: environment["PATH"]) + usedLoginPath = true + } 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 +233,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 +261,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..c528a2e --- /dev/null +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitSearchPath.swift @@ -0,0 +1,81 @@ +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"] +} diff --git a/Packages/KaernKit/Tests/KaernKitTests/RepositoryTests.swift b/Packages/KaernKit/Tests/KaernKitTests/RepositoryTests.swift index 3d5e7ca..f1eb831 100644 --- a/Packages/KaernKit/Tests/KaernKitTests/RepositoryTests.swift +++ b/Packages/KaernKit/Tests/KaernKitTests/RepositoryTests.swift @@ -289,3 +289,54 @@ 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") + } + + @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/checks/suite.py b/checks/suite.py index e9de906..ab8669a 100644 --- a/checks/suite.py +++ b/checks/suite.py @@ -94,13 +94,14 @@ def __init__(self, name, areas, dark=False, alone=False, samples=('base',), seco Check('t_firstload', 'launch history changes', seconds=8), Check('t_remotemore', 'sidebar', samples=('base', 'remotes-3000'), seconds=12), Check('t_openin', 'openin menus layout review changes settings', dark=True, seconds=14), + Check('t_loginpath', 'changes launch openin', seconds=8), ] BY_NAME = {c.name: c for c in CHECKS} # Source paths → areas. A path that matches CORE, or a Swift file that matches nothing, runs every check. CORE = r'''(?x) ^Kaern/App/(AppModel|AppDelegate|main|DebugDriver.*)\.swift$ | ^Kaern/Repository/RepositoryModel(\+Actions)?\.swift$ | ^Kaern/Window/(MainWindowController|WindowModel)\.swift$ | ^Kaern/Views/WindowRootView\.swift$ | ^Kaern/Design/ | ^Kaern/Session/ - | KaernKit/Git/(GitRunner|GitRepository|GitRepository\+Indicators)\.swift$ | KaernKit/Parsing/RecordParsing | KaernKit/Watch/ + | KaernKit/Git/(GitRunner|GitSearchPath|GitRepository|GitRepository\+Indicators)\.swift$ | KaernKit/Parsing/RecordParsing | KaernKit/Watch/ | \.xcodeproj/ | Package\.swift$ | \.entitlements$ | Info\.plist$''' NONE = r'(?x) /Tests/ | \.md$ | ^script/ | ^\.gitignore$ | ^\.github/ | ^Kaern/Resources/Licenses/' # A check's own file runs that check; any other file of the checks (a helper, a sample) runs them all. diff --git a/checks/t_loginpath.py b/checks/t_loginpath.py new file mode 100644 index 0000000..7f81abe --- /dev/null +++ b/checks/t_loginpath.py @@ -0,0 +1,42 @@ +"""t_loginpath.py [light|dark] — git and its hooks run with the login shell's PATH, as in Terminal. A pre-commit hook +that calls a tool only that PATH has (here the check's stand-in for it, `-KaernLoginPath`) lets Kaern's commit through, +and the tool ran. Without the login shell's PATH, git ran with the short one a Mac app gets, and the hook failed with +"command not found".""" +import os, sys +sys.path.insert(0, os.path.dirname(__file__)) +from k5 import * +mode = sys.argv[1] if len(sys.argv) > 1 else 'light' +TOOLS = os.path.join(RUN_DIR, 'login-tools') +MARK = os.path.join(RUN_DIR, 'hook-tool-ran') +NEW = 'login-path-check.txt' +SUMMARY = 'Check the login PATH' + + +def prepare(): + """A tool in a folder only the stand-in PATH has, a pre-commit hook that runs it, and a new file to commit.""" + os.makedirs(TOOLS, exist_ok=True) + tool = os.path.join(TOOLS, 'kaern-check-hook-tool') + with open(tool, 'w') as f: f.write('#!/bin/sh\ntouch %s\n' % MARK) + os.chmod(tool, 0o755) + hook = os.path.join(PL, '.git', 'hooks', 'pre-commit') + with open(hook, 'w') as f: f.write('#!/bin/sh\nkaern-check-hook-tool\n') + os.chmod(hook, 0o755) + with open(os.path.join(PL, NEW), 'w') as f: f.write('made for the login PATH check\n') + if os.path.exists(MARK): os.remove(MARK) + + +launch_prepared(mode, prepare=prepare, extra=['-KaernLoginPath', TOOLS + ':/usr/bin:/bin']) +show_tab('powerlens') +settle(label='powerlens') +k('unstageAll') +settle(lambda d: not d['active']['staged'], label='nothing staged') +k('stage', NEW) +settle(lambda d: d['active']['staged'] == [NEW], label='%s staged' % NEW) +k('summary', SUMMARY) +k('commit') +d = settle(lambda d: git('log', '-1', '--format=%s') == SUMMARY, seconds=60, label='the commit, its hook through') +assert os.path.exists(MARK), 'the hook ran the tool' +assert git('show', '--name-only', '--format=', 'HEAD') == NEW +print('the hook found kaern-check-hook-tool on the login PATH; committed', git('rev-parse', '--short', 'HEAD')) +quit_app() +print('LOGIN PATH OK') From f2e6d8bbbf67997c0d692d54637372f8455b4bd9 Mon Sep 17 00:00:00 2001 From: progresshans Date: Mon, 30 Nov 2026 16:08:19 +0900 Subject: [PATCH 04/15] feat: answer what ssh asks: a key's passphrase, a new host, a security key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit git starts ssh without a terminal, and ssh had no one to ask. A key with a passphrase (not in the agent or the Keychain) and a server ssh hadn't seen both failed, and Kaern said the server didn't accept the SSH key. Now ssh asks Kaern (KaernKit's GitAskpass): every command runs with SSH_ASKPASS set to Kaern's own executable and SSH_ASKPASS_REQUIRE=force. Started that way (KAERN_ASKPASS set), Kaern doesn't start the app: it hands the question to the running one over a Unix socket in the temporary folder, with a token, and prints the answer (main.swift, AskpassClient). The app answers on the main actor, one question at a time (AskpassCenter), in a window over its windows (AskpassWindowController), since a question can come from a repository no window shows: - A passphrase: Unlock, with "Remember in my Keychain" (one item per key file). A saved one answers by itself; asked again by the same ssh, it was wrong, so it goes and you're asked, "That passphrase didn't unlock the key". - A new host: its key type and fingerprint, Connect or Cancel; ssh then remembers it. - A security key's PIN, a touch notice (gone when ssh ends it), a yes-or-no, anything else as typed. - A background command (auto-fetch, refreshes) gets no window: a saved passphrase still answers, otherwise the asker leaves a note on ssh's error output and the command fails. - git's own HTTPS questions are turned down, so Sign In works as before (git's "unable to read askpass response" line is left out of the message). core.askPass and GIT_ASKPASS, when set, still come first. - A question whose asker goes away (ssh ended it, Stop) leaves the window. GitFailure tells the new cases apart: a locked key in the background, a host key nobody confirmed, a changed host key (the message says how to check it and copies ssh-keygen -R), and a question you cancelled, which ends the command without an alert and notes no fetch problem. The first three pause auto-fetch, as a rejected key does. Settings › Advanced › SSH says what Kaern does and lists the keys whose passphrase it remembers, with Forget. A test instance keeps passphrases in memory, never in the Keychain, and its window sits beside the screen like the others. Checked: KaernKit tests (the prompts read, the failures told apart, the variables reaching a stand-in ssh with what the user did or nothing in the background, git's own question turned down) and the whole KaernKit suite (214), and the new flow check t_sshprompts in light and dark: a stand-in ssh (core.sshCommand) asks through the real asker; the new host, Connect, a wrong passphrase asked again, the right one remembered, the next fetch without a question, Cancel without an alert, and auto-fetch failing on the locked key without a window and pausing. Also t_activity, t_shallow, t_clone, t_settings, t_isolation, t_pullrebase, t_publishfail and t_remotemore; all passed, no warnings. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + Kaern/App/AppModel.swift | 1 + Kaern/App/DebugDriver+Askpass.swift | 45 ++++ Kaern/App/DebugDriver.swift | 3 + Kaern/App/FailureHelp.swift | 35 +++ Kaern/App/main.swift | 3 + Kaern/Askpass/AskpassCenter.swift | 183 +++++++++++++++ Kaern/Askpass/AskpassServer.swift | 103 ++++++++ Kaern/Askpass/AskpassSocket.swift | 104 +++++++++ Kaern/Askpass/AskpassWindow.swift | 220 ++++++++++++++++++ Kaern/Repository/RepositoryModel+Fetch.swift | 7 +- Kaern/Repository/RepositoryModel.swift | 4 + Kaern/Settings/SettingsWindow.swift | 24 ++ .../Sources/KaernKit/Git/GitAskpass.swift | 94 ++++++++ .../Sources/KaernKit/Git/GitFailure.swift | 27 ++- .../Sources/KaernKit/Git/GitRunner.swift | 13 +- .../Tests/KaernKitTests/AskpassTests.swift | 94 ++++++++ checks/README.md | 5 + checks/suite.py | 2 + checks/t_sshprompts.py | 115 +++++++++ 20 files changed, 1085 insertions(+), 4 deletions(-) create mode 100644 Kaern/App/DebugDriver+Askpass.swift create mode 100644 Kaern/Askpass/AskpassCenter.swift create mode 100644 Kaern/Askpass/AskpassServer.swift create mode 100644 Kaern/Askpass/AskpassSocket.swift create mode 100644 Kaern/Askpass/AskpassWindow.swift create mode 100644 Packages/KaernKit/Sources/KaernKit/Git/GitAskpass.swift create mode 100644 Packages/KaernKit/Tests/KaernKitTests/AskpassTests.swift create mode 100644 checks/t_sshprompts.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f6c5889..72dbfde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ 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. +- 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. ### Improved @@ -39,6 +43,9 @@ 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. +- 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. diff --git a/Kaern/App/AppModel.swift b/Kaern/App/AppModel.swift index 09b0c7d..92b100c 100644 --- a/Kaern/App/AppModel.swift +++ b/Kaern/App/AppModel.swift @@ -91,6 +91,7 @@ final class AppModel { runner = GitRunner(executableURL: resolution.url, extraEnvironment: testEnvironment, removedEnvironment: launchUsesSSHAgent ? [] : ["SSH_AUTH_SOCK"], + 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.swift b/Kaern/App/DebugDriver.swift index 1854aed..98fe796 100644 --- a/Kaern/App/DebugDriver.swift +++ b/Kaern/App/DebugDriver.swift @@ -189,6 +189,8 @@ final class DebugDriver { holds(command, args) case _ where DebugDriver.frameCommands.contains(command): frames(command, args) + case _ where DebugDriver.askpassCommands.contains(command): + askpassCommand(command, args) case "sidebar": window?.showsSidebar = args.first != "off" case "details": @@ -1188,6 +1190,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. 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/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..48aa2ac --- /dev/null +++ b/Kaern/Askpass/AskpassCenter.swift @@ -0,0 +1,183 @@ +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 + /// The ssh each key's passphrase last went to, and when: a second question from it soon after is a retry (a + /// process number comes round again only much later). + @ObservationIgnored private var given: [String: (asker: Int32, at: Date)] = [:] + + 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 { + retry = given[key].map { $0.asker == request.asker && Date().timeIntervalSince($0.at) < 30 } ?? false + // The saved one, unless it was just turned down; then it goes, and you're asked. + if retry { + SSHPassphrases.forget(key) + } else if let saved = SSHPassphrases.saved(for: key) { + given[key] = (request.asker, Date()) + return AskpassReply(ok: true, answer: saved) + } + } + 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, case .passphrase(let key) = kind { given[key] = (request.asker, Date()) } + 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) } + finish(AskpassReply(ok: true, answer: text)) + 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/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.swift b/Kaern/Repository/RepositoryModel.swift index b9082cd..9927713 100644 --- a/Kaern/Repository/RepositoryModel.swift +++ b/Kaern/Repository/RepositoryModel.swift @@ -1520,6 +1520,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/SettingsWindow.swift b/Kaern/Settings/SettingsWindow.swift index 6ceb8b0..110969a 100644 --- a/Kaern/Settings/SettingsWindow.swift +++ b/Kaern/Settings/SettingsWindow.swift @@ -1151,6 +1151,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 +1242,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/Packages/KaernKit/Sources/KaernKit/Git/GitAskpass.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitAskpass.swift new file mode 100644 index 0000000..cafd6da --- /dev/null +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitAskpass.swift @@ -0,0 +1,94 @@ +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) ?? "", + ] + } +} + +/// 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/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/GitRunner.swift b/Packages/KaernKit/Sources/KaernKit/Git/GitRunner.swift index d3f4d9d..2006951 100644 --- a/Packages/KaernKit/Sources/KaernKit/Git/GitRunner.swift +++ b/Packages/KaernKit/Sources/KaernKit/Git/GitRunner.swift @@ -58,6 +58,8 @@ public struct GitError: Error, LocalizedError, Sendable, Equatable { && !line.hasPrefix("remote: Compressing") && !line.hasPrefix("remote: Enumerating") && !line.hasPrefix("remote: Total") + // git asked Kaern's asker for HTTPS credentials and it said no (Kaern signs in its own way). + && !line.hasPrefix("unable to read askpass response from ") } return settingAdviceApart(lines).joined(separator: "\n") } @@ -89,6 +91,9 @@ public struct GitRunner: Sendable { /// pointers, and git compares them as they are. `git add` keeps the filters, so staging a /// real file at an LFS path fails rather than putting the file into git itself. public let isLFSInstalled: Bool + /// Who answers what ssh asks (a key's passphrase, a new host): Kaern, through ``GitAskpass``. `nil`: nobody, and + /// ssh fails where it would ask. + public var askpass: GitAskpass? /// How long a stopped git and what it started get to end by themselves, before they are ended by force. /// Long enough for a busy Mac and for a hook that tidies up; short enough for a command that will never end. var stopGrace: Duration = .seconds(10) @@ -154,10 +159,12 @@ public struct GitRunner: Sendable { executableURL: URL = GitRunner.defaultExecutableURL, extraEnvironment: [String: String] = [:], removedEnvironment: [String] = [], + askpass: GitAskpass? = nil, onCommand: (@Sendable (GitCommandEvent) -> Void)? = nil ) { _ = GitRunner.ignoreSIGPIPE self.executableURL = executableURL + self.askpass = askpass self.onCommand = onCommand var env = ProcessInfo.processInfo.environment @@ -208,6 +215,10 @@ 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 } + 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 onCommand = onCommand @@ -244,7 +255,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/Tests/KaernKitTests/AskpassTests.swift b/Packages/KaernKit/Tests/KaernKitTests/AskpassTests.swift new file mode 100644 index 0000000..b1b065c --- /dev/null +++ b/Packages/KaernKit/Tests/KaernKitTests/AskpassTests.swift @@ -0,0 +1,94 @@ +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 { + @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/checks/README.md b/checks/README.md index c47fb42..a7f7431 100644 --- a/checks/README.md +++ b/checks/README.md @@ -55,6 +55,11 @@ opened in the dump's `driver.opened` (`OpenIn`; a command for the terminal as `t passes whatever is installed, and adds agents of its own through `KaernOpenCustom`. A test instance looks for the agents' commands only in the usual places (`LoginPath`), without asking a login shell. +What ssh asks (a key's passphrase, a new host) comes to Kaern's own window through `SSH_ASKPASS` (`GitAskpass`, +`Kaern/Askpass/`). `t_sshprompts` reaches a sample remote through a stand-in ssh (`core.sshCommand`) that asks the +way ssh does, and answers with `askpassAnswer`, `askpassCancel` and `askpassRemember`; the dump's `askpass` says what +the window shows. A test instance keeps a remembered passphrase in memory, never in the Keychain. + ## Where things are `python3 checks/paths.py` prints the work folder and the app. The work folder is in the temporary folder, one per diff --git a/checks/suite.py b/checks/suite.py index e9de906..6923804 100644 --- a/checks/suite.py +++ b/checks/suite.py @@ -94,6 +94,7 @@ def __init__(self, name, areas, dark=False, alone=False, samples=('base',), seco Check('t_firstload', 'launch history changes', seconds=8), Check('t_remotemore', 'sidebar', samples=('base', 'remotes-3000'), seconds=12), Check('t_openin', 'openin menus layout review changes settings', dark=True, seconds=14), + Check('t_sshprompts', 'ssh fetch activity', dark=True, seconds=12), ] BY_NAME = {c.name: c for c in CHECKS} @@ -138,6 +139,7 @@ def __init__(self, name, areas, dark=False, alone=False, samples=('base',), seco (r'Views/Menus/|App/MainMenu', 'menus'), (r'App/OpenIn|App/OpenAgents|Settings/OpenInPane|Menus/OpenMenus|Review/FileOpenButton|Common/DebugFrame', 'openin'), (r'Views/StatusBar/', 'statusbar'), + (r'Kaern/Askpass/|Git/GitAskpass', 'ssh fetch'), (r'Views/CommandLog/|App/CommandLog|Git/GitCommandLog', 'commandlog'), ] diff --git a/checks/t_sshprompts.py b/checks/t_sshprompts.py new file mode 100644 index 0000000..db7d434 --- /dev/null +++ b/checks/t_sshprompts.py @@ -0,0 +1,115 @@ +"""t_sshprompts.py [light|dark] — what ssh asks, Kaern asks you (GitAskpass). A stand-in ssh (core.sshCommand) asks +through SSH_ASKPASS as ssh does: first about a host it hasn't seen, then for its key's passphrase. Fetch shows each +question in Kaern's window: Connect, a wrong passphrase asked again, the right one remembered (in memory: a test +instance never touches the Keychain). The next Fetch asks nothing. Cancel ends a fetch without an alert. Auto-fetch +never shows the window: a locked key fails it, says so, and pauses it.""" +import os, sys +sys.path.insert(0, os.path.dirname(__file__)) +from k5 import * +mode = sys.argv[1] if len(sys.argv) > 1 else 'light' +STATE = os.path.join(RUN_DIR, 'fake-ssh') +KEY = os.path.join(STATE, 'id_check') +SECRET = 'check passphrase' +REMOTE = 'sshcheck' +SCRIPT = r'''#!/bin/sh +# A stand-in for ssh (ssh.variant simple: `fake-ssh host command`): asks what ssh asks, through the asker in +# SSH_ASKPASS, then runs git's command here. +STATE='@STATE@' +echo run >> "$STATE/runs" +host=$1 +for last; do :; done +if [ ! -f "$STATE/known" ]; then + answer=$("$SSH_ASKPASS" "The authenticity of host '$host (192.0.2.7)' can't be established. +ED25519 key fingerprint is SHA256:KaernCheckKaernCheckKaernCheckKaernCheck00. +This key is not known by any other names. +Are you sure you want to continue connecting (yes/no/[fingerprint])? ") + if [ "$answer" != yes ]; then echo "Host key verification failed." >&2; exit 255; fi + touch "$STATE/known" +fi +i=0 +while [ $i -lt 3 ]; do + answer=$("$SSH_ASKPASS" "Enter passphrase for key '$STATE/id_check': ") || break + if [ "$answer" = "$(cat "$STATE/passphrase")" ]; then + exec sh -c "$(printf '%s' "$last" | sed 's/^git-/git /')" + fi + i=$((i+1)) +done +echo "git@$host: Permission denied (publickey)." >&2 +exit 255 +''' + + +def prepare(): + """The stand-in ssh, its passphrase, and a remote reached through it (the sample's own bare remote).""" + os.makedirs(STATE, exist_ok=True) + for name in ('known', 'runs'): + if os.path.exists(os.path.join(STATE, name)): os.remove(os.path.join(STATE, name)) + with open(os.path.join(STATE, 'passphrase'), 'w') as f: f.write(SECRET) + ssh = os.path.join(STATE, 'fake-ssh') + with open(ssh, 'w') as f: f.write(SCRIPT.replace('@STATE@', STATE)) + os.chmod(ssh, 0o755) + git('remote', 'add', REMOTE, 'kaern-check.invalid:' + os.path.join(SAMPLES, 'remotes', 'powerlens.git')) + git('config', 'core.sshCommand', ssh) + git('config', 'ssh.variant', 'simple') + + +def ask(d): return d['askpass'] +def runs(): + path = os.path.join(STATE, 'runs') + return len(open(path).read().split()) if os.path.exists(path) else 0 +def fetched(): return git('rev-parse', '--verify', '-q', 'refs/remotes/%s/develop' % REMOTE) != '' + + +launch_prepared(mode, prepare=prepare) +show_tab('powerlens') +settle(label='powerlens') +assert not fetched() + +# Fetch: a host ssh hasn't seen. The window says which and shows its key; Connect. +k('fetch') +d = until(lambda d: ask(d).get('kind') == 'newHost' and ask(d)['window'], label='the new host question') +print('asked:', ask(d)['question'], '·', ask(d)['action']) +assert ask(d)['action'] == 'Fetch' and 'kaern-check.invalid' in ask(d)['question'], ask(d) +snap('ssh-newhost', window='SSH') +k('askpassAnswer') + +# Its key's passphrase: a wrong one is asked again, the right one remembered. +d = until(lambda d: ask(d).get('kind') == 'passphrase' and not ask(d)['retry'], label='the passphrase question') +snap('ssh-passphrase', window='SSH') +k('askpassAnswer', 'not it') +until(lambda d: ask(d).get('kind') == 'passphrase' and ask(d)['retry'], label='asked again after a wrong one') +snap('ssh-passphrase-again', window='SSH') +k('askpassRemember', 'on') +k('askpassAnswer', SECRET) +d = settle(lambda d: fetched() and ask(d)['waiting'] == 0 and not ask(d)['window'], seconds=60, label='fetched through ssh') +assert ask(d)['saved'] == [KEY], ask(d)['saved'] +assert d['active']['alert'] == '', d['active']['alert'] +shown = ask(d)['shown'] +print('connected, unlocked, remembered:', ask(d)['saved']) + +# Fetch again: the saved passphrase answers; no window. +before = runs() +k('fetch') +d = settle(lambda d: runs() > before and d['active']['activity'] == '', seconds=60, label='the second fetch') +assert ask(d)['shown'] == shown and d['active']['alert'] == '', (ask(d), d['active']['alert']) +print('fetched again without a question') + +# Cancel: the fetch ends, with no alert and no problem noted. +k('askpassForget') +k('fetch') +until(lambda d: ask(d).get('kind') == 'passphrase', label='asked once more') +k('askpassCancel') +d = settle(lambda d: ask(d)['waiting'] == 0 and d['active']['activity'] == '', label='the fetch ended') +assert d['active']['alert'] == '' and d['active']['phase4']['fetchProblem'] == '', (d['active']['alert'], d['active']['phase4']['fetchProblem']) +print('cancelled: no alert') + +# Auto-fetch: no window; the locked key fails it, and auto-fetch pauses. +shown = ask(d)['shown'] +k('autoFetchNow') +d = settle(lambda d: d['active']['phase4']['fetchProblem'] != '', seconds=60, label='auto-fetch failing') +assert ask(d)['shown'] == shown, 'auto-fetch showed the window' +assert d['active']['phase4']['fetchProblem'].startswith('sshKeyLocked'), d['active']['phase4']['fetchProblem'] +assert d['active']['phase4']['autoFetchPaused'], 'auto-fetch paused' +print('auto-fetch:', d['active']['phase4']['fetchProblem']) +quit_app() +print('SSH PROMPTS OK') From 36072ba6ca3df3e654130dbad735b28962afb209 Mon Sep 17 00:00:00 2001 From: progresshans Date: Mon, 30 Nov 2026 16:22:32 +0900 Subject: [PATCH 05/15] feat: color the code in diffs by its language MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Diffs showed code in one color. Review, Focus's drawer, file history and stashes now color keywords, strings, comments, numbers, types, functions, attributes and directives, with the colors of Xcode's default light and dark themes (K.syn…), on top of the line and changed-word backgrounds. Settings › Diff › "Color the code: keywords, strings, comments" turns it off (KaernDiffSyntax, on by default). KaernKit's SyntaxHighlighter reads a line at a time, so it needs nothing but the lines a diff has: each language is a table (keywords, types, constants, comments, quotes) plus a few rules a line can follow: attributes and decorators, preprocessor lines and directives, $variables, YAML/TOML/INI keys and sections, JSON keys, CSS properties and colors, Rust lifetimes and macros, a markup reader for HTML/XML (tags, attributes, entities, comments) and one for Markdown (headings, lists, quotes, code). A comment or string that goes on carries to the next line; the old side (unchanged and deleted lines) and the new side (unchanged and added lines) of a hunk are each read in order, and unchanged lines take the new side's colors. A quote right after a letter starts no string in YAML and shell scripts (Kaern's, don't). Lines over 1,500 characters (minified code) aren't colored. The language comes from the file's name or extension; other files stay as they were. No dependency: about 30 languages in one file, 20,600 lines of Swift in 0.09 s (release build). DiffRowItem carries each line's colors next to its changed words, built once per file in Review's row cache; the dump's phase5 `syntax` lists the colored pieces of the file Review shows. Checked: KaernKit tests (the language by name; Swift, Python, JavaScript, C, YAML, shell, JSON, HTML, Markdown, Rust, Lua and SQL lines; carried comments and strings; long lines) and the new flow check t_syntax in light and dark (a Swift file in Split and Unified, a workflow's YAML keys, the setting off and on), with the review, explore, stash and settings checks. Not a full parser: a hunk that starts inside a comment or a string colors its first lines as code. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + Kaern/App/DebugDriver+Phase5.swift | 13 + Kaern/Design/Tokens.swift | 9 + Kaern/Settings/AppSettings.swift | 2 + Kaern/Settings/SettingsWindow.swift | 2 + Kaern/Views/Explore/ExploreViews.swift | 3 +- Kaern/Views/Review/DiffViews.swift | 100 +- Kaern/Views/Review/FocusDrawer.swift | 3 +- Kaern/Views/Review/ReviewView.swift | 18 +- Kaern/Views/Stash/StashViews.swift | 3 +- .../Sources/KaernKit/Models/Syntax.swift | 948 ++++++++++++++++++ .../Tests/KaernKitTests/SyntaxTests.swift | 115 +++ checks/suite.py | 3 +- checks/t_syntax.py | 50 + 14 files changed, 1236 insertions(+), 37 deletions(-) create mode 100644 Packages/KaernKit/Sources/KaernKit/Models/Syntax.swift create mode 100644 Packages/KaernKit/Tests/KaernKitTests/SyntaxTests.swift create mode 100644 checks/t_syntax.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f6c5889..57189e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ 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. +- 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 diff --git a/Kaern/App/DebugDriver+Phase5.swift b/Kaern/App/DebugDriver+Phase5.swift index a168f34..c195de8 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 spans) = row else { return nil } + let characters = Array(line.text) + return (spans ?? []).map { "\($0.kind):" + String(characters[$0.range.clamped(to: 0..] /// 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: [SyntaxSpan]?) + case split(String, left: DiffLine?, right: DiffLine?, hunk: ReviewHunk, leftMarks: WordMarks?, rightMarks: WordMarks?, + leftSyntax: [SyntaxSpan]?, rightSyntax: [SyntaxSpan]?) 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. + 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 { Self.colors(of: hunk, 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[line.id])) budget -= 1 consumed += 1 } @@ -234,7 +237,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] }, + leftSyntax: left.flatMap { code[$0.id] }, rightSyntax: right.flatMap { code[$0.id] })) index += 1 budget -= 1 consumed += (left == nil ? 0 : 1) + (right == nil ? 0 : 1) @@ -249,7 +253,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, + leftSyntax: code[line.id], rightSyntax: code[line.id])) index += 1 budget -= 1 consumed += 1 @@ -265,6 +270,39 @@ enum DiffRowItem: Identifiable { if hidden > 0 { rows.append(.more(file.path + ":more", hidden: hidden)) } return rows } + + /// The colored code of a hunk's lines, by line: the old side (unchanged and deleted lines) and the new side + /// (unchanged and added lines) 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. + static func colors(of hunk: ReviewHunk, in language: SyntaxLanguage) -> [Int: [SyntaxSpan]] { + let lines = hunk.hunk.lines + let old = lines.filter { $0.kind == .context || $0.kind == .deletion } + let new = lines.filter { $0.kind == .context || $0.kind == .addition } + var result: [Int: [SyntaxSpan]] = [:] + for (line, spans) in zip(old, SyntaxHighlighter.highlight(old.map(\.text), in: language)) where line.kind == .deletion { + result[line.id] = spans + } + for (line, spans) in zip(new, SyntaxHighlighter.highlight(new.map(\.text), in: language)) { + result[line.id] = spans + } + return result + } +} + +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 @@ -299,10 +337,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) + case .split(_, let left, let right, let hunk, let leftMarks, let rightMarks, let leftSyntax, let rightSyntax): + SplitLineRow(left: left, right: right, hunk: hunk, picking: picking, leftMarks: leftMarks, rightMarks: rightMarks, + leftSyntax: leftSyntax, rightSyntax: rightSyntax) case .note(_, let text): Text(text) .font(.system(size: z(12))) @@ -402,6 +441,7 @@ private struct UnifiedLineRow: View { let hunk: ReviewHunk let picking: LinePicking? var marks: WordMarks? + var syntax: [SyntaxSpan]? @Environment(\.diffStyle) private var style var body: some View { @@ -418,7 +458,7 @@ private struct UnifiedLineRow: View { .foregroundStyle(line.kind == .addition ? K.add : K.del) .frame(width: z(18)) 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) + marks: marks, syntax: line.kind == .noNewline ? nil : syntax, color: line.kind == .noNewline ? K.label2 : K.code) .padding(.trailing, z(16)) } .font(style.font) @@ -430,12 +470,13 @@ private struct UnifiedLineRow: View { } } -/// 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 @@ -465,18 +506,25 @@ struct DiffLineText: View { 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 { + private func side(_ line: DiffLine?, number: Int?, changed: Bool, marks: WordMarks?, syntax: [SyntaxSpan]?) -> some View { if let line { let colors = DiffColors(kind: changed ? line.kind : .context) let pick = changed ? picking?.pick(for: line, in: hunk) : nil @@ -527,7 +577,7 @@ private struct SplitLineRow: View { if picking != nil { StagedMark(shows: changed && hunk.stage == .staged) } - DiffLineText(text: line.text, kind: changed ? line.kind : .context, marks: changed ? marks : nil) + DiffLineText(text: line.text, kind: changed ? line.kind : .context, marks: changed ? marks : nil, syntax: syntax) .padding(.leading, picking == nil ? z(8) : z(2)) .padding(.trailing, z(12)) } diff --git a/Kaern/Views/Review/FocusDrawer.swift b/Kaern/Views/Review/FocusDrawer.swift index ae98124..864dbca 100644 --- a/Kaern/Views/Review/FocusDrawer.swift +++ b/Kaern/Views/Review/FocusDrawer.swift @@ -11,6 +11,7 @@ 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 file list has keyboard focus: ↑ ↓ show the file above or below. @FocusState private var filesFocused: Bool @@ -46,7 +47,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(DiffRowItem.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..1ea9b83 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) { @@ -475,19 +476,20 @@ struct LinePickBar: View { } /// 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. +/// the diff of a file is cut into rows (its edited lines compared word by word, its code colored) 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])] = [:] + private var entries: [String: (file: ReviewFile, layout: DiffLayout, limit: Int, words: Bool, syntax: 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 { + 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) + let rows = DiffRowItem.rows(for: file, layout: layout, limit: limit, words: words, syntax: syntax) if entries.count >= 400 { entries.removeAll() } - entries[file.path] = (file, layout, limit, words, rows) + entries[file.path] = (file, layout, limit, words, syntax, rows) return rows } } diff --git a/Kaern/Views/Stash/StashViews.swift b/Kaern/Views/Stash/StashViews.swift index 2156183..1ec9ba3 100644 --- a/Kaern/Views/Stash/StashViews.swift +++ b/Kaern/Views/Stash/StashViews.swift @@ -8,6 +8,7 @@ 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] = [:] var body: some View { @@ -20,7 +21,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 = DiffRowItem.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/Models/Syntax.swift b/Packages/KaernKit/Sources/KaernKit/Models/Syntax.swift new file mode 100644 index 0000000..6218450 --- /dev/null +++ b/Packages/KaernKit/Sources/KaernKit/Models/Syntax.swift @@ -0,0 +1,948 @@ +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 { line in + guard line.count <= longestLine else { + state = .normal + return [] + } + return highlight(line: line, language, &state) + } + } + + static func highlight(line text: String, _ language: SyntaxLanguage, _ state: inout State) -> [SyntaxSpan] { + 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 + } +} + +/// One line, read once from the start. +private struct Reader { + let text: [Character] + let language: SyntaxLanguage + var spans: [SyntaxSpan] = [] + var index = 0 + + init(text: [Character], language: SyntaxLanguage) { + self.text = text + self.language = language + } + + var count: Int { text.count } + + mutating func add(_ start: Int, _ end: Int, _ kind: SyntaxKind) { + guard end > 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/SyntaxTests.swift b/Packages/KaernKit/Tests/KaernKitTests/SyntaxTests.swift new file mode 100644 index 0000000..91d3864 --- /dev/null +++ b/Packages/KaernKit/Tests/KaernKitTests/SyntaxTests.swift @@ -0,0 +1,115 @@ +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(["