adds claude-generated commit messages and a recent commits panel to the git view - adds log tailing in the explorer, branch merging and a clean up button
This commit is contained in:
@@ -5,6 +5,8 @@ public enum TerminalKind: String, Sendable, Equatable, CaseIterable {
|
||||
case agent
|
||||
/// The bottom pane: a plain login shell.
|
||||
case shell
|
||||
/// The Explorer's log block: `tail -f` on one file.
|
||||
case tail
|
||||
}
|
||||
|
||||
/// Executable, arguments and environment for one terminal pane.
|
||||
@@ -21,7 +23,7 @@ public struct TerminalLaunch: Sendable, Equatable {
|
||||
self.workingDirectory = workingDirectory
|
||||
}
|
||||
|
||||
/// The launch for a pane. The agent runs as `$SHELL -i -c <command>`: `-i` still sources the rc
|
||||
/// The launch for the agent or shell pane. The agent runs as `$SHELL -i -c <command>`: `-i` still sources the rc
|
||||
/// files (nvm etc.) but leaves no prompt line or echoed command behind.
|
||||
public static func make(kind: TerminalKind, config: HelderConfig, projectRoot: String?, environment base: [String: String]) -> TerminalLaunch {
|
||||
let shell = config.terminal.shell ?? base["SHELL"] ?? "/bin/zsh"
|
||||
@@ -30,6 +32,12 @@ public struct TerminalLaunch: Sendable, Equatable {
|
||||
return TerminalLaunch(executable: shell, arguments: args, environment: environment(from: base), workingDirectory: cwd)
|
||||
}
|
||||
|
||||
/// `tail -f` on a project-relative path, run directly without a shell.
|
||||
public static func tail(path: String, projectRoot: String?, environment base: [String: String]) -> TerminalLaunch {
|
||||
TerminalLaunch(executable: "/usr/bin/tail", arguments: ["-f", path], environment: environment(from: base),
|
||||
workingDirectory: projectRoot ?? base["HOME"] ?? "/")
|
||||
}
|
||||
|
||||
/// The child environment. A GUI launch inherits no locale and no COLORTERM, which turns
|
||||
/// multibyte output into mojibake and shifts the CLI's 24-bit colours; npm's prefix
|
||||
/// variables make nvm refuse to load. `TERM_PROGRAM` tells the agent it runs in Helder.
|
||||
|
||||
@@ -9,8 +9,8 @@ public enum ContextTarget: Sendable, Equatable {
|
||||
case directory(path: String)
|
||||
/// A file row in the Git view; a deleted file has nothing to open.
|
||||
case gitRow(path: String, isDeleted: Bool)
|
||||
/// The caret beside the Git view's Commit button.
|
||||
case commitMenu
|
||||
/// A row in the Git view's Branches panel; `current` is the checked-out branch.
|
||||
case branch(name: String, remote: Bool, current: String, isDirty: Bool)
|
||||
/// The empty space under the tree: the project folder itself.
|
||||
case projectRoot
|
||||
case terminal(TerminalKind, hasSelection: Bool)
|
||||
@@ -19,7 +19,7 @@ public enum ContextTarget: Sendable, Equatable {
|
||||
switch self {
|
||||
case let .editor(reference, _, _): reference.path
|
||||
case let .file(path), let .directory(path), let .gitRow(path, _): path
|
||||
case .projectRoot, .terminal, .commitMenu: ""
|
||||
case .projectRoot, .terminal, .branch: ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,8 @@ public enum ContextAction: Sendable, Equatable {
|
||||
case openFile(String)
|
||||
/// Reverts unstaged changes: modified and deleted files come back from the index, new files are removed.
|
||||
case gitDiscard([String])
|
||||
case commit(andPush: Bool)
|
||||
/// The Git view's Clean up: every unstaged change reverted to the index, every untracked file and folder removed.
|
||||
case gitCleanUp
|
||||
/// Opens the Diff of the open file at this line.
|
||||
case showDiff(String, line: Int)
|
||||
case rename(String, isDirectory: Bool)
|
||||
@@ -52,16 +53,20 @@ public enum ContextAction: Sendable, Equatable {
|
||||
case bouwen(String)
|
||||
/// Reads a Markdown file's prose aloud.
|
||||
case readAloudFile(String)
|
||||
/// Runs `tail -f` on a `.log` file in the Explorer's tail block, replacing any running tail.
|
||||
case tailLog(String)
|
||||
case readAloudText(String)
|
||||
/// Sends the editor selection to Plak as it is, code and all.
|
||||
case plak(String)
|
||||
/// Sends the pane's selection to Plak; the text is fetched when the item runs.
|
||||
case plakTerminalSelection(TerminalKind)
|
||||
/// Merges this branch into the current one.
|
||||
case mergeBranch(String)
|
||||
|
||||
/// Destructive items read in amber-deep.
|
||||
public var isDestructive: Bool {
|
||||
switch self {
|
||||
case .gitDiscard, .delete: true
|
||||
case .gitDiscard, .gitCleanUp, .delete: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
@@ -69,7 +74,7 @@ public enum ContextAction: Sendable, Equatable {
|
||||
/// The menu's main item, set in bold.
|
||||
public var isEmphasized: Bool {
|
||||
switch self {
|
||||
case .openFile, .commit(andPush: true): true
|
||||
case .openFile: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
@@ -78,7 +83,15 @@ public enum ContextAction: Sendable, Equatable {
|
||||
/// A menu entry, or a separator between groups.
|
||||
public enum ContextMenuEntry: Sendable, Equatable {
|
||||
case action(ContextAction, label: String)
|
||||
/// Shown dimmed with its `hint` as tooltip; the keyboard skips it and a click does nothing.
|
||||
case disabled(ContextAction, label: String, hint: String)
|
||||
case separator
|
||||
|
||||
/// The keyboard can land on it.
|
||||
public var isSelectable: Bool {
|
||||
if case .action = self { return true }
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
public enum ContextActions {
|
||||
@@ -86,8 +99,9 @@ public enum ContextActions {
|
||||
public static func header(for target: ContextTarget, projectName: String) -> String {
|
||||
switch target {
|
||||
case let .file(path), let .gitRow(path, _): path
|
||||
case let .branch(name, _, _, _): name
|
||||
case .projectRoot: projectName + "/"
|
||||
case .editor, .directory, .terminal, .commitMenu: ""
|
||||
case .editor, .directory, .terminal: ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +124,7 @@ public enum ContextActions {
|
||||
.action(.revealInFinder(""), label: "Show in Finder"),
|
||||
]
|
||||
case let .file(path):
|
||||
return fileHead(path) + readAloudFile(path) + [
|
||||
return fileHead(path) + readAloudFile(path) + tailLog(path) + [
|
||||
.separator,
|
||||
.action(.rename(path, isDirectory: false), label: "Rename file"),
|
||||
.action(.revealInFinder(path), label: "Show in Finder"),
|
||||
@@ -136,19 +150,20 @@ public enum ContextActions {
|
||||
.separator, .action(.plakTerminalSelection(kind), label: "Plak")] : []
|
||||
let waitWhat: [ContextMenuEntry] = hasSelection && kind == .agent
|
||||
? [.separator, .action(.waitWhat(kind), label: "Wait what?")] : []
|
||||
return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : [])
|
||||
+ [.action(.pasteIntoTerminal(kind), label: "Paste")] + readAloud + waitWhat
|
||||
let paste: [ContextMenuEntry] = kind == .tail ? [] : [.action(.pasteIntoTerminal(kind), label: "Paste")]
|
||||
return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : []) + paste + readAloud + waitWhat
|
||||
case let .gitRow(path, isDeleted):
|
||||
let open: [ContextMenuEntry] = isDeleted ? [] : [.action(.openFile(path), label: "Open in editor"), .separator]
|
||||
return open + [
|
||||
.action(.passOnReference(path, code: nil), label: "Pass on reference"),
|
||||
.action(.copyReference(path), label: "Copy reference"),
|
||||
]
|
||||
case .commitMenu:
|
||||
return [
|
||||
.action(.commit(andPush: false), label: "Commit"),
|
||||
.action(.commit(andPush: true), label: "Commit and push"),
|
||||
]
|
||||
case let .branch(name, remote, current, isDirty):
|
||||
if !remote && name == current { return [] }
|
||||
let label = "Merge into \(current)"
|
||||
return [isDirty
|
||||
? .disabled(.mergeBranch(name), label: label, hint: "Commit or discard your changes first")
|
||||
: .action(.mergeBranch(name), label: label)]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,6 +178,10 @@ public enum ContextActions {
|
||||
FileType.isMarkdown(path) ? [.separator, .action(.readAloudFile(path), label: "Read aloud")] : []
|
||||
}
|
||||
|
||||
private static func tailLog(_ path: String) -> [ContextMenuEntry] {
|
||||
(path as NSString).pathExtension.lowercased() == "log" ? [.separator, .action(.tailLog(path), label: "Tail log")] : []
|
||||
}
|
||||
|
||||
/// Selected Markdown is read as prose; a selection with no prose left, such as one code block, is read as it is.
|
||||
private static func readAloudSelection(_ code: String, path: String) -> [ContextMenuEntry] {
|
||||
let prose = FileType.isMarkdown(path) ? MarkdownSpeech.plainText(MarkdownParser.parse(code)) : ""
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import Foundation
|
||||
|
||||
/// The staged changes as `git diff --cached` prints them: the `--stat` summary and the full patch.
|
||||
public struct StagedDiff: Sendable, Equatable {
|
||||
public var stat: String
|
||||
public var patch: String
|
||||
|
||||
public init(stat: String, patch: String) {
|
||||
self.stat = stat
|
||||
self.patch = patch
|
||||
}
|
||||
|
||||
public var isEmpty: Bool {
|
||||
patch.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
}
|
||||
}
|
||||
|
||||
/// The prompt that asks the Claude CLI for one commit message, and the cleaning of its answer.
|
||||
public enum CommitMessagePrompt {
|
||||
public static let maxPatchCharacters = 60_000
|
||||
|
||||
public static let examples = [
|
||||
"Adds a new button on the header to navigate to profile",
|
||||
"Fixed security issue that made it possible to hack a file upload",
|
||||
"Makes sure the register form does not accept R&B fans - Enforces password rules on login form",
|
||||
]
|
||||
|
||||
/// The full prompt; a patch over `limit` characters is cut and the prompt says so, the stat always stays whole.
|
||||
public static func make(_ diff: StagedDiff, limit: Int = maxPatchCharacters) -> String {
|
||||
let isCut = diff.patch.count > limit
|
||||
let patch = isCut ? String(diff.patch.prefix(limit)) : diff.patch
|
||||
var lines = [
|
||||
"Write ONE git commit message for the staged changes below.",
|
||||
"",
|
||||
"Rules:",
|
||||
"- One single sentence on one line. No body, no quotes, no prefix such as \"feat:\". A trailing period is not needed.",
|
||||
"- English. Start with a verb in the third person or in the past tense.",
|
||||
"- When two separate things changed, join them with \" - \" in that one line.",
|
||||
"- Reply with the message only, nothing else.",
|
||||
"",
|
||||
"Examples:",
|
||||
"- \(examples[0])",
|
||||
"- \(examples[1])",
|
||||
"- \(examples[2]) (two things changed)",
|
||||
"",
|
||||
"Changed files (git diff --cached --stat):",
|
||||
diff.stat.trimmingCharacters(in: .newlines),
|
||||
"",
|
||||
"Diff (git diff --cached):",
|
||||
]
|
||||
if isCut {
|
||||
lines.append("(The diff is cut after \(limit) characters; the file list above is complete.)")
|
||||
}
|
||||
lines.append(patch.trimmingCharacters(in: .newlines))
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
|
||||
/// The first non-empty line, Markdown fence lines skipped, without surrounding quotes or backticks and with single spaces;
|
||||
/// nil when nothing is left.
|
||||
public static func clean(_ output: String) -> String? {
|
||||
let wrappers: Set<Character> = ["\"", "'", "`", "“", "”", "‘", "’"]
|
||||
guard var line = output.split(whereSeparator: \.isNewline)
|
||||
.map({ $0.trimmingCharacters(in: .whitespaces) })
|
||||
.first(where: { !$0.isEmpty && !$0.hasPrefix("```") }) else { return nil }
|
||||
while let first = line.first, let last = line.last, line.count >= 2, wrappers.contains(first), wrappers.contains(last) {
|
||||
line = String(line.dropFirst().dropLast()).trimmingCharacters(in: .whitespaces)
|
||||
}
|
||||
line = line.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
|
||||
return line.isEmpty ? nil : line
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import Foundation
|
||||
|
||||
/// One commit of HEAD's recent history, as the Git view's commit list shows it.
|
||||
public struct GitCommitSummary: Sendable, Equatable {
|
||||
public var hash: String
|
||||
public var subject: String
|
||||
public var author: String
|
||||
public var date: Date
|
||||
|
||||
public init(hash: String, subject: String, author: String, date: Date) {
|
||||
self.hash = hash
|
||||
self.subject = subject
|
||||
self.author = author
|
||||
self.date = date
|
||||
}
|
||||
}
|
||||
|
||||
public enum GitCommitLogParsing {
|
||||
public static let limit = 30
|
||||
/// NUL between fields and a record separator after each commit, so no subject can split a record.
|
||||
public static let arguments = ["log", "-n", "\(limit)", "--no-color", "--format=%h%x00%s%x00%an%x00%ct%x1e"]
|
||||
|
||||
/// Reads the records `arguments` prints, newest first; a malformed record is skipped.
|
||||
public static func commits(_ raw: String) -> [GitCommitSummary] {
|
||||
raw.split(separator: "\u{1e}").compactMap { record in
|
||||
let text = record.trimmingCharacters(in: .newlines)
|
||||
let fields = text.split(separator: "\0", omittingEmptySubsequences: false)
|
||||
guard fields.count == 4, !fields[0].isEmpty, let seconds = TimeInterval(fields[3]) else { return nil }
|
||||
return GitCommitSummary(hash: String(fields[0]), subject: String(fields[1]), author: String(fields[2]),
|
||||
date: Date(timeIntervalSince1970: seconds))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum RelativeTime {
|
||||
/// "just now", "5 min ago", "3 h ago", "2 d ago", "3 w ago", "4 mo ago", "2 y ago"; a future date reads "just now".
|
||||
public static func text(_ date: Date, now: Date) -> String {
|
||||
let seconds = Int(now.timeIntervalSince(date))
|
||||
let minute = 60, hour = 3_600, day = 86_400
|
||||
switch seconds {
|
||||
case ..<minute: return "just now"
|
||||
case ..<hour: return "\(seconds / minute) min ago"
|
||||
case ..<day: return "\(seconds / hour) h ago"
|
||||
case ..<(7 * day): return "\(seconds / day) d ago"
|
||||
case ..<(30 * day): return "\(seconds / (7 * day)) w ago"
|
||||
case ..<(365 * day): return "\(seconds / (30 * day)) mo ago"
|
||||
default: return "\(seconds / (365 * day)) y ago"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
/// Why no commit message came back; `detail` is the toast's mono line.
|
||||
public enum CommitMessageError: Error, Equatable {
|
||||
case notFound
|
||||
case timedOut
|
||||
/// The CLI could not start or exited non-zero; the first stderr line, else the exit code.
|
||||
case failed(String)
|
||||
/// The CLI answered with nothing usable.
|
||||
case empty
|
||||
|
||||
public var detail: String {
|
||||
switch self {
|
||||
case .notFound: "claude not found"
|
||||
case .timedOut: "timed out"
|
||||
case let .failed(reason): reason
|
||||
case .empty: "claude returned no message"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a commit message for a prompt built by `CommitMessagePrompt`.
|
||||
public protocol CommitMessageGenerating: Sendable {
|
||||
/// The cleaned one-line message; throws `CommitMessageError`, or `CancellationError` when the caller went away.
|
||||
func generate(prompt: String) async throws -> String
|
||||
}
|
||||
|
||||
/// Runs the Claude CLI in print mode, with no tools, in the project root.
|
||||
public struct ClaudeCommitMessageService: CommitMessageGenerating {
|
||||
public let root: URL
|
||||
private let runner: ProcessRunning
|
||||
private let locator: ExecutableLocator
|
||||
private let timeout: TimeInterval
|
||||
|
||||
/// No `--model`: the CLI's own default model writes the message.
|
||||
public static let arguments = [
|
||||
"-p", "--output-format", "text", "--no-session-persistence", "--strict-mcp-config", "--disable-slash-commands",
|
||||
"--tools", "",
|
||||
]
|
||||
|
||||
public init(root: URL, runner: ProcessRunning = ProcessRunner(), locator: ExecutableLocator = .agent, timeout: TimeInterval = 90) {
|
||||
self.root = root
|
||||
self.runner = runner
|
||||
self.locator = locator
|
||||
self.timeout = timeout
|
||||
}
|
||||
|
||||
/// The found binary's folder goes first on the child's PATH, so the CLI finds its own helpers.
|
||||
public func generate(prompt: String) async throws -> String {
|
||||
guard let binary = locator.locate("claude") else { throw CommitMessageError.notFound }
|
||||
var environment = ProcessInfo.processInfo.environment
|
||||
let folder = binary.deletingLastPathComponent().path
|
||||
environment["PATH"] = [folder, environment["PATH"]].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ":")
|
||||
let runner = self.runner, root = self.root, timeout = self.timeout
|
||||
|
||||
let outcome = try await withThrowingTaskGroup(of: ProcessResult?.self) { group -> ProcessResult? in
|
||||
group.addTask {
|
||||
do {
|
||||
return try await runner.run(binary.path, arguments: Self.arguments, in: root, environment: environment, input: prompt)
|
||||
} catch ProcessRunnerError.executableNotFound {
|
||||
throw CommitMessageError.notFound
|
||||
} catch let ProcessRunnerError.launchFailed(reason) {
|
||||
throw CommitMessageError.failed(reason)
|
||||
}
|
||||
}
|
||||
group.addTask {
|
||||
try await Task.sleep(nanoseconds: UInt64(max(0, timeout) * 1_000_000_000))
|
||||
return nil
|
||||
}
|
||||
defer { group.cancelAll() }
|
||||
return try await group.next() ?? nil
|
||||
}
|
||||
guard let result = outcome else { throw CommitMessageError.timedOut }
|
||||
guard result.succeeded else {
|
||||
throw CommitMessageError.failed(Self.reason(stderr: result.stderr) ?? "claude exited with code \(result.exitCode)")
|
||||
}
|
||||
guard let message = CommitMessagePrompt.clean(result.stdout) else { throw CommitMessageError.empty }
|
||||
return message
|
||||
}
|
||||
|
||||
/// The first stderr line; the CLI prints notices such as a sign-in expiry as "Warning: …" before the real error.
|
||||
static func reason(stderr: String) -> String? {
|
||||
let lines = stderr.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
|
||||
return lines.first { !$0.hasPrefix("Warning:") } ?? lines.first
|
||||
}
|
||||
}
|
||||
@@ -112,6 +112,21 @@ public actor GitService: GitServicing {
|
||||
return "\(name) <\(email)>"
|
||||
}
|
||||
|
||||
public func recentCommits() async -> [GitCommitSummary] {
|
||||
guard let result = try? await Self.run(GitCommitLogParsing.arguments, root: root, runner: runner), result.succeeded else {
|
||||
return []
|
||||
}
|
||||
return GitCommitLogParsing.commits(result.stdout)
|
||||
}
|
||||
|
||||
/// No external diff driver, so the patch is git's own text whatever the user configured.
|
||||
public func stagedDiff() async -> StagedDiff? {
|
||||
async let stat = try? Self.run(["diff", "--cached", "--no-color", "--no-ext-diff", "--stat"], root: root, runner: runner)
|
||||
async let patch = try? Self.run(["diff", "--cached", "--no-color", "--no-ext-diff"], root: root, runner: runner)
|
||||
guard let stat = await stat, stat.succeeded, let patch = await patch, patch.succeeded else { return nil }
|
||||
return StagedDiff(stat: stat.stdout, patch: patch.stdout)
|
||||
}
|
||||
|
||||
private func configValue(_ key: String) async -> String? {
|
||||
guard let result = try? await Self.run(["config", "--get", key], root: root, runner: runner), result.succeeded else { return nil }
|
||||
let value = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
|
||||
@@ -31,6 +31,10 @@ public protocol GitServicing: Sendable {
|
||||
func branches() async -> GitBranchList
|
||||
/// `user.name <user.email>` from git config, nil when unset.
|
||||
func author() async -> String?
|
||||
/// The last 30 commits of HEAD, newest first; empty without commits or outside a repository.
|
||||
func recentCommits() async -> [GitCommitSummary]
|
||||
/// `git diff --cached` as stat and patch; nil when git fails, e.g. outside a repository.
|
||||
func stagedDiff() async -> StagedDiff?
|
||||
}
|
||||
|
||||
extension GitServicing {
|
||||
|
||||
@@ -20,6 +20,16 @@ public struct ExecutableLocator: Sendable {
|
||||
return ExecutableLocator(directories: dirs.filter { seen.insert($0).inserted })
|
||||
}
|
||||
|
||||
/// `standard` plus the folders the Claude CLI installs itself into, which a GUI app's PATH never holds.
|
||||
public static var agent: ExecutableLocator {
|
||||
let home = FileManager.default.homeDirectoryForCurrentUser.path
|
||||
var locator = standard
|
||||
for dir in ["\(home)/.local/bin", "\(home)/.claude/local"] where !locator.directories.contains(dir) {
|
||||
locator.directories.append(dir)
|
||||
}
|
||||
return locator
|
||||
}
|
||||
|
||||
/// The first executable file called `name`, or nil. A name with a slash is checked as given.
|
||||
public func locate(_ name: String) -> URL? {
|
||||
let fm = FileManager.default
|
||||
|
||||
@@ -25,12 +25,21 @@ public protocol ProcessRunning: Sendable {
|
||||
/// Runs `executable` (a name looked up on the search path, or a path) and collects its output.
|
||||
/// A non-zero exit is a normal result, not an error; `environment: nil` inherits ours.
|
||||
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult
|
||||
/// Like `run`, with `input` written to the child's stdin, which is then closed.
|
||||
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||
input: String) async throws -> ProcessResult
|
||||
/// Like `run`, but hands each output line to `onLine` as it arrives (`isError` for stderr).
|
||||
func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult
|
||||
}
|
||||
|
||||
extension ProcessRunning {
|
||||
/// Refuses, so a runner that cannot feed stdin never runs a child that would wait on it.
|
||||
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||
input: String) async throws -> ProcessResult {
|
||||
throw ProcessRunnerError.launchFailed("stdin is not supported by \(type(of: self))")
|
||||
}
|
||||
|
||||
/// Runs to completion, then emits the stdout lines and after them the stderr lines.
|
||||
public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult {
|
||||
@@ -53,18 +62,23 @@ public struct ProcessRunner: ProcessRunning {
|
||||
}
|
||||
|
||||
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
|
||||
try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: nil)
|
||||
try await launch(executable, arguments: arguments, in: directory, environment: environment, input: nil, onLine: nil)
|
||||
}
|
||||
|
||||
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||
input: String) async throws -> ProcessResult {
|
||||
try await launch(executable, arguments: arguments, in: directory, environment: environment, input: Data(input.utf8), onLine: nil)
|
||||
}
|
||||
|
||||
public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult {
|
||||
try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: onLine)
|
||||
try await launch(executable, arguments: arguments, in: directory, environment: environment, input: nil, onLine: onLine)
|
||||
}
|
||||
|
||||
private func launch(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||
onLine: (@Sendable (String, Bool) -> Void)?) async throws -> ProcessResult {
|
||||
input: Data?, onLine: (@Sendable (String, Bool) -> Void)?) async throws -> ProcessResult {
|
||||
guard let url = locator.locate(executable) else { throw ProcessRunnerError.executableNotFound(executable) }
|
||||
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment, onLine: onLine)
|
||||
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment, input: input, onLine: onLine)
|
||||
return try await withTaskCancellationHandler {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
job.start(continuation)
|
||||
@@ -118,12 +132,14 @@ private final class Job: @unchecked Sendable {
|
||||
private var cancelled = false
|
||||
private var continuation: CheckedContinuation<ProcessResult, Error>?
|
||||
private let onLine: (@Sendable (String, Bool) -> Void)?
|
||||
private let input: Data?
|
||||
/// Keeps `onLine` to one call at a time, though both pipes feed it.
|
||||
private let emitLock = NSLock()
|
||||
|
||||
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?,
|
||||
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?, input: Data?,
|
||||
onLine: (@Sendable (String, Bool) -> Void)?) {
|
||||
self.onLine = onLine
|
||||
self.input = input
|
||||
process.executableURL = url
|
||||
process.arguments = arguments
|
||||
if let directory { process.currentDirectoryURL = directory }
|
||||
@@ -136,6 +152,8 @@ private final class Job: @unchecked Sendable {
|
||||
let err = Pipe()
|
||||
process.standardOutput = out
|
||||
process.standardError = err
|
||||
let stdin = input.map { _ in Pipe() }
|
||||
if let stdin { process.standardInput = stdin }
|
||||
|
||||
let group = DispatchGroup()
|
||||
var outData = Data()
|
||||
@@ -159,6 +177,10 @@ private final class Job: @unchecked Sendable {
|
||||
self.continuation = continuation
|
||||
lock.unlock()
|
||||
|
||||
if let stdin, let input {
|
||||
DispatchQueue.global().async { Self.write(input, to: stdin.fileHandleForWriting) }
|
||||
}
|
||||
|
||||
group.enter()
|
||||
DispatchQueue.global().async { [self] in
|
||||
outData = drain(out.fileHandleForReading, isError: false)
|
||||
@@ -178,6 +200,14 @@ private final class Job: @unchecked Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes on its own thread, since a child that stops reading would block it. A child that exits
|
||||
/// early makes the write fail instead of raising SIGPIPE, which would end the app.
|
||||
private static func write(_ data: Data, to handle: FileHandle) {
|
||||
_ = fcntl(handle.fileDescriptor, F_SETNOSIGPIPE, 1)
|
||||
try? handle.write(contentsOf: data)
|
||||
try? handle.close()
|
||||
}
|
||||
|
||||
/// Resumes the caller once; whichever of finish and cancel comes second is dropped.
|
||||
private func resume(with result: Result<ProcessResult, Error>) {
|
||||
lock.lock()
|
||||
|
||||
@@ -43,6 +43,7 @@ public struct ContextMenuHeader: View {
|
||||
|
||||
/// One 30pt menu item. Highlighted: `raised` fill, 2pt amber left rule, text-1 500 label, amber icon.
|
||||
/// A tinted icon keeps its tint when highlighted; destructive items stay amber-deep in every state.
|
||||
/// Disabled is 40% opacity and the arrow; it still takes hover, so a tooltip on it can show.
|
||||
public struct ContextMenuRow: View {
|
||||
var label: String
|
||||
var systemImage: String?
|
||||
@@ -51,9 +52,10 @@ public struct ContextMenuRow: View {
|
||||
var isHighlighted: Bool
|
||||
var isDestructive: Bool
|
||||
var isEmphasized: Bool
|
||||
var isDisabled: Bool
|
||||
|
||||
public init(_ label: String, systemImage: String? = nil, iconTint: Color? = nil, shortcut: String? = nil,
|
||||
isHighlighted: Bool, isDestructive: Bool = false, isEmphasized: Bool = false) {
|
||||
isHighlighted: Bool, isDestructive: Bool = false, isEmphasized: Bool = false, isDisabled: Bool = false) {
|
||||
self.label = label
|
||||
self.systemImage = systemImage
|
||||
self.iconTint = iconTint
|
||||
@@ -61,6 +63,7 @@ public struct ContextMenuRow: View {
|
||||
self.isHighlighted = isHighlighted
|
||||
self.isDestructive = isDestructive
|
||||
self.isEmphasized = isEmphasized
|
||||
self.isDisabled = isDisabled
|
||||
}
|
||||
|
||||
/// Pass as `systemImage` for the pass-on spark, which has no SF Symbol.
|
||||
@@ -93,8 +96,9 @@ public struct ContextMenuRow: View {
|
||||
.overlay(alignment: .leading) {
|
||||
Rectangle().fill(isHighlighted ? Palette.amber : .clear).frame(width: Metrics.accentRule)
|
||||
}
|
||||
.opacity(isDisabled ? 0.4 : 1)
|
||||
.contentShape(Rectangle())
|
||||
.pointerHand()
|
||||
.pointerHand(!isDisabled)
|
||||
}
|
||||
|
||||
private var labelRole: TypeRole {
|
||||
|
||||
@@ -216,6 +216,10 @@ private struct DiffContextMenu: View {
|
||||
isHighlighted: highlighted == index, isDestructive: action.isDestructive)
|
||||
.onHover { inside in if inside { highlighted = index } }
|
||||
.onTapGesture { choose(action) }
|
||||
case let .disabled(action, label, _):
|
||||
ContextMenuRow(label, systemImage: ContextMenuOverlay.symbol(for: action),
|
||||
iconTint: ContextMenuOverlay.tint(for: action).color,
|
||||
isHighlighted: false, isDisabled: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// Column B: the file tree, flattened to its visible rows so thousands of files stay lazy.
|
||||
/// Column B: the file tree, flattened to its visible rows so thousands of files stay lazy,
|
||||
/// with the tail block under it while a `.log` file is tailed.
|
||||
public struct ExplorerColumn: View {
|
||||
let model: WorkspaceModel
|
||||
@State private var columnFrame = CGRect.zero
|
||||
@@ -15,11 +16,19 @@ public struct ExplorerColumn: View {
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
header
|
||||
GeometryReader { proxy in
|
||||
VStack(spacing: 0) {
|
||||
if let store = model.explorer {
|
||||
tree(store)
|
||||
} else {
|
||||
Spacer()
|
||||
}
|
||||
if let path = model.terminal.tailedPath {
|
||||
TailBlock(model: model, path: path)
|
||||
.frame(height: proxy.size.height * Self.tailFraction)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(Palette.column(.explorer, active: isActive))
|
||||
@@ -27,6 +36,8 @@ public struct ExplorerColumn: View {
|
||||
.simultaneousGesture(TapGesture().onEnded { model.pointerFocused(.explorer) })
|
||||
}
|
||||
|
||||
private static let tailFraction = 0.4
|
||||
|
||||
private var isActive: Bool { model.layout.activePanel == .explorer }
|
||||
private var showHidden: Bool { model.layout.showHidden }
|
||||
|
||||
@@ -107,6 +118,53 @@ public struct ExplorerColumn: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// `tail -f` on one log file: a header with the file name and a close button over a live terminal.
|
||||
private struct TailBlock: View {
|
||||
let model: WorkspaceModel
|
||||
let path: String
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack(spacing: 8) {
|
||||
Text("Tail").typeRole(Typography.panelLabel).foregroundStyle(Palette.text4)
|
||||
Spacer(minLength: 8)
|
||||
Text(PathUtils.basename(path))
|
||||
.typeRole(Typography.panelLabel)
|
||||
.foregroundStyle(Palette.text4)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
.help(path)
|
||||
CloseTailButton { model.perform(.closeTail) }
|
||||
}
|
||||
.padding(.leading, 12)
|
||||
.padding(.trailing, 8)
|
||||
.frame(height: Metrics.panelHeader)
|
||||
.hairline(.top)
|
||||
.zIndex(1)
|
||||
TerminalPane(kind: .tail, store: model.terminal, scale: model.layout.textScale)
|
||||
.id(model.terminal.tailGeneration)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct CloseTailButton: View {
|
||||
let action: () -> Void
|
||||
@State private var isHovered = false
|
||||
|
||||
var body: some View {
|
||||
Button(action: action) {
|
||||
GitIconView(icon: .x, size: 14)
|
||||
.foregroundStyle(isHovered ? Palette.text1 : Palette.text4)
|
||||
.padding(4)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.pointerHand()
|
||||
.tracksHover($isHovered)
|
||||
.tip("Stop tailing", edge: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
/// One tree row: indent, chevron, folder glyph or type badge, name, change letter.
|
||||
private struct TreeRowView: View {
|
||||
let row: TreeRow
|
||||
|
||||
@@ -3,6 +3,7 @@ import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// Local and origin branches; a click switches, but only while the working tree is clean.
|
||||
/// A right click offers to merge the branch into the current one.
|
||||
struct GitBranchesPanel: View {
|
||||
let model: WorkspaceModel
|
||||
let store: SourceControlStore
|
||||
@@ -60,7 +61,8 @@ struct GitBranchesPanel: View {
|
||||
name: name, remote: remote, current: current, locked: !current && store.isDirty,
|
||||
meta: current ? "current" : (tracked ? "tracked" : ""),
|
||||
action: canSwitch ? (remote && !tracked ? "checkout →" : "switch →") : "",
|
||||
clickable: !current && !isCurrentUpstream
|
||||
clickable: !current && !isCurrentUpstream,
|
||||
menu: .branch(name: name, remote: remote, current: store.state.branch, isDirty: store.isDirty)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -74,6 +76,7 @@ private struct BranchItem {
|
||||
let meta: String
|
||||
let action: String
|
||||
let clickable: Bool
|
||||
let menu: ContextTarget
|
||||
}
|
||||
|
||||
private struct BranchRow: View {
|
||||
@@ -112,6 +115,9 @@ private struct BranchRow: View {
|
||||
model.perform(.switchBranch(item.name, remote: item.remote))
|
||||
}
|
||||
.pointerHand(item.clickable && !item.locked)
|
||||
.overlay(RightClickArea { point in
|
||||
model.perform(.showContextMenu(item.menu, anchor: point))
|
||||
})
|
||||
.tracksHover($isHovered)
|
||||
.modifier(LockedTip(isLocked: item.locked))
|
||||
}
|
||||
@@ -131,12 +137,12 @@ private struct LockedTip: ViewModifier {
|
||||
|
||||
/// Puts the enclosing scroll view's scrollers over the content, so rows keep their 16px right padding.
|
||||
/// A legacy scroller would take its width from the rows whenever the list overflows.
|
||||
private struct OverlayScrollers: NSViewRepresentable {
|
||||
struct OverlayScrollers: NSViewRepresentable {
|
||||
func makeNSView(context: Context) -> OverlayScrollersProbe { OverlayScrollersProbe() }
|
||||
func updateNSView(_ view: OverlayScrollersProbe, context: Context) { view.apply() }
|
||||
}
|
||||
|
||||
private final class OverlayScrollersProbe: NSView {
|
||||
final class OverlayScrollersProbe: NSView {
|
||||
private var observer: NSObjectProtocol?
|
||||
|
||||
override func viewDidMoveToWindow() {
|
||||
|
||||
@@ -2,7 +2,7 @@ import AppKit
|
||||
import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// The message field over the author, the ⌘↵ hint and the Commit split button.
|
||||
/// The message field over Gen. Commit Message, the author, the ⌘↵ hint and the three commit buttons.
|
||||
struct GitCommitBlock: View {
|
||||
let model: WorkspaceModel
|
||||
let store: SourceControlStore
|
||||
@@ -22,12 +22,13 @@ struct GitCommitBlock: View {
|
||||
}
|
||||
.animation(Metrics.colorTransition, value: isFocused)
|
||||
HStack(spacing: 16) {
|
||||
GenerateMessageButton(model: model, store: store)
|
||||
if let author = store.author {
|
||||
Text(author).typeRole(Typography.path).foregroundStyle(Palette.textMuted).lineLimit(1)
|
||||
}
|
||||
Text("⌘↵ commits").typeRole(Typography.path).foregroundStyle(Palette.text4).fixedSize()
|
||||
Spacer(minLength: 0)
|
||||
CommitSplitButton(model: model, store: store)
|
||||
CommitButtons(model: model, store: store)
|
||||
}
|
||||
.padding(.leading, 16)
|
||||
.padding(.trailing, 14)
|
||||
@@ -43,57 +44,93 @@ struct GitCommitBlock: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// `Commit N files` plus a caret that opens Commit / Commit and push. Amber only when git would accept it,
|
||||
/// but both parts always run, so git's own refusal shows in the console.
|
||||
private struct CommitSplitButton: View {
|
||||
/// `Gen. Commit Message`: the Claude CLI writes the message for the staged changes. Dims while nothing is staged
|
||||
/// and while a message is being written.
|
||||
private struct GenerateMessageButton: View {
|
||||
let model: WorkspaceModel
|
||||
let store: SourceControlStore
|
||||
@State private var mainHovered = false
|
||||
@State private var caretHovered = false
|
||||
@State private var caretFrame = CGRect.zero
|
||||
@State private var hovered = false
|
||||
|
||||
var body: some View {
|
||||
let ready = store.canCommitNow
|
||||
let count = store.stagedPathCount
|
||||
HStack(spacing: 0) {
|
||||
Button { model.perform(.commit) } label: {
|
||||
Text(count > 0 ? "Commit \(count) file\(count == 1 ? "" : "s")" : "Nothing staged")
|
||||
let color = hovered ? Palette.text1 : Palette.text3
|
||||
Button { model.perform(.generateCommitMessage) } label: {
|
||||
HStack(spacing: 7) {
|
||||
SparkGlyph()
|
||||
.stroke(color, style: StrokeStyle(lineWidth: 1.1 * 12 / 16, lineJoin: .round))
|
||||
.frame(width: 12, height: 12)
|
||||
Text(store.isGeneratingMessage ? "Generating…" : "Gen. Commit Message")
|
||||
.typeRole(Typography.gitCommitButton)
|
||||
.padding(.horizontal, 18)
|
||||
.frame(minWidth: GitMetrics.commitButtonMinWidth)
|
||||
.foregroundStyle(color)
|
||||
}
|
||||
.padding(.horizontal, 12)
|
||||
.frame(height: GitMetrics.commitButton)
|
||||
.background(fill(ready: ready, hovered: mainHovered))
|
||||
.background(hovered ? Palette.hover : .clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
||||
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.pointerHand()
|
||||
.tracksHover($mainHovered)
|
||||
Button(action: openMenu) {
|
||||
GitIconView(icon: .chevronDown, size: 14)
|
||||
.frame(width: GitMetrics.commitButton, height: GitMetrics.commitButton)
|
||||
.background(fill(ready: ready, hovered: caretHovered))
|
||||
.overlay(alignment: .leading) { Rectangle().fill(Palette.editor).frame(width: Metrics.hairline) }
|
||||
.tracksHover($hovered)
|
||||
.disabledLook(!store.canGenerateMessage)
|
||||
.fixedSize()
|
||||
}
|
||||
}
|
||||
|
||||
/// `Add, Stage & Commit` and `Commit N files` beside the primary `Commit and push`. The last two dim while nothing is staged;
|
||||
/// with files staged they always run, so git's refusal of an empty message shows in the console.
|
||||
private struct CommitButtons: View {
|
||||
let model: WorkspaceModel
|
||||
let store: SourceControlStore
|
||||
@State private var stageAllHovered = false
|
||||
@State private var commitHovered = false
|
||||
@State private var pushHovered = false
|
||||
|
||||
var body: some View {
|
||||
let count = store.stagedPathCount
|
||||
HStack(spacing: 8) {
|
||||
secondaryButton("Add, Stage & Commit", command: .stageAllAndCommit, hovered: $stageAllHovered)
|
||||
.disabledLook(!store.canStageAllAndCommit)
|
||||
HStack(spacing: 8) {
|
||||
secondaryButton(count > 0 ? "Commit \(count) file\(count == 1 ? "" : "s")" : "Nothing staged",
|
||||
command: .commit, hovered: $commitHovered)
|
||||
Button { model.perform(.commitAndPush) } label: {
|
||||
Text("Commit and push")
|
||||
.typeRole(Typography.gitCommitButton)
|
||||
.foregroundStyle(store.canCommitNow ? Palette.badgeText : Palette.textMuted)
|
||||
.padding(.horizontal, 18)
|
||||
.frame(height: GitMetrics.commitButton)
|
||||
.background(pushFill, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.pointerHand()
|
||||
.tracksHover($caretHovered)
|
||||
.background(GlobalFrameReader(frame: $caretFrame))
|
||||
.tracksHover($pushHovered)
|
||||
}
|
||||
.disabledLook(count == 0)
|
||||
}
|
||||
.foregroundStyle(ready ? Palette.badgeText : Palette.textMuted)
|
||||
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
||||
.fixedSize()
|
||||
}
|
||||
|
||||
private func fill(ready: Bool, hovered: Bool) -> Color {
|
||||
if ready { return hovered ? Palette.amberDeep : Palette.amber }
|
||||
return hovered ? Palette.commitIdleHover : Palette.raised
|
||||
private func secondaryButton(_ title: String, command: Command, hovered: Binding<Bool>) -> some View {
|
||||
Button { model.perform(command) } label: {
|
||||
Text(title)
|
||||
.typeRole(Typography.gitCommitButton)
|
||||
.foregroundStyle(hovered.wrappedValue ? Palette.text1 : Palette.text3)
|
||||
.padding(.horizontal, 18)
|
||||
.frame(minWidth: GitMetrics.commitButtonMinWidth)
|
||||
.frame(height: GitMetrics.commitButton)
|
||||
.background(hovered.wrappedValue ? Palette.hover : .clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
||||
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.raised, lineWidth: Metrics.hairline))
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.pointerHand()
|
||||
.tracksHover(hovered)
|
||||
}
|
||||
|
||||
/// The menu hangs under the caret, right-aligned to it.
|
||||
private func openMenu() {
|
||||
let anchor = CGPoint(x: caretFrame.maxX - Metrics.contextMenuWidth, y: caretFrame.maxY + 4)
|
||||
model.perform(.showContextMenu(.commitMenu, anchor: anchor))
|
||||
private var pushFill: Color {
|
||||
if store.canCommitNow { return pushHovered ? Palette.amberDeep : Palette.amber }
|
||||
return pushHovered ? Palette.commitIdleHover : Palette.raised
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// The bottom strip's right end on a wide window: the last commits of the current branch, read-only.
|
||||
struct GitCommitsPanel: View {
|
||||
let store: SourceControlStore
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
header
|
||||
if !store.state.isRepository {
|
||||
placeholder("— no repository")
|
||||
} else if store.recentCommits.isEmpty {
|
||||
placeholder("no commits yet")
|
||||
} else {
|
||||
ScrollView {
|
||||
TimelineView(.periodic(from: .now, by: 30)) { context in
|
||||
LazyVStack(alignment: .leading, spacing: 0) {
|
||||
ForEach(store.recentCommits, id: \.hash) { commit in
|
||||
CommitRow(commit: commit, now: context.date)
|
||||
}
|
||||
}
|
||||
.padding(.bottom, 12)
|
||||
}
|
||||
.background(OverlayScrollers())
|
||||
}
|
||||
.scrollIndicators(.automatic)
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.clipped()
|
||||
}
|
||||
|
||||
private var header: some View {
|
||||
HStack(spacing: 12) {
|
||||
Text("[ commits ]").typeRole(Typography.panelLabel).foregroundStyle(Palette.text4).fixedSize()
|
||||
Spacer(minLength: 0)
|
||||
if store.state.isRepository {
|
||||
Text(store.state.branch)
|
||||
.typeRole(Typography.path)
|
||||
.foregroundStyle(Palette.textMuted)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.frame(height: GitMetrics.stripHeader)
|
||||
}
|
||||
|
||||
private func placeholder(_ text: String) -> some View {
|
||||
Text(text)
|
||||
.typeRole(Typography.path)
|
||||
.foregroundStyle(Palette.text4)
|
||||
.padding(.horizontal, 16)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private struct CommitRow: View {
|
||||
let commit: GitCommitSummary
|
||||
let now: Date
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 10) {
|
||||
Text(commit.hash).typeRole(Typography.gitStats).foregroundStyle(Palette.amber).fixedSize()
|
||||
Text(commit.subject)
|
||||
.typeRole(Typography.path)
|
||||
.foregroundStyle(Palette.text2)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
HStack(spacing: 0) {
|
||||
Text(commit.author).lineLimit(1).truncationMode(.tail).frame(maxWidth: 140, alignment: .trailing)
|
||||
Text(" · \(RelativeTime.text(commit.date, now: now))").fixedSize()
|
||||
}
|
||||
.typeRole(Typography.meta)
|
||||
.foregroundStyle(Palette.text4)
|
||||
.layoutPriority(1)
|
||||
}
|
||||
.padding(.horizontal, 16)
|
||||
.frame(height: GitMetrics.branchRow)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import HelderCore
|
||||
import SwiftUI
|
||||
|
||||
/// `[ git ]`, the branch and its place against origin, then Pull, Push and Close.
|
||||
/// `[ git ]`, the branch and its place against origin, then Pull, Push, Clean up and Close.
|
||||
struct GitTopBar: View {
|
||||
let model: WorkspaceModel
|
||||
let store: SourceControlStore
|
||||
@@ -21,9 +21,12 @@ struct GitTopBar: View {
|
||||
trailing: state.behind > 0 ? "↓\(state.behind)" : nil) { model.perform(.pull) }
|
||||
GitBarButton(icon: .arrowUpFromLine, label: store.busy == .push ? "Pushing…" : "Push",
|
||||
trailing: state.ahead > 0 ? "↑\(state.ahead)" : nil) { model.perform(.push) }
|
||||
GitBarButton(icon: .eraser, label: "Clean up", trailing: nil) { model.perform(.context(.gitCleanUp)) }
|
||||
.disabledLook(!store.canCleanUp)
|
||||
GitBarButton(icon: .minimize, label: "Close", trailing: "⌘G") { model.perform(.closeGitView) }
|
||||
}
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.leading, model.layout.isFullScreen ? 14 : Metrics.trafficLightInset)
|
||||
.padding(.trailing, 14)
|
||||
.frame(height: GitMetrics.topBar)
|
||||
.background(Palette.panel)
|
||||
.hairline(.bottom)
|
||||
|
||||
@@ -25,18 +25,27 @@ struct GitView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// The console left, the branches right, 230pt tall.
|
||||
/// The console left, the branches right, 230pt tall; a wide window adds the commit list after them.
|
||||
private struct GitBottomStrip: View {
|
||||
let model: WorkspaceModel
|
||||
let store: SourceControlStore
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { proxy in
|
||||
let layout = GitStripLayout(width: proxy.size.width)
|
||||
HStack(spacing: 0) {
|
||||
GitConsolePanel(model: model, store: store)
|
||||
.frame(maxWidth: .infinity)
|
||||
.frame(width: layout.console)
|
||||
Hairline(.vertical)
|
||||
GitBranchesPanel(model: model, store: store)
|
||||
.frame(maxWidth: .infinity)
|
||||
.frame(width: layout.branches)
|
||||
if let commits = layout.commits {
|
||||
Hairline(.vertical)
|
||||
GitCommitsPanel(store: store)
|
||||
.frame(width: commits)
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
}
|
||||
.frame(height: GitMetrics.bottomStrip)
|
||||
.background(Palette.panel)
|
||||
@@ -44,6 +53,23 @@ private struct GitBottomStrip: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// The widths of the bottom strip's panels for one strip width.
|
||||
struct GitStripLayout: Equatable {
|
||||
var console: CGFloat
|
||||
var branches: CGFloat
|
||||
/// Nil while the room left after the two capped panels is under `GitMetrics.commitsMinWidth`.
|
||||
var commits: CGFloat?
|
||||
|
||||
init(width: CGFloat) {
|
||||
let hairline = Metrics.hairline
|
||||
let share = max(0, (width - hairline) / 2).rounded(.down)
|
||||
console = min(GitMetrics.consoleMaxWidth, share)
|
||||
branches = min(GitMetrics.branchesMaxWidth, share)
|
||||
let left = width - console - branches - 2 * hairline
|
||||
commits = left >= GitMetrics.commitsMinWidth ? left : nil
|
||||
}
|
||||
}
|
||||
|
||||
/// The Git view's fixed sizes, from the design handoff.
|
||||
enum GitMetrics {
|
||||
static let topBar: CGFloat = 44
|
||||
@@ -68,6 +94,9 @@ enum GitMetrics {
|
||||
static let diffGutter: CGFloat = 52
|
||||
static let diffGap: CGFloat = 28
|
||||
static let bottomStrip: CGFloat = 230
|
||||
static let consoleMaxWidth: CGFloat = 820
|
||||
static let branchesMaxWidth: CGFloat = 820
|
||||
static let commitsMinWidth: CGFloat = 260
|
||||
static let stripHeader: CGFloat = 32
|
||||
static let branchRow: CGFloat = 28
|
||||
}
|
||||
|
||||
@@ -4,18 +4,19 @@ import SwiftUI
|
||||
|
||||
enum MenuCursor {
|
||||
static func first(in entries: [ContextMenuEntry]) -> Int? {
|
||||
entries.firstIndex { $0 != .separator }
|
||||
entries.firstIndex(where: \.isSelectable)
|
||||
}
|
||||
|
||||
/// The next selectable entry in `step` direction, wrapping around and skipping separators.
|
||||
static func step(_ current: Int, by step: Int, in entries: [ContextMenuEntry]) -> Int {
|
||||
guard !entries.isEmpty else { return current }
|
||||
/// The next selectable entry in `step` direction, wrapping around and skipping separators and disabled
|
||||
/// entries; nil when the menu has none.
|
||||
static func step(_ current: Int, by step: Int, in entries: [ContextMenuEntry]) -> Int? {
|
||||
guard !entries.isEmpty else { return nil }
|
||||
var index = current
|
||||
for _ in entries.indices {
|
||||
index = (index + step + entries.count) % entries.count
|
||||
if entries[index] != .separator { return index }
|
||||
if entries[index].isSelectable { return index }
|
||||
}
|
||||
return current
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +83,10 @@ struct ContextMenuOverlay: View {
|
||||
isEmphasized: action.isEmphasized)
|
||||
.onHover { inside in if inside { highlighted = index } }
|
||||
.onTapGesture { onPerform(action) }
|
||||
case let .disabled(action, label, hint):
|
||||
ContextMenuRow(label, systemImage: Self.symbol(for: action), iconTint: Self.tint(for: action).color,
|
||||
isHighlighted: false, isDisabled: true)
|
||||
.tip(hint)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,11 +115,11 @@ struct ContextMenuOverlay: View {
|
||||
nonisolated static func tint(for action: ContextAction) -> MenuIconTint {
|
||||
switch action {
|
||||
case .copyReference, .copyTerminalSelection, .pasteIntoTerminal, .readAloudFile, .readAloudText, .readAloudTerminalSelection,
|
||||
.plak, .plakTerminalSelection, .openFile, .commit: .plain
|
||||
.plak, .plakTerminalSelection, .openFile, .mergeBranch, .tailLog: .plain
|
||||
case .newFile, .newFolder: .add
|
||||
case .copyFileName, .revealInFinder: .modify
|
||||
case .passOnReference, .passOnFileName, .bouwen, .waitWhat, .showDiff, .rename: .rename
|
||||
case .gitDiscard, .delete: .danger
|
||||
case .gitDiscard, .gitCleanUp, .delete: .danger
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,16 +132,17 @@ struct ContextMenuOverlay: View {
|
||||
case .plak, .plakTerminalSelection: "note.text.badge.plus"
|
||||
case .copyReference, .copyFileName, .copyTerminalSelection: "doc.on.doc"
|
||||
case .openFile: "doc.text"
|
||||
case .commit(andPush: false): "checkmark"
|
||||
case .commit(andPush: true): "arrow.up.to.line"
|
||||
case .pasteIntoTerminal: "doc.on.clipboard"
|
||||
case .newFile: "doc.badge.plus"
|
||||
case .newFolder: "folder.badge.plus"
|
||||
case .showDiff: "arrow.left.arrow.right"
|
||||
case .gitDiscard: "arrow.uturn.backward"
|
||||
case .gitCleanUp: "eraser"
|
||||
case .rename: "pencil"
|
||||
case .revealInFinder: "folder"
|
||||
case .delete: "trash"
|
||||
case .mergeBranch: "arrow.triangle.merge"
|
||||
case .tailLog: "terminal"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,8 @@ struct SchemaTopBar: View {
|
||||
.disabledLook(!store.hasCommand)
|
||||
GitBarButton(icon: .minimize, label: "Close", trailing: "⌘D") { model.perform(.closeSchemaView) }
|
||||
}
|
||||
.padding(.horizontal, 14)
|
||||
.padding(.leading, model.layout.isFullScreen ? 14 : Metrics.trafficLightInset)
|
||||
.padding(.trailing, 14)
|
||||
.frame(height: SchemaViewMetrics.topBar)
|
||||
.background(Palette.panel)
|
||||
.hairline(.bottom)
|
||||
|
||||
@@ -114,10 +114,21 @@ public enum Command: Equatable, Sendable {
|
||||
/// ⌘A outside a text field: the whole open file in its pane.
|
||||
case selectAllInFile
|
||||
|
||||
// MARK: Explorer tail
|
||||
|
||||
/// The tail block's close button: ends `tail -f` and removes the block.
|
||||
case closeTail
|
||||
|
||||
// MARK: Git
|
||||
|
||||
/// ⌘↵ and the Commit button: always runs git, so its refusal shows in the console.
|
||||
case commit
|
||||
/// The Commit and push button: pushes only after a successful commit.
|
||||
case commitAndPush
|
||||
/// The Add, Stage & Commit button: stages every change, then commits without a push.
|
||||
case stageAllAndCommit
|
||||
/// The Gen. Commit Message button: the Claude CLI writes a message for the staged changes.
|
||||
case generateCommitMessage
|
||||
/// ⌘P
|
||||
case push
|
||||
case pull
|
||||
|
||||
@@ -42,7 +42,11 @@ public final class SourceControlStore {
|
||||
/// `user.name <user.email>`, read when the view opens.
|
||||
public private(set) var author: String?
|
||||
public private(set) var branches = GitBranchList.empty
|
||||
/// The last 30 commits of HEAD, read with the branches.
|
||||
public private(set) var recentCommits: [GitCommitSummary] = []
|
||||
public private(set) var busy: GitBusy?
|
||||
/// True while the Claude CLI writes a commit message for the staged changes.
|
||||
public private(set) var isGeneratingMessage = false
|
||||
public private(set) var lines: [GitConsoleEntry] = []
|
||||
public var consoleInput = ""
|
||||
public private(set) var history: [String] = []
|
||||
@@ -58,10 +62,11 @@ public final class SourceControlStore {
|
||||
|
||||
/// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`.
|
||||
@ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in }
|
||||
/// Asks for the keyboard in the message field, after git refused an empty message.
|
||||
/// Asks for the keyboard in the message field, after an empty message was refused.
|
||||
@ObservationIgnored public var focusMessage: () -> Void = {}
|
||||
|
||||
@ObservationIgnored private let git: GitServicing
|
||||
@ObservationIgnored private let commitMessages: CommitMessageGenerating?
|
||||
@ObservationIgnored private let derive: @Sendable (GitSnapshot?) -> GitWorkingState
|
||||
@ObservationIgnored private var refreshGeneration = 0
|
||||
@ObservationIgnored private var pollTask: Task<Void, Never>?
|
||||
@@ -74,9 +79,12 @@ public final class SourceControlStore {
|
||||
/// The status error already in the console, so a poll that keeps failing logs it once.
|
||||
@ObservationIgnored private var loggedStatusError: String?
|
||||
|
||||
/// `derive` runs off the main actor, since it diffs every changed file.
|
||||
public init(git: GitServicing, derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
|
||||
/// `derive` runs off the main actor, since it diffs every changed file. Without `commitMessages` the
|
||||
/// generate button stays off.
|
||||
public init(git: GitServicing, commitMessages: CommitMessageGenerating? = nil,
|
||||
derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
|
||||
self.git = git
|
||||
self.commitMessages = commitMessages
|
||||
self.derive = derive
|
||||
}
|
||||
|
||||
@@ -91,19 +99,37 @@ public final class SourceControlStore {
|
||||
return out
|
||||
}
|
||||
|
||||
/// Any change, staged or not; it locks branch switching.
|
||||
/// Any change, staged or not; it locks branch switching and merging.
|
||||
public var isDirty: Bool { !state.changes.isEmpty }
|
||||
|
||||
/// Distinct changed paths, a file with two rows once.
|
||||
public var changedPathCount: Int { Set(state.changes.map(\.path)).count }
|
||||
|
||||
/// Distinct paths with an unstaged row: what Clean up throws away.
|
||||
public var cleanUpPathCount: Int { Set(state.changes.filter { !$0.staged }.map(\.path)).count }
|
||||
|
||||
/// Off while a push or pull runs, and during a conflict, which only a resolution may touch.
|
||||
public var canCleanUp: Bool {
|
||||
busy == nil && cleanUpPathCount > 0 && !state.changes.contains { $0.status == .unmerged }
|
||||
}
|
||||
|
||||
public var stagedPathCount: Int { GitSections.uniquePaths(state.changes.filter(\.staged)).count }
|
||||
|
||||
/// Off without changes, while a push or pull runs, and during a conflict: staging a conflicted file marks it resolved.
|
||||
public var canStageAllAndCommit: Bool {
|
||||
busy == nil && isDirty && !state.changes.contains { $0.status == .unmerged }
|
||||
}
|
||||
|
||||
/// The ready look of the Commit button; the button itself always runs git.
|
||||
public var canCommitNow: Bool {
|
||||
stagedPathCount > 0 && !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty
|
||||
}
|
||||
|
||||
/// The Gen. Commit Message button's on state.
|
||||
public var canGenerateMessage: Bool {
|
||||
commitMessages != nil && stagedPathCount > 0 && !isGeneratingMessage
|
||||
}
|
||||
|
||||
public var syncLabel: String {
|
||||
GitConsoleText.syncLabel(ahead: state.ahead, behind: state.behind, upstream: state.upstream)
|
||||
}
|
||||
@@ -144,6 +170,31 @@ public final class SourceControlStore {
|
||||
commitMessage = SourceControlText.normalizeCommitMessage(value)
|
||||
}
|
||||
|
||||
public static let generateFailedTitle = "Couldn't generate a commit message"
|
||||
|
||||
/// Replaces the draft with the message the Claude CLI writes for the staged diff, then focuses the field.
|
||||
/// Ignored while one is being written or nothing is staged.
|
||||
public func generateCommitMessage() async {
|
||||
guard let commitMessages, canGenerateMessage else { return }
|
||||
isGeneratingMessage = true
|
||||
defer { isGeneratingMessage = false }
|
||||
guard let staged = await git.stagedDiff(), !staged.isEmpty else {
|
||||
notify(Self.generateFailedTitle, "no staged diff")
|
||||
return
|
||||
}
|
||||
do {
|
||||
let message = try await commitMessages.generate(prompt: CommitMessagePrompt.make(staged))
|
||||
setCommitMessage(message)
|
||||
focusMessage()
|
||||
} catch is CancellationError {
|
||||
return
|
||||
} catch let error as CommitMessageError {
|
||||
notify(Self.generateFailedTitle, error.detail)
|
||||
} catch {
|
||||
notify(Self.generateFailedTitle, "\(error)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Reading git
|
||||
|
||||
/// Re-reads git and derives rows and diffs; a result that a newer refresh overtook is dropped.
|
||||
@@ -183,11 +234,16 @@ public final class SourceControlStore {
|
||||
branches = await git.branches()
|
||||
}
|
||||
|
||||
/// The Git view opened: reads the author and the branches, then fetches origin so ahead/behind are honest.
|
||||
public func reloadRecentCommits() async {
|
||||
recentCommits = await git.recentCommits()
|
||||
}
|
||||
|
||||
/// The Git view opened: reads the author, the branches and the recent commits, then fetches origin so ahead/behind are honest.
|
||||
/// Without an origin there is nothing to fetch, so the console stays quiet.
|
||||
public func viewOpened() async {
|
||||
author = await git.author()
|
||||
await reloadBranches()
|
||||
await reloadRecentCommits()
|
||||
await loadIfNeeded()
|
||||
guard !isFetching, state.isRepository, !branches.remote.isEmpty || state.upstream?.hasPrefix("origin/") == true else { return }
|
||||
isFetching = true
|
||||
@@ -199,10 +255,12 @@ public final class SourceControlStore {
|
||||
// MARK: Staging
|
||||
|
||||
/// Always the listed paths, never `add -A`, which would also take files the view has not shown yet.
|
||||
public func stage(_ paths: [String]) async {
|
||||
guard !paths.isEmpty else { return }
|
||||
await run(["add", "--"] + paths)
|
||||
@discardableResult
|
||||
public func stage(_ paths: [String]) async -> Bool {
|
||||
guard !paths.isEmpty else { return true }
|
||||
let result = await run(["add", "--"] + paths)
|
||||
await afterCommand()
|
||||
return result.succeeded
|
||||
}
|
||||
|
||||
/// A staged rename takes its source along, or the old path stays staged as deleted.
|
||||
@@ -232,13 +290,71 @@ public final class SourceControlStore {
|
||||
await afterCommand()
|
||||
}
|
||||
|
||||
/// Reverts unstaged edits to the index and removes untracked files and folders; staged content and ignored files stay.
|
||||
public func cleanUp() async {
|
||||
guard canCleanUp else { return }
|
||||
let unstaged = state.changes.filter { !$0.staged }
|
||||
let count = cleanUpPathCount
|
||||
var failure: (GitCommandResult, [String])?
|
||||
if unstaged.contains(where: { $0.status != .added }) {
|
||||
let arguments = ["restore", "--worktree", "--", "."]
|
||||
let result = await run(arguments)
|
||||
if !result.succeeded { failure = (result, arguments) }
|
||||
}
|
||||
if unstaged.contains(where: { $0.status == .added }) {
|
||||
// No -x: ignored files such as .env, vendor/ and node_modules/ must survive.
|
||||
let arguments = ["clean", "-fd"]
|
||||
let result = await run(arguments)
|
||||
if !result.succeeded && failure == nil { failure = (result, arguments) }
|
||||
}
|
||||
await afterCommand()
|
||||
if case let (result, arguments)? = failure {
|
||||
notify("Clean up failed", Self.failureDetail(of: result, arguments: arguments))
|
||||
} else {
|
||||
notify("Cleaned up \(count) file\(count == 1 ? "" : "s")", nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func unstagedStatus(_ path: String) -> GitStatus? {
|
||||
state.changes.first { !$0.staged && $0.path == path }?.status
|
||||
}
|
||||
|
||||
/// The confirm dialog a discard needs, or nil to run it straight away; restoring deleted files never asks.
|
||||
/// The confirm dialog a discard, clean up or merge needs, or nil to run it straight away; restoring deleted files never asks.
|
||||
/// A merge that `mergeBranch` refuses (dirty tree, current branch) asks nothing, so the refusal toast shows at once.
|
||||
public func confirmation(for action: ContextAction) -> ConfirmRequest? {
|
||||
guard case let .gitDiscard(paths) = action, config.confirmDiscard, !paths.isEmpty else { return nil }
|
||||
switch action {
|
||||
case let .gitDiscard(paths): discardConfirmation(paths, action: action)
|
||||
case let .mergeBranch(name): mergeConfirmation(name, action: action)
|
||||
case .gitCleanUp: cleanUpConfirmation()
|
||||
default: nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Always asks, whatever `confirmDiscard` says; nil only when `cleanUp` would refuse anyway.
|
||||
private func cleanUpConfirmation() -> ConfirmRequest? {
|
||||
guard canCleanUp else { return nil }
|
||||
let count = cleanUpPathCount
|
||||
return ConfirmRequest(
|
||||
title: "Clean up \(count) file\(count == 1 ? "" : "s")?",
|
||||
body: "New files are removed from disk and unstaged changes are reverted. Staged changes stay. This cannot be undone.",
|
||||
confirmLabel: "Clean up",
|
||||
action: .gitCleanUp
|
||||
)
|
||||
}
|
||||
|
||||
private func mergeConfirmation(_ name: String, action: ContextAction) -> ConfirmRequest? {
|
||||
let current = state.branch
|
||||
guard !isDirty, name != current else { return nil }
|
||||
return ConfirmRequest(
|
||||
title: "Merge \(name) into \(current)?",
|
||||
body: "Git merges the commits of \(name) into \(current). A conflict stops the merge for you to resolve.",
|
||||
confirmLabel: "Merge",
|
||||
action: action
|
||||
)
|
||||
}
|
||||
|
||||
private func discardConfirmation(_ paths: [String], action: ContextAction) -> ConfirmRequest? {
|
||||
guard config.confirmDiscard, !paths.isEmpty else { return nil }
|
||||
let statuses = paths.map(unstagedStatus)
|
||||
let hasNew = statuses.contains(.added)
|
||||
if statuses.allSatisfy({ $0 == .deleted }) { return nil }
|
||||
@@ -272,6 +388,18 @@ public final class SourceControlStore {
|
||||
if andPush { await push() }
|
||||
}
|
||||
|
||||
/// Stages every unstaged path, new files included, then commits without a push.
|
||||
/// An empty message stages nothing, so a refusal never leaves the files half done.
|
||||
public func stageAllAndCommit() async {
|
||||
guard canStageAllAndCommit else { return }
|
||||
guard !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty else {
|
||||
focusMessage()
|
||||
return
|
||||
}
|
||||
guard await stage(state.unstagedPaths) else { return }
|
||||
await commit()
|
||||
}
|
||||
|
||||
/// A branch without an upstream is pushed again with `-u origin <branch>`. Ignored while a push or pull runs.
|
||||
public func push() async {
|
||||
guard busy == nil else { return }
|
||||
@@ -337,6 +465,31 @@ public final class SourceControlStore {
|
||||
return true
|
||||
}
|
||||
|
||||
/// Runs `git merge --no-edit` into the current branch; refuses with a toast while the tree is dirty, without asking git.
|
||||
@discardableResult
|
||||
public func mergeBranch(_ name: String) async -> Bool {
|
||||
if isDirty {
|
||||
let count = changedPathCount
|
||||
notify("— Commit or discard \(count) file\(count == 1 ? "" : "s") before you merge.", nil)
|
||||
return false
|
||||
}
|
||||
let current = state.branch
|
||||
guard name != current else { return false }
|
||||
let arguments = ["merge", "--no-edit", name]
|
||||
let result = await run(arguments)
|
||||
await afterCommand()
|
||||
guard result.succeeded else {
|
||||
if state.changes.contains(where: { $0.status == .unmerged }) {
|
||||
notify("Merge conflict — resolve, then commit", nil)
|
||||
} else {
|
||||
notify("Merge failed", Self.failureDetail(of: result, arguments: arguments))
|
||||
}
|
||||
return false
|
||||
}
|
||||
notify("Merged \(name) into \(current)", nil)
|
||||
return true
|
||||
}
|
||||
|
||||
// MARK: Console
|
||||
|
||||
/// Runs what was typed; `clear` empties the log and a bare `log` reads as a short one-line log.
|
||||
@@ -404,6 +557,7 @@ public final class SourceControlStore {
|
||||
private func afterCommand() async {
|
||||
await refresh()
|
||||
await reloadBranches()
|
||||
await reloadRecentCommits()
|
||||
}
|
||||
|
||||
private func log(_ text: String, _ kind: GitLineKind) {
|
||||
|
||||
@@ -46,12 +46,18 @@ public final class TerminalStore {
|
||||
public private(set) var isConfigured = false
|
||||
public private(set) var agentExited = false
|
||||
public private(set) var shellExited = false
|
||||
public private(set) var tailExited = false
|
||||
/// The file the Explorer's tail block follows; nil while no block is shown.
|
||||
public private(set) var tailedPath: String?
|
||||
/// Moves on every new tail, so the block builds a fresh pane and the old file's output never stays.
|
||||
public private(set) var tailGeneration = 0
|
||||
/// True while the agent's composer holds typed or pasted text, so the next paste starts on a new line.
|
||||
public private(set) var agentComposerHasText = false
|
||||
|
||||
@ObservationIgnored public let projectRoot: String?
|
||||
@ObservationIgnored public private(set) var agent: TerminalSessionHandle?
|
||||
@ObservationIgnored public private(set) var shell: TerminalSessionHandle?
|
||||
@ObservationIgnored public private(set) var tail: TerminalSessionHandle?
|
||||
@ObservationIgnored private let environment: [String: String]
|
||||
/// A right-click in a pane: its kind, whether it holds a selection, the click in window coordinates.
|
||||
@ObservationIgnored public var contextMenuRequested: ((TerminalKind, Bool, CGPoint) -> Void)?
|
||||
@@ -63,7 +69,10 @@ public final class TerminalStore {
|
||||
|
||||
/// Executable, arguments, environment and cwd for a pane.
|
||||
public func launch(for kind: TerminalKind) -> TerminalLaunch {
|
||||
TerminalLaunch.make(kind: kind, config: config, projectRoot: projectRoot, environment: environment)
|
||||
guard kind == .tail else {
|
||||
return TerminalLaunch.make(kind: kind, config: config, projectRoot: projectRoot, environment: environment)
|
||||
}
|
||||
return TerminalLaunch.tail(path: tailedPath ?? "", projectRoot: projectRoot, environment: environment)
|
||||
}
|
||||
|
||||
/// argv[0] with a leading dash, which makes the shell a login shell: a Finder-launched app
|
||||
@@ -76,6 +85,7 @@ public final class TerminalStore {
|
||||
switch kind {
|
||||
case .agent: agent
|
||||
case .shell: shell
|
||||
case .tail: tail
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,15 +99,37 @@ public final class TerminalStore {
|
||||
case .shell:
|
||||
shell = handle
|
||||
if shellExited { shellExited = false }
|
||||
case .tail:
|
||||
tail = handle
|
||||
if tailExited { tailExited = false }
|
||||
}
|
||||
}
|
||||
|
||||
/// Attaches a pane and spawns its process.
|
||||
public func start(_ kind: TerminalKind, on handle: TerminalSessionHandle) {
|
||||
if kind == .tail && tailedPath == nil { return }
|
||||
attach(handle, as: kind)
|
||||
let launch = launch(for: kind)
|
||||
Log.info("pty", "spawn \(kind.rawValue): \(launch.executable) \(launch.arguments.joined(separator: " ")) in \(launch.workingDirectory)")
|
||||
handle.start(launch, argv0: Self.loginArgv0(for: launch.executable))
|
||||
let argv0 = kind == .tail ? (launch.executable as NSString).lastPathComponent : Self.loginArgv0(for: launch.executable)
|
||||
handle.start(launch, argv0: argv0)
|
||||
}
|
||||
|
||||
/// Shows the tail block on `path`; a running tail is killed first, and the block's new pane spawns the fresh one.
|
||||
public func startTail(_ path: String) {
|
||||
tail.map(Self.terminate)
|
||||
tail = nil
|
||||
tailExited = false
|
||||
tailedPath = path
|
||||
tailGeneration += 1
|
||||
}
|
||||
|
||||
/// Kills the tail and removes its block.
|
||||
public func closeTail() {
|
||||
tail.map(Self.terminate)
|
||||
tail = nil
|
||||
tailExited = false
|
||||
tailedPath = nil
|
||||
}
|
||||
|
||||
/// Kills whatever runs in the pane and spawns it again with the current config.
|
||||
@@ -112,6 +144,7 @@ public final class TerminalStore {
|
||||
switch kind {
|
||||
case .agent: agentExited = true
|
||||
case .shell: shellExited = true
|
||||
case .tail: tailExited = true
|
||||
}
|
||||
if let exitCode, exitCode != 0 {
|
||||
Log.warn("pty", "\(kind.rawValue) exited unexpectedly with code \(exitCode)")
|
||||
@@ -121,7 +154,11 @@ public final class TerminalStore {
|
||||
}
|
||||
|
||||
public func hasExited(_ kind: TerminalKind) -> Bool {
|
||||
kind == .agent ? agentExited : shellExited
|
||||
switch kind {
|
||||
case .agent: agentExited
|
||||
case .shell: shellExited
|
||||
case .tail: tailExited
|
||||
}
|
||||
}
|
||||
|
||||
/// Feed every keystroke the user sends to the agent: Enter empties the composer, printable text fills it.
|
||||
@@ -157,16 +194,19 @@ public final class TerminalStore {
|
||||
agent = nil
|
||||
} else if shell === handle {
|
||||
shell = nil
|
||||
} else if tail === handle {
|
||||
tail = nil
|
||||
} else {
|
||||
return
|
||||
}
|
||||
Self.terminate(handle)
|
||||
}
|
||||
|
||||
/// Kills both processes; call it before the window closes or the store is replaced.
|
||||
/// Kills every process, the tail included; call it before the window closes or the store is replaced.
|
||||
public func terminateAll() {
|
||||
agent.map(Self.terminate)
|
||||
shell.map(Self.terminate)
|
||||
closeTail()
|
||||
agent = nil
|
||||
shell = nil
|
||||
}
|
||||
|
||||
@@ -14,11 +14,14 @@ extension WorkspaceModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// A target without entries, such as the current branch, opens no menu.
|
||||
func showContextMenu(_ target: ContextTarget, anchor: CGPoint) {
|
||||
let entries = ContextActions.entries(for: target)
|
||||
guard !entries.isEmpty else { return }
|
||||
overlay.present(.contextMenu(ContextMenuRequest(
|
||||
target: target,
|
||||
header: ContextActions.header(for: target, projectName: name),
|
||||
entries: ContextActions.entries(for: target),
|
||||
entries: entries,
|
||||
anchor: anchor
|
||||
)))
|
||||
}
|
||||
@@ -78,8 +81,12 @@ extension WorkspaceModel {
|
||||
case let .openFile(path):
|
||||
closeGitView()
|
||||
open(path)
|
||||
case let .commit(andPush):
|
||||
track { await sourceControl?.commit(andPush: andPush) }
|
||||
case let .mergeBranch(name):
|
||||
guard let sourceControl else { return }
|
||||
track {
|
||||
await sourceControl.mergeBranch(name)
|
||||
self.scheduleRefresh([.tree, .openFiles])
|
||||
}
|
||||
case let .passOnFileName(name):
|
||||
overlay.present(.passOn(PassOnRequest(reference: name, anchor: anchor)))
|
||||
case let .bouwen(name):
|
||||
@@ -92,6 +99,8 @@ extension WorkspaceModel {
|
||||
readAloud.read(text)
|
||||
case let .readAloudFile(path):
|
||||
readAloudFile(path)
|
||||
case let .tailLog(path):
|
||||
terminal.startTail(path)
|
||||
case let .readAloudTerminalSelection(kind):
|
||||
let text = terminal.selection(kind)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||
let prose = MarkdownSpeech.plainText(MarkdownParser.parse(text))
|
||||
@@ -113,6 +122,12 @@ extension WorkspaceModel {
|
||||
if let text = terminal.selection(kind) { app.system.copy(text) }
|
||||
case let .pasteIntoTerminal(kind):
|
||||
if let text = app.system.pasteboardText() { terminal.paste(text, into: kind) }
|
||||
case .gitCleanUp:
|
||||
guard let sourceControl else { return }
|
||||
track {
|
||||
await sourceControl.cleanUp()
|
||||
self.scheduleRefresh([.tree, .openFiles])
|
||||
}
|
||||
case let .gitDiscard(paths):
|
||||
track {
|
||||
await sourceControl?.discard(paths)
|
||||
|
||||
@@ -52,7 +52,7 @@ extension WorkspaceModel {
|
||||
rowFrames = [:]
|
||||
let notify: (String, String?) -> Void = { [weak self] title, detail in self?.toasts.show(title, detail: detail) }
|
||||
|
||||
let sourceControl = SourceControlStore(git: services.git)
|
||||
let sourceControl = SourceControlStore(git: services.git, commitMessages: services.commitMessages)
|
||||
sourceControl.notify = notify
|
||||
sourceControl.focusMessage = { [weak self] in self?.focusRequest = FocusRequest(.commitMessage) }
|
||||
self.sourceControl = sourceControl
|
||||
|
||||
@@ -176,10 +176,20 @@ public final class WorkspaceModel {
|
||||
case .cycleMode: editor?.togglePreview()
|
||||
case let .passSelection(info): passSelection(info)
|
||||
case .selectAllInFile: editor?.selectAll()
|
||||
case .closeTail: terminal.closeTail()
|
||||
|
||||
case .commit:
|
||||
guard let sourceControl else { return }
|
||||
track { await sourceControl.commit() }
|
||||
case .commitAndPush:
|
||||
guard let sourceControl else { return }
|
||||
track { await sourceControl.commit(andPush: true) }
|
||||
case .stageAllAndCommit:
|
||||
guard let sourceControl else { return }
|
||||
track { await sourceControl.stageAllAndCommit() }
|
||||
case .generateCommitMessage:
|
||||
guard let sourceControl else { return }
|
||||
track { await sourceControl.generateCommitMessage() }
|
||||
case .push:
|
||||
guard let sourceControl else { return }
|
||||
track { await sourceControl.push() }
|
||||
|
||||
@@ -12,9 +12,12 @@ public struct WorkspaceServices {
|
||||
public var recentFiles: RecentFilesStoring
|
||||
/// The Schema view's dump reading and `helder:schema` runs.
|
||||
public var schema: SchemaServicing
|
||||
/// The Git view's Gen. Commit Message: the Claude CLI in print mode.
|
||||
public var commitMessages: CommitMessageGenerating
|
||||
|
||||
public init(git: GitServicing, files: FileServicing, search: SearchServicing, symbols: SymbolServicing,
|
||||
config: ConfigServicing, recentFiles: RecentFilesStoring, schema: SchemaServicing) {
|
||||
config: ConfigServicing, recentFiles: RecentFilesStoring, schema: SchemaServicing,
|
||||
commitMessages: CommitMessageGenerating) {
|
||||
self.git = git
|
||||
self.files = files
|
||||
self.search = search
|
||||
@@ -22,6 +25,7 @@ public struct WorkspaceServices {
|
||||
self.config = config
|
||||
self.recentFiles = recentFiles
|
||||
self.schema = schema
|
||||
self.commitMessages = commitMessages
|
||||
}
|
||||
|
||||
public static func live(root: URL) -> WorkspaceServices {
|
||||
@@ -34,7 +38,8 @@ public struct WorkspaceServices {
|
||||
symbols: SymbolService(root: root, config: config),
|
||||
config: config,
|
||||
recentFiles: RecentFilesStore(root: root),
|
||||
schema: SchemaService(root: root)
|
||||
schema: SchemaService(root: root),
|
||||
commitMessages: ClaudeCommitMessageService(root: root)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,4 +51,14 @@ import Testing
|
||||
#expect(launch.workingDirectory == "/p")
|
||||
#expect(TerminalLaunch.make(kind: .shell, config: .defaults, projectRoot: nil, environment: [:]).arguments.isEmpty)
|
||||
}
|
||||
|
||||
@Test func theTailRunsTailDirectlyOnTheProjectRelativePathInTheProject() {
|
||||
let launch = TerminalLaunch.tail(path: "storage/logs/laravel.log", projectRoot: "/p",
|
||||
environment: ["SHELL": "/bin/zsh", "TERM_PROGRAM": "Apple_Terminal"])
|
||||
#expect(launch.executable == "/usr/bin/tail")
|
||||
#expect(launch.arguments == ["-f", "storage/logs/laravel.log"])
|
||||
#expect(launch.workingDirectory == "/p")
|
||||
#expect(launch.environment["TERM_PROGRAM"] == "Helder")
|
||||
#expect(TerminalLaunch.tail(path: "a.log", projectRoot: nil, environment: ["HOME": "/Users/me"]).workingDirectory == "/Users/me")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +42,11 @@ import Testing
|
||||
#expect(!labels(.terminal(.shell, hasSelection: false)).contains("Read aloud selection"))
|
||||
}
|
||||
|
||||
@Test func theTailPaneOffersCopyButNoPasteOrWaitWhat() {
|
||||
#expect(labels(.terminal(.tail, hasSelection: true)) == ["Copy", "Read aloud selection", "Plak"])
|
||||
#expect(ContextActions.entries(for: .terminal(.tail, hasSelection: false)).isEmpty)
|
||||
}
|
||||
|
||||
@Test func theMenuHasNoHeader() {
|
||||
#expect(ContextActions.header(for: .terminal(.agent, hasSelection: false), projectName: "app").isEmpty)
|
||||
#expect(ContextActions.header(for: .directory(path: "src"), projectName: "app").isEmpty)
|
||||
@@ -143,16 +148,6 @@ import Testing
|
||||
#expect(ContextAction.openFile("src/a.php").isEmphasized)
|
||||
}
|
||||
|
||||
@Test func theCommitMenuOffersCommitAndABoldCommitAndPush() {
|
||||
#expect(ContextActions.header(for: .commitMenu, projectName: "app") == "")
|
||||
#expect(ContextActions.entries(for: .commitMenu) == [
|
||||
.action(.commit(andPush: false), label: "Commit"),
|
||||
.action(.commit(andPush: true), label: "Commit and push"),
|
||||
])
|
||||
#expect(ContextAction.commit(andPush: true).isEmphasized)
|
||||
#expect(!ContextAction.commit(andPush: false).isEmphasized)
|
||||
}
|
||||
|
||||
@Test func aSelectionCanBeReadAloudAfterCopyReference() {
|
||||
let reference = AgentReference(path: "src/a.php", startLine: 3, endLine: 4)
|
||||
#expect(ContextActions.entries(for: .editor(reference: reference, code: "$a = 1;", showDiffLine: 3)) == [
|
||||
@@ -204,3 +199,59 @@ import Testing
|
||||
#expect(plak(.editor(reference: reference, code: "")).isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct BranchContextMenuTests {
|
||||
@Test func aCleanTreeOffersTheMergeIntoTheCurrentBranch() {
|
||||
#expect(ContextActions.entries(for: .branch(name: "feature", remote: false, current: "dev", isDirty: false)) == [
|
||||
.action(.mergeBranch("feature"), label: "Merge into dev"),
|
||||
])
|
||||
#expect(ContextActions.entries(for: .branch(name: "origin/feature", remote: true, current: "dev", isDirty: false)) == [
|
||||
.action(.mergeBranch("origin/feature"), label: "Merge into dev"),
|
||||
])
|
||||
}
|
||||
|
||||
@Test func aDirtyTreeShowsTheMergeDisabled() {
|
||||
let entries = ContextActions.entries(for: .branch(name: "feature", remote: false, current: "dev", isDirty: true))
|
||||
#expect(entries == [
|
||||
.disabled(.mergeBranch("feature"), label: "Merge into dev", hint: "Commit or discard your changes first"),
|
||||
])
|
||||
#expect(!entries[0].isSelectable)
|
||||
}
|
||||
|
||||
@Test func theCurrentBranchHasNoMenuButItsUpstreamHas() {
|
||||
#expect(ContextActions.entries(for: .branch(name: "dev", remote: false, current: "dev", isDirty: false)).isEmpty)
|
||||
#expect(ContextActions.entries(for: .branch(name: "origin/dev", remote: true, current: "dev", isDirty: false)).count == 1)
|
||||
}
|
||||
|
||||
@Test func theHeaderIsTheBranchName() {
|
||||
#expect(ContextActions.header(for: .branch(name: "origin/feature", remote: true, current: "dev", isDirty: false),
|
||||
projectName: "app") == "origin/feature")
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct TailLogContextMenuTests {
|
||||
private func hasTailLog(_ target: ContextTarget) -> Bool {
|
||||
ContextActions.entries(for: target).contains { entry in
|
||||
guard case .action(.tailLog, _) = entry else { return false }
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@Test func aLogFileOffersTailLogInItsOwnGroupAfterTheCopyItems() {
|
||||
let entries = ContextActions.entries(for: .file(path: "storage/logs/laravel.log"))
|
||||
#expect(Array(entries[4...6]) == [
|
||||
.separator,
|
||||
.action(.tailLog("storage/logs/laravel.log"), label: "Tail log"),
|
||||
.separator,
|
||||
])
|
||||
#expect(hasTailLog(.file(path: "LOGS/Error.LOG")))
|
||||
}
|
||||
|
||||
@Test func otherFilesAndFoldersDoNot() {
|
||||
#expect(!hasTailLog(.file(path: "src/app.php")))
|
||||
#expect(!hasTailLog(.file(path: "notes.md")))
|
||||
#expect(!hasTailLog(.file(path: "catalog")))
|
||||
#expect(!hasTailLog(.directory(path: "storage/logs.log")))
|
||||
#expect(!hasTailLog(.gitRow(path: "laravel.log", isDeleted: false)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct CommitMessagePromptTests {
|
||||
private let diff = StagedDiff(stat: " src/a.php | 2 +-\n 1 file changed\n", patch: "diff --git a/src/a.php b/src/a.php\n-old\n+new\n")
|
||||
|
||||
@Test("the prompt holds the rules, the three examples verbatim, the stat and the diff")
|
||||
func promptContents() {
|
||||
let prompt = CommitMessagePrompt.make(diff)
|
||||
#expect(prompt.contains("Write ONE git commit message"))
|
||||
#expect(prompt.contains("\" - \""))
|
||||
#expect(prompt.contains("Adds a new button on the header to navigate to profile"))
|
||||
#expect(prompt.contains("Fixed security issue that made it possible to hack a file upload"))
|
||||
#expect(prompt.contains("Makes sure the register form does not accept R&B fans - Enforces password rules on login form (two things changed)"))
|
||||
#expect(prompt.contains(" src/a.php | 2 +-\n 1 file changed"))
|
||||
#expect(prompt.hasSuffix("+new"))
|
||||
#expect(!prompt.contains("is cut"))
|
||||
}
|
||||
|
||||
@Test("a long diff is cut at the limit and the prompt says so; the stat stays whole")
|
||||
func cutDiff() {
|
||||
let stat = (0..<50).map { " file\($0).txt | 1 +" }.joined(separator: "\n")
|
||||
let long = StagedDiff(stat: stat, patch: String(repeating: "a", count: 90) + "TAIL")
|
||||
let prompt = CommitMessagePrompt.make(long, limit: 90)
|
||||
#expect(prompt.contains("cut after 90 characters"))
|
||||
#expect(prompt.contains(stat))
|
||||
#expect(prompt.contains(String(repeating: "a", count: 90)))
|
||||
#expect(!prompt.contains("TAIL"))
|
||||
}
|
||||
|
||||
@Test("a diff exactly at the limit is not cut")
|
||||
func diffAtLimit() {
|
||||
let prompt = CommitMessagePrompt.make(StagedDiff(stat: "s", patch: String(repeating: "b", count: 10)), limit: 10)
|
||||
#expect(!prompt.contains("is cut"))
|
||||
}
|
||||
|
||||
@Test("cleaning takes the first non-empty line and trims it")
|
||||
func firstLine() {
|
||||
#expect(CommitMessagePrompt.clean("\n\n Adds a button \nSecond line\n") == "Adds a button")
|
||||
}
|
||||
|
||||
@Test("cleaning strips surrounding quotes and backticks, nested too")
|
||||
func wrappers() {
|
||||
#expect(CommitMessagePrompt.clean("\"Fixed the parser\"") == "Fixed the parser")
|
||||
#expect(CommitMessagePrompt.clean("`'Fixed the parser'`") == "Fixed the parser")
|
||||
#expect(CommitMessagePrompt.clean("“Fixed the parser”") == "Fixed the parser")
|
||||
#expect(CommitMessagePrompt.clean("Fixed the \"parser\" bug") == "Fixed the \"parser\" bug")
|
||||
}
|
||||
|
||||
@Test("cleaning skips Markdown fence lines")
|
||||
func fences() {
|
||||
#expect(CommitMessagePrompt.clean("```text\nAdds a button\n```") == "Adds a button")
|
||||
}
|
||||
|
||||
@Test("cleaning collapses runs of whitespace")
|
||||
func whitespace() {
|
||||
#expect(CommitMessagePrompt.clean("Adds\ta button") == "Adds a button")
|
||||
}
|
||||
|
||||
@Test("nothing usable cleans to nil")
|
||||
func empty() {
|
||||
#expect(CommitMessagePrompt.clean("") == nil)
|
||||
#expect(CommitMessagePrompt.clean(" \n\t\n") == nil)
|
||||
#expect(CommitMessagePrompt.clean("\"\"") == nil)
|
||||
}
|
||||
|
||||
@Test("an empty patch is an empty diff")
|
||||
func isEmpty() {
|
||||
#expect(StagedDiff(stat: "", patch: " \n").isEmpty)
|
||||
#expect(!diff.isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct GitCommitLogTests {
|
||||
@Test("each record splits into hash, subject, author and date, newest first")
|
||||
func commits() {
|
||||
let raw = "a1b2c3d\0fix the parser\0Jonathan van Rij\01767225600\u{1e}\n0123abc\0first\0Zoë\01700000000\u{1e}\n"
|
||||
#expect(GitCommitLogParsing.commits(raw) == [
|
||||
GitCommitSummary(hash: "a1b2c3d", subject: "fix the parser", author: "Jonathan van Rij",
|
||||
date: Date(timeIntervalSince1970: 1_767_225_600)),
|
||||
GitCommitSummary(hash: "0123abc", subject: "first", author: "Zoë", date: Date(timeIntervalSince1970: 1_700_000_000)),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("a subject with quotes, tabs, unicode and separators stays whole")
|
||||
func oddSubject() throws {
|
||||
let subject = "feat: \"quotes\" · tab\there | pipe %s %x00 — émoji 🚀"
|
||||
let commit = try #require(GitCommitLogParsing.commits("0123abc\0\(subject)\0Zoë\01700000000\u{1e}\n").first)
|
||||
#expect(commit.subject == subject)
|
||||
#expect(commit.author == "Zoë")
|
||||
}
|
||||
|
||||
@Test("an empty subject still parses")
|
||||
func emptySubject() {
|
||||
#expect(GitCommitLogParsing.commits("0123abc\0\0Zoë\01700000000\u{1e}\n").first?.subject == "")
|
||||
}
|
||||
|
||||
@Test("a malformed record is skipped, the rest stays")
|
||||
func malformedRecord() {
|
||||
let raw = "abc\0subject\0author\0soon\u{1e}\n0123abc\0ok\0Zoë\01700000000\u{1e}\n"
|
||||
#expect(GitCommitLogParsing.commits(raw).map(\.hash) == ["0123abc"])
|
||||
}
|
||||
|
||||
@Test("an empty repository prints nothing, which is no commits", arguments: ["", "\n", "garbage", "\u{1e}\n"])
|
||||
func noCommits(raw: String) {
|
||||
#expect(GitCommitLogParsing.commits(raw).isEmpty)
|
||||
}
|
||||
|
||||
@Test("relative time steps from seconds to years", arguments: [
|
||||
(0, "just now"),
|
||||
(59, "just now"),
|
||||
(60, "1 min ago"),
|
||||
(3_540, "59 min ago"),
|
||||
(10_800, "3 h ago"),
|
||||
(86_400, "1 d ago"),
|
||||
(518_400, "6 d ago"),
|
||||
(1_209_600, "2 w ago"),
|
||||
(5_184_000, "2 mo ago"),
|
||||
(69_120_000, "2 y ago"),
|
||||
(-120, "just now"),
|
||||
] as [(TimeInterval, String)])
|
||||
func relativeTime(age: TimeInterval, text: String) {
|
||||
let now = Date(timeIntervalSince1970: 1_800_000_000)
|
||||
#expect(RelativeTime.text(now.addingTimeInterval(-age), now: now) == text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Testing
|
||||
|
||||
@Suite struct CommitMessageServiceTests {
|
||||
/// A project folder plus a `bin` folder holding a fake `claude` with the given shell body.
|
||||
private func setup(claude body: String?) throws -> (dir: TempDirectory, bin: URL) {
|
||||
let dir = try TempDirectory()
|
||||
try dir.mkdir("project")
|
||||
try dir.mkdir("bin")
|
||||
if let body {
|
||||
try dir.write("bin/claude", "#!/bin/sh\n" + body + "\n")
|
||||
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.url("bin/claude").path)
|
||||
}
|
||||
return (dir, dir.url("bin"))
|
||||
}
|
||||
|
||||
private func service(_ dir: TempDirectory, bin: URL, timeout: TimeInterval = 20) -> ClaudeCommitMessageService {
|
||||
ClaudeCommitMessageService(root: dir.url("project"), locator: ExecutableLocator(directories: [bin.path]), timeout: timeout)
|
||||
}
|
||||
|
||||
@Test func sendsThePromptOnStdinInTheProjectAndCleansTheAnswer() async throws {
|
||||
let (dir, bin) = try setup(claude: """
|
||||
cat > "$(dirname "$0")/stdin.txt"
|
||||
pwd > "$(dirname "$0")/cwd.txt"
|
||||
printf '%s\\n' "$@" > "$(dirname "$0")/args.txt"
|
||||
printf '\\n "Adds a thing" \\n\\nextra line\\n'
|
||||
""")
|
||||
let message = try await service(dir, bin: bin).generate(prompt: "the prompt\nwith two lines")
|
||||
#expect(message == "Adds a thing")
|
||||
#expect(try String(contentsOf: dir.url("bin/stdin.txt"), encoding: .utf8) == "the prompt\nwith two lines")
|
||||
// The child reports /private/var/…; resolving both sides drops the /private prefix alike.
|
||||
let cwd = try String(contentsOf: dir.url("bin/cwd.txt"), encoding: .utf8).trimmingCharacters(in: .newlines)
|
||||
#expect(URL(fileURLWithPath: cwd).resolvingSymlinksInPath().path == dir.url("project").resolvingSymlinksInPath().path)
|
||||
let args = try String(contentsOf: dir.url("bin/args.txt"), encoding: .utf8)
|
||||
#expect(args == ClaudeCommitMessageService.arguments.map { $0 + "\n" }.joined())
|
||||
}
|
||||
|
||||
@Test func theRunnerGetsThePromptAsInputAndClaudesFolderFirstOnPath() async throws {
|
||||
let (dir, bin) = try setup(claude: "exit 0")
|
||||
let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "`Fixed the parser`\n", stderr: "") }
|
||||
let service = ClaudeCommitMessageService(root: dir.url("project"), runner: runner,
|
||||
locator: ExecutableLocator(directories: [bin.path]))
|
||||
#expect(try await service.generate(prompt: "write it") == "Fixed the parser")
|
||||
let call = try #require(runner.calls.first)
|
||||
#expect(call.executable == bin.appendingPathComponent("claude").path)
|
||||
#expect(call.arguments == ClaudeCommitMessageService.arguments)
|
||||
#expect(call.input == "write it")
|
||||
#expect(call.directory == dir.url("project"))
|
||||
#expect(call.environment?["PATH"]?.hasPrefix(bin.path + ":") == true)
|
||||
}
|
||||
|
||||
@Test func theArgumentsDisableToolsAndUseTheDefaultModel() {
|
||||
let args = ClaudeCommitMessageService.arguments
|
||||
#expect(args.first == "-p")
|
||||
#expect(args.suffix(2) == ["--tools", ""])
|
||||
#expect(!args.contains("--model"))
|
||||
}
|
||||
|
||||
@Test func aFailedRunReportsItsFirstStderrLinePastWarnings() async throws {
|
||||
let (dir, bin) = try setup(claude: """
|
||||
echo "Warning: this sign-in ends soon" >&2
|
||||
echo "Invalid API key" >&2
|
||||
echo "second" >&2
|
||||
exit 1
|
||||
""")
|
||||
await #expect(throws: CommitMessageError.failed("Invalid API key")) {
|
||||
try await service(dir, bin: bin).generate(prompt: "p")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func aSilentFailureReportsTheExitCode() async throws {
|
||||
let (dir, bin) = try setup(claude: "exit 3")
|
||||
await #expect(throws: CommitMessageError.failed("claude exited with code 3")) {
|
||||
try await service(dir, bin: bin).generate(prompt: "p")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func anEmptyAnswerIsAnError() async throws {
|
||||
let (dir, bin) = try setup(claude: "cat > /dev/null; printf '\\n \\n'")
|
||||
await #expect(throws: CommitMessageError.empty) {
|
||||
try await service(dir, bin: bin).generate(prompt: "p")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func aMissingClaudeIsNotFound() async throws {
|
||||
let (dir, bin) = try setup(claude: nil)
|
||||
await #expect(throws: CommitMessageError.notFound) {
|
||||
try await service(dir, bin: bin).generate(prompt: "p")
|
||||
}
|
||||
#expect(CommitMessageError.notFound.detail == "claude not found")
|
||||
}
|
||||
|
||||
@Test func aSlowRunTimesOut() async throws {
|
||||
let (dir, bin) = try setup(claude: "exec sleep 10")
|
||||
let started = Date()
|
||||
await #expect(throws: CommitMessageError.timedOut) {
|
||||
try await service(dir, bin: bin, timeout: 0.3).generate(prompt: "p")
|
||||
}
|
||||
#expect(Date().timeIntervalSince(started) < 5)
|
||||
#expect(CommitMessageError.timedOut.detail == "timed out")
|
||||
}
|
||||
|
||||
@Test func theAgentLocatorAddsTheClaudeInstallFolders() {
|
||||
let home = FileManager.default.homeDirectoryForCurrentUser.path
|
||||
let agent = ExecutableLocator.agent.directories
|
||||
#expect(agent.contains("\(home)/.local/bin"))
|
||||
#expect(agent.contains("\(home)/.claude/local"))
|
||||
#expect(Array(agent.prefix(ExecutableLocator.standard.directories.count)) == ExecutableLocator.standard.directories)
|
||||
}
|
||||
}
|
||||
@@ -207,6 +207,34 @@ import Testing
|
||||
let service = GitService(root: worktree)
|
||||
#expect(await service.isRepository())
|
||||
}
|
||||
|
||||
@Test func recentCommitsReadHeadNewestFirst() async throws {
|
||||
let repo = try repo()
|
||||
let before = await GitService(root: repo.root).recentCommits().count
|
||||
try repo.commit(["c.txt": "c\n"], message: "add \"c\" | 100% done")
|
||||
let commits = await GitService(root: repo.root).recentCommits()
|
||||
#expect(commits.count == before + 1)
|
||||
let commit = try #require(commits.first)
|
||||
#expect(commit.subject == "add \"c\" | 100% done")
|
||||
#expect(commit.author == "Helder Tests")
|
||||
#expect(!commit.hash.isEmpty)
|
||||
#expect(abs(commit.date.timeIntervalSinceNow) < 600)
|
||||
}
|
||||
|
||||
@Test func recentCommitsStopAtThirty() async throws {
|
||||
let repo = try repo()
|
||||
for index in 0..<32 {
|
||||
try repo.commit(["n.txt": "\(index)\n"], message: "commit \(index)")
|
||||
}
|
||||
let commits = await GitService(root: repo.root).recentCommits()
|
||||
#expect(commits.count == GitCommitLogParsing.limit)
|
||||
#expect(commits.first?.subject == "commit 31")
|
||||
}
|
||||
|
||||
@Test func aRepositoryWithoutCommitsHasNoRecentCommits() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
#expect(await GitService(root: repo.root).recentCommits().isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
/// Names git would read as globs or options unless every pathspec is literal.
|
||||
@@ -232,3 +260,30 @@ import Testing
|
||||
#expect(runner.calls.allSatisfy { $0.environment?["GIT_LITERAL_PATHSPECS"] == "1" })
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct GitServiceStagedDiffTests {
|
||||
@Test func stagedDiffHoldsOnlyTheStagedChanges() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit(["a.txt": "1\n", "b.txt": "1\n"], message: "init")
|
||||
try repo.write("a.txt", "1\nstaged\n")
|
||||
try repo.run("add", "a.txt")
|
||||
try repo.write("b.txt", "1\nunstaged\n")
|
||||
let diff = try #require(await GitService(root: repo.root).stagedDiff())
|
||||
#expect(diff.stat.contains("a.txt"))
|
||||
#expect(!diff.stat.contains("b.txt"))
|
||||
#expect(diff.patch.contains("+staged"))
|
||||
#expect(!diff.patch.contains("unstaged"))
|
||||
}
|
||||
|
||||
@Test func nothingStagedIsAnEmptyDiff() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit(["a.txt": "1\n"], message: "init")
|
||||
let diff = try #require(await GitService(root: repo.root).stagedDiff())
|
||||
#expect(diff.isEmpty)
|
||||
}
|
||||
|
||||
@Test func outsideARepositoryThereIsNoDiff() async throws {
|
||||
let dir = try TempDirectory()
|
||||
#expect(await GitService(root: dir.root).stagedDiff() == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,30 @@ import Testing
|
||||
#expect(result == ProcessResult(exitCode: 0, stdout: "", stderr: ""))
|
||||
}
|
||||
|
||||
@Test func inputReachesStdinAndThenEnds() async throws {
|
||||
let result = try await runner.run("cat", arguments: [], in: nil, environment: nil, input: "héllo\nworld")
|
||||
#expect(result == ProcessResult(exitCode: 0, stdout: "héllo\nworld", stderr: ""))
|
||||
}
|
||||
|
||||
@Test func largeInputIsWrittenWhole() async throws {
|
||||
let input = String(repeating: "x", count: 1_000_000)
|
||||
let result = try await runner.run("wc", arguments: ["-c"], in: nil, environment: nil, input: input)
|
||||
#expect(result.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == "1000000")
|
||||
}
|
||||
|
||||
@Test func aChildThatIgnoresItsInputStillFinishes() async throws {
|
||||
let input = String(repeating: "x", count: 1_000_000)
|
||||
let result = try await runner.run("true", arguments: [], in: nil, environment: nil, input: input)
|
||||
#expect(result.exitCode == 0)
|
||||
}
|
||||
|
||||
@Test func aRunnerWithoutStdinSupportRefusesInput() async throws {
|
||||
let fake = CannedRunner(result: ProcessResult(exitCode: 0, stdout: "", stderr: ""))
|
||||
await #expect(throws: ProcessRunnerError.self) {
|
||||
try await fake.run("x", arguments: [], in: nil, environment: nil, input: "prompt")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func largeOutputOnBothPipesDoesNotDeadlock() async throws {
|
||||
let script = "i=0; while [ $i -lt 20000 ]; do echo line$i; echo err$i >&2; i=$((i+1)); done"
|
||||
let result = try await runner.run("sh", ["-c", script])
|
||||
|
||||
@@ -22,6 +22,8 @@ struct RecordedCall: Sendable, Equatable {
|
||||
var executable: String
|
||||
var arguments: [String]
|
||||
var environment: [String: String]?
|
||||
var directory: URL? = nil
|
||||
var input: String? = nil
|
||||
}
|
||||
|
||||
/// Records every call and answers from a script; for tests of argument construction and error paths.
|
||||
@@ -39,7 +41,14 @@ final class ScriptedRunner: ProcessRunning, @unchecked Sendable {
|
||||
}
|
||||
|
||||
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
|
||||
let call = RecordedCall(executable: executable, arguments: arguments, environment: environment)
|
||||
let call = RecordedCall(executable: executable, arguments: arguments, environment: environment, directory: directory)
|
||||
lock.withLock { recorded.append(call) }
|
||||
return try await respond(call)
|
||||
}
|
||||
|
||||
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||
input: String) async throws -> ProcessResult {
|
||||
let call = RecordedCall(executable: executable, arguments: arguments, environment: environment, directory: directory, input: input)
|
||||
lock.withLock { recorded.append(call) }
|
||||
return try await respond(call)
|
||||
}
|
||||
|
||||
@@ -22,9 +22,8 @@ import Testing
|
||||
#expect(ContextMenuOverlay.tint(for: .rename("a.php", isDirectory: false)) == .rename)
|
||||
}
|
||||
|
||||
@Test func theGitViewItemsKeepThePlainIcon() {
|
||||
@Test func theGitViewRowItemKeepsThePlainIcon() {
|
||||
#expect(ContextMenuOverlay.tint(for: .openFile("a.php")) == .plain)
|
||||
#expect(ContextMenuOverlay.tint(for: .commit(andPush: true)) == .plain)
|
||||
}
|
||||
|
||||
@Test func copyReferenceKeepsThePlainIconThatTurnsAmberOnHighlight() {
|
||||
@@ -34,6 +33,8 @@ import Testing
|
||||
|
||||
@Test func destructiveActionsAreAmberDeep() {
|
||||
#expect(ContextMenuOverlay.tint(for: .gitDiscard(["a.php"])) == .danger)
|
||||
#expect(ContextMenuOverlay.tint(for: .gitCleanUp) == .danger)
|
||||
#expect(ContextAction.gitCleanUp.isDestructive)
|
||||
#expect(ContextMenuOverlay.tint(for: .delete("a", isDirectory: true)) == .danger)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +70,24 @@ import Testing
|
||||
#expect(MenuCursor.step(3, by: 1, in: entries) == 0)
|
||||
#expect(MenuCursor.step(0, by: -1, in: entries) == 3)
|
||||
}
|
||||
|
||||
@Test func arrowsSkipDisabledEntries() {
|
||||
let entries: [ContextMenuEntry] = [
|
||||
.action(.copyReference("a"), label: "Copy reference"),
|
||||
.disabled(.mergeBranch("b"), label: "Merge into main", hint: "Commit or discard your changes first"),
|
||||
.action(.delete("a", isDirectory: false), label: "Delete file"),
|
||||
]
|
||||
#expect(MenuCursor.step(0, by: 1, in: entries) == 2)
|
||||
#expect(MenuCursor.step(2, by: -1, in: entries) == 0)
|
||||
}
|
||||
|
||||
@Test func aMenuWithOnlyADisabledEntryHighlightsNothing() {
|
||||
let entries: [ContextMenuEntry] = [
|
||||
.disabled(.mergeBranch("b"), label: "Merge into main", hint: "Commit or discard your changes first"),
|
||||
]
|
||||
#expect(MenuCursor.first(in: entries) == nil)
|
||||
#expect(MenuCursor.step(-1, by: 1, in: entries) == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct NamePromptTextTests {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import CoreGraphics
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@Suite struct GitStripLayoutTests {
|
||||
@Test func aNarrowStripSplitsEvenlyWithoutTheCommitList() {
|
||||
let layout = GitStripLayout(width: 1201)
|
||||
#expect(layout.console == 600)
|
||||
#expect(layout.branches == 600)
|
||||
#expect(layout.commits == nil)
|
||||
}
|
||||
|
||||
@Test func bothPanelsStopAt820AndASmallRestStaysEmpty() {
|
||||
let layout = GitStripLayout(width: 1800)
|
||||
#expect(layout.console == GitMetrics.consoleMaxWidth)
|
||||
#expect(layout.branches == GitMetrics.branchesMaxWidth)
|
||||
#expect(layout.commits == nil)
|
||||
}
|
||||
|
||||
@Test func theCommitListTakesTheRestFrom260() {
|
||||
let edge = GitMetrics.consoleMaxWidth + GitMetrics.branchesMaxWidth + 2 + GitMetrics.commitsMinWidth
|
||||
#expect(GitStripLayout(width: edge - 1).commits == nil)
|
||||
#expect(GitStripLayout(width: edge).commits == GitMetrics.commitsMinWidth)
|
||||
#expect(GitStripLayout(width: 2560).commits == CGFloat(2560 - 1640 - 2))
|
||||
}
|
||||
}
|
||||
@@ -274,6 +274,73 @@ import Testing
|
||||
#expect(texts(store) == ["$ git restore -- src/b.php src/c.php", "$ git clean -f -- new.txt", "Removing new.txt"])
|
||||
}
|
||||
|
||||
// MARK: Clean up
|
||||
|
||||
@Test func cleanUpRevertsTheWorkingTreeAndRemovesNewFiles() async {
|
||||
let (store, git, recorder) = await makeStore()
|
||||
#expect(store.cleanUpPathCount == 5)
|
||||
#expect(store.canCleanUp)
|
||||
await store.cleanUp()
|
||||
#expect(git.executed == [["restore", "--worktree", "--", "."], ["clean", "-fd"]])
|
||||
#expect(recorder.toastTitles == ["Cleaned up 5 files"])
|
||||
}
|
||||
|
||||
@Test func cleanUpRunsOnlyWhatTheTreeNeeds() async {
|
||||
let (onlyNew, newGit, _) = await makeStore(snapshot([("new.txt", .added, false), ("a.php", .modified, true)]))
|
||||
await onlyNew.cleanUp()
|
||||
#expect(newGit.executed == [["clean", "-fd"]])
|
||||
|
||||
let (onlyTracked, trackedGit, recorder) = await makeStore(snapshot([("a.php", .modified, false)]))
|
||||
await onlyTracked.cleanUp()
|
||||
#expect(trackedGit.executed == [["restore", "--worktree", "--", "."]])
|
||||
#expect(recorder.toastTitles == ["Cleaned up 1 file"])
|
||||
}
|
||||
|
||||
@Test func cleanUpDoesNothingWhenOnlyStagedChangesAreLeft() async {
|
||||
let (store, git, recorder) = await makeStore(snapshot([("a.php", .modified, true), ("b.php", .added, true)]))
|
||||
#expect(!store.canCleanUp)
|
||||
#expect(store.confirmation(for: .gitCleanUp) == nil)
|
||||
await store.cleanUp()
|
||||
#expect(git.executed.isEmpty)
|
||||
#expect(recorder.toastTitles.isEmpty)
|
||||
}
|
||||
|
||||
@Test func cleanUpIsRefusedDuringAConflict() async {
|
||||
let (store, git, _) = await makeStore(snapshot([("both.txt", .unmerged, false), ("src/b.php", .modified, false)]))
|
||||
#expect(!store.canCleanUp)
|
||||
await store.cleanUp()
|
||||
#expect(git.executed.isEmpty)
|
||||
}
|
||||
|
||||
@Test func cleanUpIsRefusedWhileAPushRuns() async {
|
||||
let (store, git, _) = await makeStore()
|
||||
git.setRun(FakeGitRun(delay: .milliseconds(300)), forCommand: "push")
|
||||
let push = Task { await store.push() }
|
||||
#expect(await eventually { store.busy == .push })
|
||||
#expect(!store.canCleanUp)
|
||||
await store.cleanUp()
|
||||
await push.value
|
||||
#expect(git.executed == [["push"]])
|
||||
}
|
||||
|
||||
@Test func aFailedCleanUpToastsGitsError() async {
|
||||
let (store, git, recorder) = await makeStore(snapshot([("new.txt", .added, false)]))
|
||||
git.setRun(FakeGitRun(exitCode: 1, lines: [("warning: failed to remove new.txt: Permission denied", true)]), forCommand: "clean")
|
||||
await store.cleanUp()
|
||||
#expect(recorder.toastTitles == ["Clean up failed"])
|
||||
#expect(recorder.toasts.first?.1 == "warning: failed to remove new.txt: Permission denied")
|
||||
}
|
||||
|
||||
@Test func cleanUpAlwaysAsksWithTheCount() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
store.config.confirmDiscard = false
|
||||
let request = store.confirmation(for: .gitCleanUp)
|
||||
#expect(request?.title == "Clean up 5 files?")
|
||||
#expect(request?.body == "New files are removed from disk and unstaged changes are reverted. Staged changes stay. This cannot be undone.")
|
||||
#expect(request?.confirmLabel == "Clean up")
|
||||
#expect(request?.action == .gitCleanUp)
|
||||
}
|
||||
|
||||
// MARK: Commit
|
||||
|
||||
@Test func commitAlwaysRunsGitEvenWithNothingStagedOrNoMessage() async {
|
||||
@@ -350,6 +417,54 @@ import Testing
|
||||
#expect(failingGit.executed == [["commit", "-m", "ship it"]])
|
||||
}
|
||||
|
||||
@Test func stageAllAndCommitStagesEveryUnstagedPathThenCommits() async {
|
||||
let (store, git, recorder) = await makeStore()
|
||||
#expect(store.canStageAllAndCommit)
|
||||
store.setCommitMessage("ship it")
|
||||
await store.stageAllAndCommit()
|
||||
#expect(git.executed == [
|
||||
["add", "--", "src/b.php", "README.md", "src/a.php", "src/c.php", "new.txt"],
|
||||
["commit", "-m", "ship it"],
|
||||
])
|
||||
#expect(store.commitMessage.isEmpty)
|
||||
#expect(recorder.toastTitles.first?.hasPrefix("Committed") == true)
|
||||
}
|
||||
|
||||
@Test func stageAllAndCommitWithoutAMessageRunsNothingAndFocusesTheMessage() async {
|
||||
let (store, git, recorder) = await makeStore()
|
||||
var focused = 0
|
||||
store.focusMessage = { focused += 1 }
|
||||
store.setCommitMessage(" ")
|
||||
await store.stageAllAndCommit()
|
||||
#expect(git.executed.isEmpty)
|
||||
#expect(focused == 1)
|
||||
#expect(recorder.toastTitles.isEmpty)
|
||||
}
|
||||
|
||||
@Test func stageAllAndCommitIsRefusedDuringAConflict() async {
|
||||
let (store, git, _) = await makeStore(snapshot([("both.txt", .unmerged, false), ("src/b.php", .modified, false)]))
|
||||
#expect(!store.canStageAllAndCommit)
|
||||
store.setCommitMessage("ship it")
|
||||
await store.stageAllAndCommit()
|
||||
#expect(git.executed.isEmpty)
|
||||
}
|
||||
|
||||
@Test func stageAllAndCommitIsOffWithoutChanges() async {
|
||||
let (store, git, _) = await makeStore(snapshot([]))
|
||||
#expect(!store.canStageAllAndCommit)
|
||||
store.setCommitMessage("ship it")
|
||||
await store.stageAllAndCommit()
|
||||
#expect(git.executed.isEmpty)
|
||||
}
|
||||
|
||||
@Test func stageAllAndCommitDoesNotCommitWhenStagingFails() async {
|
||||
let (store, git, _) = await makeStore()
|
||||
git.setRun(FakeGitRun(exitCode: 128, lines: [("fatal: Unable to create '.git/index.lock': File exists.", true)]), forCommand: "add")
|
||||
store.setCommitMessage("ship it")
|
||||
await store.stageAllAndCommit()
|
||||
#expect(git.executed.map(\.first) == ["add"])
|
||||
}
|
||||
|
||||
// MARK: Push and pull
|
||||
|
||||
@Test func aPushWithoutUpstreamRetriesWithTheBranch() async {
|
||||
@@ -441,6 +556,60 @@ import Testing
|
||||
#expect(git.executed.isEmpty)
|
||||
}
|
||||
|
||||
@Test func mergingIsRefusedWhileDirtyWithoutAskingGit() async {
|
||||
let (store, git, recorder) = await makeStore()
|
||||
#expect(await !store.mergeBranch("feature"))
|
||||
#expect(git.executed.isEmpty)
|
||||
#expect(recorder.toastTitles == ["— Commit or discard 6 files before you merge."])
|
||||
}
|
||||
|
||||
@Test func aMergeRunsNoEditIntoTheCurrentBranchAndToasts() async {
|
||||
let (store, git, recorder) = await makeStore(snapshot([]))
|
||||
#expect(await store.mergeBranch("feature"))
|
||||
#expect(git.executed == [["merge", "--no-edit", "feature"]])
|
||||
#expect(texts(store).first == "$ git merge --no-edit feature")
|
||||
#expect(recorder.toastTitles == ["Merged feature into main"])
|
||||
}
|
||||
|
||||
@Test func theCurrentBranchIsNoMerge() async {
|
||||
let (store, git, _) = await makeStore(snapshot([]))
|
||||
#expect(await !store.mergeBranch("main"))
|
||||
#expect(git.executed.isEmpty)
|
||||
}
|
||||
|
||||
@Test func aMergeOnACleanTreeAsksFirst() async {
|
||||
let (store, git, _) = await makeStore(snapshot([]))
|
||||
let request = store.confirmation(for: .mergeBranch("feature"))
|
||||
#expect(request?.title == "Merge feature into main?")
|
||||
#expect(request?.body == "Git merges the commits of feature into main. A conflict stops the merge for you to resolve.")
|
||||
#expect(request?.confirmLabel == "Merge")
|
||||
#expect(request?.action == .mergeBranch("feature"))
|
||||
#expect(git.executed.isEmpty)
|
||||
}
|
||||
|
||||
@Test func aMergeThatWouldBeRefusedAsksNothing() async {
|
||||
let (dirty, _, _) = await makeStore()
|
||||
#expect(dirty.confirmation(for: .mergeBranch("feature")) == nil)
|
||||
let (clean, _, _) = await makeStore(snapshot([]))
|
||||
#expect(clean.confirmation(for: .mergeBranch("main")) == nil)
|
||||
}
|
||||
|
||||
@Test func aMergeThatLeavesConflictsSaysSo() async {
|
||||
let (store, git, recorder) = await makeStore(snapshot([]))
|
||||
git.setRun(FakeGitRun(exitCode: 1, lines: [("CONFLICT (content): Merge conflict in a.txt", false)]), forCommand: "merge")
|
||||
git.set(snapshot([("a.txt", .unmerged, false)]))
|
||||
#expect(await !store.mergeBranch("feature"))
|
||||
#expect(recorder.toastTitles == ["Merge conflict — resolve, then commit"])
|
||||
}
|
||||
|
||||
@Test func aFailedMergeWithoutConflictsShowsGitsError() async {
|
||||
let (store, git, recorder) = await makeStore(snapshot([]))
|
||||
git.setRun(FakeGitRun(exitCode: 1, lines: [("merge: nope - not something we can merge", true)]), forCommand: "merge")
|
||||
#expect(await !store.mergeBranch("nope"))
|
||||
#expect(recorder.toasts.last?.0 == "Merge failed")
|
||||
#expect(recorder.toasts.last?.1 == "merge: nope - not something we can merge")
|
||||
}
|
||||
|
||||
// MARK: Console
|
||||
|
||||
@Test func clearEmptiesTheLogWithoutGit() async {
|
||||
@@ -505,6 +674,23 @@ import Testing
|
||||
#expect(texts(store).first == "$ git fetch origin")
|
||||
}
|
||||
|
||||
@Test func openingTheViewAndEveryCommandReadTheRecentCommits() async {
|
||||
let (store, git, _) = await makeStore()
|
||||
let first = [GitCommitSummary(hash: "a1b2c3d", subject: "first", author: "Jonathan",
|
||||
date: Date(timeIntervalSince1970: 1_700_000_000))]
|
||||
git.setRecentCommits(first)
|
||||
#expect(store.recentCommits.isEmpty)
|
||||
await store.viewOpened()
|
||||
#expect(store.recentCommits == first)
|
||||
|
||||
let second = [GitCommitSummary(hash: "b2c3d4e", subject: "second", author: "Jonathan",
|
||||
date: Date(timeIntervalSince1970: 1_700_000_100))] + first
|
||||
git.setRecentCommits(second)
|
||||
await store.stage(["README.md"])
|
||||
#expect(store.recentCommits == second)
|
||||
#expect(git.recentCommitsReads == 2)
|
||||
}
|
||||
|
||||
@Test func anUpstreamOnOriginIsEnoughToFetch() async {
|
||||
let tracked = GitSnapshot(branch: "main", ahead: 1, canPush: true, upstream: "origin/main", changes: [])
|
||||
let (store, git, _) = await makeStore(tracked)
|
||||
@@ -536,3 +722,81 @@ import Testing
|
||||
#expect(!store.isPolling)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct SourceControlGenerateMessageTests {
|
||||
private func makeStore(_ rows: [(String, GitStatus, Bool)] = [("a.txt", .modified, true)])
|
||||
async -> (SourceControlStore, FakeGit, FakeCommitMessages, Recorder, () -> Int) {
|
||||
let git = FakeGit(snapshot(rows))
|
||||
let generator = FakeCommitMessages()
|
||||
let store = SourceControlStore(git: git, commitMessages: generator, derive: TestDerivation.derive)
|
||||
let recorder = Recorder()
|
||||
store.notify = recorder.notify
|
||||
var focused = 0
|
||||
store.focusMessage = { focused += 1 }
|
||||
await store.refresh()
|
||||
return (store, git, generator, recorder, { focused })
|
||||
}
|
||||
|
||||
@Test func successReplacesTheMessageAndFocusesTheField() async {
|
||||
let (store, git, generator, recorder, focused) = await makeStore()
|
||||
git.setStagedDiff(StagedDiff(stat: " a.txt | 1 +\n", patch: "+the change\n"))
|
||||
generator.setResult(.success("Adds the change"))
|
||||
store.setCommitMessage("old draft")
|
||||
await store.generateCommitMessage()
|
||||
#expect(store.commitMessage == "adds the change")
|
||||
#expect(focused() == 1)
|
||||
#expect(recorder.toasts.isEmpty)
|
||||
#expect(!store.isGeneratingMessage)
|
||||
let prompt = generator.prompts.first ?? ""
|
||||
#expect(prompt.contains(" a.txt | 1 +"))
|
||||
#expect(prompt.contains("+the change"))
|
||||
}
|
||||
|
||||
@Test func failureToastsWithTheDetailAndKeepsTheDraft() async {
|
||||
let (store, _, generator, recorder, focused) = await makeStore()
|
||||
generator.setResult(.failure(.notFound))
|
||||
store.setCommitMessage("my draft")
|
||||
await store.generateCommitMessage()
|
||||
#expect(store.commitMessage == "my draft")
|
||||
#expect(recorder.toasts.map(\.0) == ["Couldn't generate a commit message"])
|
||||
#expect(recorder.toasts.first?.1 == "claude not found")
|
||||
#expect(focused() == 0)
|
||||
#expect(!store.isGeneratingMessage)
|
||||
}
|
||||
|
||||
@Test func nothingStagedDoesNothing() async {
|
||||
let (store, _, generator, recorder, _) = await makeStore([("a.txt", .modified, false)])
|
||||
#expect(!store.canGenerateMessage)
|
||||
await store.generateCommitMessage()
|
||||
#expect(generator.prompts.isEmpty)
|
||||
#expect(recorder.toasts.isEmpty)
|
||||
#expect(store.commitMessage == "")
|
||||
}
|
||||
|
||||
@Test func anEmptyStagedDiffToastsWithoutAskingClaude() async {
|
||||
let (store, git, generator, recorder, _) = await makeStore()
|
||||
git.setStagedDiff(StagedDiff(stat: "", patch: ""))
|
||||
await store.generateCommitMessage()
|
||||
#expect(generator.prompts.isEmpty)
|
||||
#expect(recorder.toasts.map(\.0) == ["Couldn't generate a commit message"])
|
||||
}
|
||||
|
||||
@Test func aClickWhileGeneratingIsIgnored() async {
|
||||
let (store, _, generator, _, _) = await makeStore()
|
||||
generator.setDelay(.milliseconds(200))
|
||||
let first = Task { await store.generateCommitMessage() }
|
||||
#expect(await eventually { store.isGeneratingMessage })
|
||||
#expect(!store.canGenerateMessage)
|
||||
await store.generateCommitMessage()
|
||||
await first.value
|
||||
#expect(generator.prompts.count == 1)
|
||||
#expect(!store.isGeneratingMessage)
|
||||
}
|
||||
|
||||
@Test func withoutAGeneratorTheButtonStaysOff() async {
|
||||
let store = SourceControlStore(git: FakeGit(snapshot([("a.txt", .modified, true)])), derive: TestDerivation.derive)
|
||||
await store.refresh()
|
||||
#expect(!store.canGenerateMessage)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,6 +294,39 @@ import Testing
|
||||
#expect(harness.model.editor?.text(for: "a.php") == "committed")
|
||||
}
|
||||
|
||||
@Test func cleanUpAsksFirstThenRunsGitAndReloadsTheFile() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false), ("new.txt", .added, false)]),
|
||||
contents: ["a.php": "edited"])
|
||||
await harness.start()
|
||||
harness.model.open("a.php")
|
||||
await harness.model.settle()
|
||||
await harness.perform(.context(.gitCleanUp))
|
||||
guard case let .confirm(request) = harness.model.overlay.current else {
|
||||
Issue.record("expected a confirm overlay")
|
||||
return
|
||||
}
|
||||
#expect(request.title == "Clean up 2 files?")
|
||||
#expect(harness.git.executed.isEmpty)
|
||||
harness.files.set("a.php", "staged")
|
||||
await harness.perform(.confirmPending)
|
||||
#expect(harness.git.executed == [["restore", "--worktree", "--", "."], ["clean", "-fd"]])
|
||||
#expect(await eventually { harness.model.editor?.text(for: "a.php") == "staged" })
|
||||
}
|
||||
|
||||
@Test func mergeAsksFirstThenRunsGit() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([]))
|
||||
await harness.start()
|
||||
await harness.perform(.context(.mergeBranch("feature")))
|
||||
guard case let .confirm(request) = harness.model.overlay.current else {
|
||||
Issue.record("expected a confirm overlay")
|
||||
return
|
||||
}
|
||||
#expect(request.confirmLabel == "Merge")
|
||||
#expect(harness.git.executed.isEmpty)
|
||||
await harness.perform(.confirmPending)
|
||||
#expect(harness.git.executed == [["merge", "--no-edit", "feature"]])
|
||||
}
|
||||
|
||||
@Test func stagingRunsGitStraightAway() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false), ("b.php", .modified, false)]))
|
||||
await harness.start()
|
||||
@@ -353,6 +386,46 @@ import Testing
|
||||
#expect(harness.toastTitles == ["Committed 1 file", "Pushed to origin/main"])
|
||||
}
|
||||
|
||||
@Test func theCommitButtonCommitsWithoutPushingAndCommitAndPushPushes() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, true)]))
|
||||
await harness.start()
|
||||
harness.model.sourceControl?.setCommitMessage("fix it")
|
||||
await harness.perform(.commit)
|
||||
#expect(harness.git.executed == [["commit", "-m", "fix it"]])
|
||||
|
||||
let pushing = WorkspaceHarness(git: snapshot([("a.php", .modified, true)]))
|
||||
await pushing.start()
|
||||
pushing.model.sourceControl?.setCommitMessage("ship it")
|
||||
await pushing.perform(.commitAndPush)
|
||||
#expect(pushing.git.executed == [["commit", "-m", "ship it"], ["push"]])
|
||||
}
|
||||
|
||||
@Test func theStageAllAndCommitCommandStagesThenCommitsWithoutPushing() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false), ("new.txt", .added, false)]))
|
||||
await harness.start()
|
||||
harness.model.sourceControl?.setCommitMessage("ship it")
|
||||
await harness.perform(.stageAllAndCommit)
|
||||
#expect(harness.git.executed == [["add", "--", "a.php", "new.txt"], ["commit", "-m", "ship it"]])
|
||||
}
|
||||
|
||||
@Test func theGenerateCommitMessageCommandFillsTheMessageAndFocusesIt() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, true)]))
|
||||
await harness.start()
|
||||
harness.commitMessages.setResult(.success("Fixed the login form"))
|
||||
await harness.perform(.generateCommitMessage)
|
||||
#expect(harness.model.sourceControl?.commitMessage == "fixed the login form")
|
||||
#expect(harness.model.focusRequest?.target == .commitMessage)
|
||||
#expect(harness.git.executed.isEmpty)
|
||||
}
|
||||
|
||||
@Test func aFailedGenerationToastsOnce() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, true)]))
|
||||
await harness.start()
|
||||
harness.commitMessages.setResult(.failure(.timedOut))
|
||||
await harness.perform(.generateCommitMessage)
|
||||
#expect(harness.toastTitles == ["Couldn't generate a commit message"])
|
||||
}
|
||||
|
||||
@Test func commitWithoutAMessageStillAsksGitThenFocusesTheMessage() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, true)]))
|
||||
await harness.start()
|
||||
@@ -637,6 +710,46 @@ import Testing
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct TailLogModelTests {
|
||||
@Test func tailLogShowsTheBlockAndCloseRemovesIt() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.perform(.context(.tailLog("storage/logs/laravel.log")))
|
||||
#expect(harness.model.terminal.tailedPath == "storage/logs/laravel.log")
|
||||
let tail = FakeTerminal()
|
||||
harness.model.terminal.start(.tail, on: tail)
|
||||
await harness.perform(.closeTail)
|
||||
#expect(tail.terminations == 1)
|
||||
#expect(harness.model.terminal.tailedPath == nil)
|
||||
}
|
||||
|
||||
@Test func tailingASecondLogReplacesTheFirst() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.perform(.context(.tailLog("a.log")))
|
||||
let first = FakeTerminal()
|
||||
harness.model.terminal.start(.tail, on: first)
|
||||
await harness.perform(.context(.tailLog("b.log")))
|
||||
#expect(first.terminations == 1)
|
||||
#expect(harness.model.terminal.tailedPath == "b.log")
|
||||
}
|
||||
|
||||
@Test func aProjectSwitchEndsTheTailAndOpensWithout() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
await harness.perform(.context(.tailLog("a.log")))
|
||||
let tail = FakeTerminal()
|
||||
harness.model.terminal.start(.tail, on: tail)
|
||||
await harness.model.openProject(URL(fileURLWithPath: "/fake/other"))
|
||||
#expect(tail.terminations == 1)
|
||||
#expect(harness.model.terminal.tailedPath == nil)
|
||||
}
|
||||
|
||||
@Test func theTailLogItemUsesThePlainTint() {
|
||||
#expect(ContextMenuOverlay.tint(for: .tailLog("a.log")) == .plain)
|
||||
#expect(ContextMenuOverlay.symbol(for: .tailLog("a.log")) == "terminal")
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct TerminalContextMenuModelTests {
|
||||
@Test func aRightClickInATerminalOpensTheAppMenuAtThePointer() {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import Foundation
|
||||
import HelderServices
|
||||
|
||||
/// Answers `generate` with a scripted message or error and records every prompt.
|
||||
final class FakeCommitMessages: CommitMessageGenerating, @unchecked Sendable {
|
||||
private struct State {
|
||||
var result: Result<String, CommitMessageError> = .success("Adds a generated message")
|
||||
var delay: Duration = .zero
|
||||
var prompts: [String] = []
|
||||
}
|
||||
|
||||
private let state = Locked(State())
|
||||
|
||||
var prompts: [String] { state.current.prompts }
|
||||
|
||||
func setResult(_ result: Result<String, CommitMessageError>) { state.mutate { $0.result = result } }
|
||||
/// How long each `generate` takes before it answers.
|
||||
func setDelay(_ delay: Duration) { state.mutate { $0.delay = delay } }
|
||||
|
||||
func generate(prompt: String) async throws -> String {
|
||||
let (result, delay) = state.mutate { state in
|
||||
state.prompts.append(prompt)
|
||||
return (state.result, state.delay)
|
||||
}
|
||||
if delay > .zero { try await Task.sleep(for: delay) }
|
||||
return try result.get()
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,9 @@ final class FakeGit: GitServicing, @unchecked Sendable {
|
||||
var runsByCommand: [String: FakeGitRun] = [:]
|
||||
var branches = GitBranchList.empty
|
||||
var author: String?
|
||||
var recentCommits: [GitCommitSummary] = []
|
||||
var recentCommitsReads = 0
|
||||
var stagedDiff: StagedDiff? = StagedDiff(stat: " a.txt | 1 +\n", patch: "+a\n")
|
||||
}
|
||||
|
||||
private let state: Locked<State>
|
||||
@@ -54,6 +57,10 @@ final class FakeGit: GitServicing, @unchecked Sendable {
|
||||
func setRun(_ run: FakeGitRun, forCommand command: String) { state.mutate { $0.runsByCommand[command] = run } }
|
||||
func setBranches(_ value: GitBranchList) { state.mutate { $0.branches = value } }
|
||||
func setAuthor(_ value: String?) { state.mutate { $0.author = value } }
|
||||
func setRecentCommits(_ value: [GitCommitSummary]) { state.mutate { $0.recentCommits = value } }
|
||||
var recentCommitsReads: Int { state.current.recentCommitsReads }
|
||||
/// What `stagedDiff` returns; nil plays a failed git read.
|
||||
func setStagedDiff(_ value: StagedDiff?) { state.mutate { $0.stagedDiff = value } }
|
||||
/// Makes every `load` throw this error, or read normally again with nil.
|
||||
func setLoadError(_ error: Error?) { state.mutate { $0.loadError = error } }
|
||||
|
||||
@@ -86,6 +93,13 @@ final class FakeGit: GitServicing, @unchecked Sendable {
|
||||
|
||||
func branches() async -> GitBranchList { state.current.branches }
|
||||
func author() async -> String? { state.current.author }
|
||||
func recentCommits() async -> [GitCommitSummary] {
|
||||
state.mutate { state in
|
||||
state.recentCommitsReads += 1
|
||||
return state.recentCommits
|
||||
}
|
||||
}
|
||||
func stagedDiff() async -> StagedDiff? { state.current.stagedDiff }
|
||||
}
|
||||
|
||||
/// A snapshot with one change per row: (path, status, staged).
|
||||
|
||||
@@ -20,6 +20,7 @@ struct WorkspaceHarness {
|
||||
let speech: FakeSpeech
|
||||
let schema: FakeSchema
|
||||
let schemaLayouts: FakeSchemaLayouts
|
||||
let commitMessages: FakeCommitMessages
|
||||
let watchers: WatcherBox
|
||||
let agent = FakeTerminal()
|
||||
|
||||
@@ -42,13 +43,15 @@ struct WorkspaceHarness {
|
||||
let speech = FakeSpeech()
|
||||
let schema = FakeSchema()
|
||||
let schemaLayouts = FakeSchemaLayouts()
|
||||
let commitMessages = FakeCommitMessages()
|
||||
let watchers = WatcherBox()
|
||||
let app = AppServices(
|
||||
recentProjects: recentStore, session: session, layouts: layouts, schemaLayouts: schemaLayouts,
|
||||
system: system, speech: speech,
|
||||
makeWorkspace: { _ in
|
||||
WorkspaceServices(git: git, files: files, search: FakeSearch(), symbols: symbols,
|
||||
config: config, recentFiles: recentFiles, schema: schema)
|
||||
config: config, recentFiles: recentFiles, schema: schema,
|
||||
commitMessages: commitMessages)
|
||||
},
|
||||
makeWatcher: {
|
||||
let watcher = FakeWatcher()
|
||||
@@ -70,6 +73,7 @@ struct WorkspaceHarness {
|
||||
self.speech = speech
|
||||
self.schema = schema
|
||||
self.schemaLayouts = schemaLayouts
|
||||
self.commitMessages = commitMessages
|
||||
self.watchers = watchers
|
||||
model.terminal.attach(agent, as: .agent)
|
||||
}
|
||||
|
||||
@@ -171,6 +171,84 @@ import Testing
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct TerminalStoreTailTests {
|
||||
private let environment = ["SHELL": "/bin/zsh", "HOME": "/Users/me"]
|
||||
|
||||
@Test func aTailRunsTailOnThePathInTheProjectWithoutALoginShell() {
|
||||
let store = TerminalStore(projectRoot: "/code/app", environment: environment)
|
||||
store.startTail("storage/logs/laravel.log")
|
||||
let tail = FakeTerminal()
|
||||
store.start(.tail, on: tail)
|
||||
#expect(store.tailedPath == "storage/logs/laravel.log")
|
||||
#expect(store.tail === tail)
|
||||
#expect(tail.starts.first?.launch.executable == "/usr/bin/tail")
|
||||
#expect(tail.starts.first?.launch.arguments == ["-f", "storage/logs/laravel.log"])
|
||||
#expect(tail.starts.first?.launch.workingDirectory == "/code/app")
|
||||
#expect(tail.starts.first?.argv0 == "tail")
|
||||
}
|
||||
|
||||
@Test func withoutATailedPathThePaneSpawnsNothing() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: environment)
|
||||
let tail = FakeTerminal()
|
||||
store.start(.tail, on: tail)
|
||||
#expect(tail.starts.isEmpty)
|
||||
#expect(store.tail == nil)
|
||||
}
|
||||
|
||||
@Test func tailingAnotherFileTerminatesTheOldTailAndAsksForAFreshPane() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: environment)
|
||||
store.startTail("a.log")
|
||||
let first = FakeTerminal()
|
||||
store.start(.tail, on: first)
|
||||
let generation = store.tailGeneration
|
||||
store.startTail("b.log")
|
||||
#expect(first.terminations == 1)
|
||||
#expect(store.tail == nil)
|
||||
#expect(store.tailedPath == "b.log")
|
||||
#expect(store.tailGeneration != generation)
|
||||
let second = FakeTerminal()
|
||||
store.start(.tail, on: second)
|
||||
#expect(second.starts.first?.launch.arguments == ["-f", "b.log"])
|
||||
#expect(first.starts.count == 1)
|
||||
}
|
||||
|
||||
@Test func closeTerminatesTheTailAndRemovesTheBlock() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: environment)
|
||||
store.startTail("a.log")
|
||||
let tail = FakeTerminal()
|
||||
store.start(.tail, on: tail)
|
||||
store.closeTail()
|
||||
#expect(tail.terminations == 1)
|
||||
#expect(store.tail == nil)
|
||||
#expect(store.tailedPath == nil)
|
||||
}
|
||||
|
||||
@Test func terminateAllEndsTheTailToo() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: environment)
|
||||
let agent = FakeTerminal(), shell = FakeTerminal(), tail = FakeTerminal()
|
||||
store.start(.agent, on: agent)
|
||||
store.start(.shell, on: shell)
|
||||
store.startTail("a.log")
|
||||
store.start(.tail, on: tail)
|
||||
store.terminateAll()
|
||||
#expect([agent, shell, tail].allSatisfy { $0.terminations == 1 })
|
||||
#expect(store.tail == nil)
|
||||
#expect(store.tailedPath == nil)
|
||||
store.release(tail)
|
||||
#expect(tail.terminations == 1)
|
||||
}
|
||||
|
||||
@Test func aTailExitIsReportedOnItsOwn() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: environment)
|
||||
store.startTail("a.log")
|
||||
store.start(.tail, on: FakeTerminal())
|
||||
store.processExited(.tail, exitCode: 1)
|
||||
#expect(store.hasExited(.tail))
|
||||
#expect(!store.hasExited(.shell))
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct TerminalPseudoTerminalTests {
|
||||
@Test(.tags(.realProcess), .timeLimit(.minutes(1)))
|
||||
|
||||
+22
-10
@@ -48,20 +48,21 @@ The title-bar panel toggle group now reads `Git N · Schema · Explorer · File
|
||||
|
||||
## Screen: Git view (full screen)
|
||||
|
||||
A `position: fixed; inset: 0` layer, `z-index: 44`, background `#101720`, min-width 900px, laid out as a flex column. It sits above the app shell and below the file diff overlay (45), context menu (60/61), modal (70) and toast (80). This lets the confirm modals and the commit menu appear on top of it.
|
||||
A `position: fixed; inset: 0` layer, `z-index: 44`, background `#101720`, min-width 900px, laid out as a flex column. It sits above the app shell and below the file diff overlay (45), context menu (60/61), modal (70) and toast (80). This lets the confirm modals and the context menus appear on top of it.
|
||||
|
||||
From top to bottom:
|
||||
|
||||
### 1. Top bar — 44px
|
||||
- Background `#18202B`, bottom border `1px #232C39`, padding `0 14px`, flex row, gap 14px, items centred.
|
||||
- Background `#18202B`, bottom border `1px #232C39`, padding `0 14px` (left: the traffic-light inset, 14px in full screen), flex row, gap 14px, items centred.
|
||||
- **`[ GIT ]`**: Plex Mono 700, 11px, letter-spacing .14em, uppercase, `#828D9A`.
|
||||
- **Branch**: Lucide `git-branch` icon at 13px, then the branch name. Plex Mono 500, 12px, `#E8913A`, truncated with an ellipsis.
|
||||
- **Sync label**: Plex Mono 400, 12px, `#828D9A`. Text is `2 behind origin`, `1 ahead · 2 behind origin`, or `in sync with origin`.
|
||||
- A flex spacer, then three buttons, each 28px tall:
|
||||
- A flex spacer, then four buttons, each 28px tall:
|
||||
- Shared style: padding `0 11px`, border `1px #232C39`, radius 2px, transparent background, Plex Sans 500 12px `#BAC0C0`, icon 14px, gap 7px.
|
||||
- Hover: text `#F4F5F4`, border `#3A424C`.
|
||||
- **Pull**: icon `arrow-down-to-line`, label `Pull` (`Pulling…` while busy), then the count `↓2` in Plex Mono 600 11px `#E8913A`. The count is hidden when 0.
|
||||
- **Push**: icon `arrow-up-from-line`, label `Push` (`Pushing…` while busy), then the count `↑1` in the same amber style.
|
||||
- **Clean up** (native build only): icon `eraser`, label `Clean up`, no count. Disabled (40% opacity, default cursor) when nothing is unstaged or untracked, during a merge conflict, or while a pull or push runs.
|
||||
- **Close**: icon `minimize-2`, label `Close`, then the key hint `⌘G` in amber mono 11px.
|
||||
|
||||
### 2. Commit block
|
||||
@@ -71,15 +72,15 @@ From top to bottom:
|
||||
- Padding `14px 16px`, Plex Mono 400, 14px / 1.6, colour `#F4F5F4`, caret `#E8913A`.
|
||||
- Placeholder: `Commit message`. The field gets focus when the Git view opens.
|
||||
- **Footer row**: 52px tall, padding `0 14px 0 16px`, gap 16px.
|
||||
- **Gen. Commit Message** (small secondary), first on the left: 32px tall, padding `0 12px`, radius 2px, a `1px #232C39` border, the pass-on spark glyph (12px, stroke) then the label in the commit-button type, text `#BAC0C0`; hover fills `#1E2733` and turns glyph and text `#F4F5F4`. While it runs the label reads `Generating…`. Disabled (40% opacity, default cursor, no clicks) when nothing is staged or while it runs. A click sends the staged diff to the Claude CLI and puts its one-line answer in the message field (replacing the draft, lowercased like typed text) and focuses the field; a failure toasts `Couldn't generate a commit message` with the reason (`claude not found`, the CLI's first error line, `timed out`). Native build only.
|
||||
- Author `Jonathan van Rij <jonathan@blijnder.nl>` in Plex Mono 12px `#828D9A`. In the real build, read this from `git config user.name` and `user.email`.
|
||||
- Hint `⌘↵ commits` in Plex Mono 12px `#6C7783`.
|
||||
- A spacer, then a **split button**, radius 2px, 32px tall:
|
||||
- Main part: min-width 160px, padding `0 18px`, Plex Sans 600 13px.
|
||||
- Label: `Commit N file(s)`, or `Nothing staged` when nothing is staged.
|
||||
- Ready state (≥1 staged file **and** a non-empty message): background `#E8913A`, text `#101720`.
|
||||
- Otherwise: background `#232C39`, text `#828D9A`. It stays clickable, so git's own error appears in the console.
|
||||
- Caret part: 32×32px, `chevron-down` icon at 14px, separated from the main part by a `1px #101720` left border. It opens a context menu with `Commit` (icon `check`) and **`Commit and push`** (icon `arrow-up-from-line`, bold).
|
||||
- Hover on either part: `filter: brightness(.92)`. (Real build: use amber-deep `#C4741F` instead, per Kade.)
|
||||
- A spacer, then **three buttons** side by side, gap 8px, each radius 2px, 32px tall, padding `0 18px`, Plex Sans 600 13px:
|
||||
- **Add, Stage & Commit** (secondary), on the left: the same look as Commit. Stages every unstaged path with `git add -- <paths>`, then commits without a push. An empty message stages nothing and focuses the message field. Disabled (40% opacity, default cursor, no clicks) with no changes, during a merge conflict, or while a push or pull runs.
|
||||
- **Commit** (secondary): min-width 160px, label `Commit N file(s)`, or `Nothing staged` when nothing is staged. Transparent with a `1px #232C39` border and text `#BAC0C0`; hover fills `#1E2733` and turns the text `#F4F5F4`.
|
||||
- **Commit and push** (primary), on the right. Ready state (≥1 staged file **and** a non-empty message): background `#E8913A`, text `#101720`, hover amber-deep `#C4741F`. Otherwise: background `#232C39`, text `#828D9A`, hover `#202834`. With files staged it stays clickable, so git's own error appears in the console.
|
||||
- Nothing staged: Commit and Commit and push are disabled, 40% opacity, default cursor, clicks do nothing. ⌘↵ still runs `git commit`.
|
||||
- Native build only; the prototype still draws the old split button.
|
||||
|
||||
### 3. File sections (scrolling area, `flex: 1`, padding-bottom 24px)
|
||||
Sections appear in this fixed order, and only when they contain files:
|
||||
@@ -151,6 +152,7 @@ If there are no changes at all, the area shows only: `— No changes. The workin
|
||||
### 5. Bottom strip — 230px, split 50/50
|
||||
- Background `#18202B`, top border `1px #232C39`.
|
||||
- `display: grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr)`. The left half has a `1px #232C39` right border.
|
||||
- Native build: console and branches each stop at 820px. When at least 260px is left after them, a **commits** list fills the rest behind a `1px #232C39` left border; below that the rest stays empty. Not in the prototype.
|
||||
|
||||
**Left — Console**
|
||||
- **Header**: 32px tall, padding `0 12px 0 16px`.
|
||||
@@ -207,6 +209,15 @@ If there are no changes at all, the area shows only: `— No changes. The workin
|
||||
- Switching to a remote branch with no local branch runs `git switch <name>`, which auto-creates a tracking branch. It logs `branch '<name>' set up to track 'origin/<name>'.` and `Switched to a new branch '<name>'`, then adds the branch to the local list.
|
||||
- After a switch: the title bar, status bar and Git top bar show the new branch; ahead/behind are recalculated; expanded diffs are cleared; a toast reads `Switched to <name>`.
|
||||
|
||||
**Far right — Commits** (native build only)
|
||||
- **Header**: 32px tall, padding `0 16px`, `[ COMMITS ]` in the console header style; right side, the current branch in 12px mono `#828D9A`, ellipsis.
|
||||
- **List**: scrolls, overlay scrollers, padding-bottom 12px. The last 30 commits of HEAD (`git log -n 30`), newest first.
|
||||
- **Commit row**: 28px tall, padding `0 16px`, gap 10px, no hover, default cursor. From left to right:
|
||||
- Short hash: Plex Mono 500 12px amber.
|
||||
- Subject: Plex Mono 12px `#E4E7E6`, one line, ellipsis; it takes the free width.
|
||||
- Right-aligned: `author · 3 h ago` 11px `#6C7783`, the author cut at 140px.
|
||||
- **Empty**: `no commits yet`, or `— no repository`, in 12px mono `#6C7783`, padding `0 16px`.
|
||||
|
||||
---
|
||||
|
||||
## Screen: Schema view (full screen)
|
||||
@@ -332,6 +343,7 @@ Real build: run `php artisan helder:schema` in the project root (respect the pro
|
||||
- ` create mode 100644 <path>` / ` delete mode 100644 <path>` for added and deleted files
|
||||
- After a commit: the message clears, the staged section disappears, ahead increases by 1, and the commit is added to `git log`.
|
||||
- **Commit and push** pushes right after a successful commit.
|
||||
- **Add, Stage & Commit** runs `git add -- <every unstaged path>` first, then the same commit; a failed `add` runs no commit.
|
||||
|
||||
**Push**
|
||||
- Ahead 0: `Everything up-to-date`.
|
||||
|
||||
+10
-6
@@ -12,7 +12,7 @@ Helder (executable) → HelderUI → HelderServices → HelderCore
|
||||
| Target | May import | Rules |
|
||||
|---|---|---|
|
||||
| `HelderCore` | Foundation | Pure logic and value types, all `Sendable`. No AppKit, no SwiftUI, no disk, no processes. Swift 6 mode. |
|
||||
| `HelderServices` | HelderCore, Foundation, CoreServices, AVFoundation | Everything that touches disk or spawns `git`/`rg`, behind a protocol. Processes only through `ProcessRunning`. |
|
||||
| `HelderServices` | HelderCore, Foundation, CoreServices, AVFoundation | Everything that touches disk or spawns `git`/`rg`/`php`/`claude`, behind a protocol. Processes only through `ProcessRunning`. |
|
||||
| `HelderUI` | Core, Services, SwiftUI, AppKit, SwiftTerm | `@Observable @MainActor` stores plus views. Never runs a process or touches project files directly, only through the service protocols (the SwiftTerm terminals are the one exception). |
|
||||
| `Helder` | HelderUI | The `@main` app. Keep it tiny. |
|
||||
|
||||
@@ -25,10 +25,11 @@ Helder (executable) → HelderUI → HelderServices → HelderCore
|
||||
- **Stores report, the model shows.** Stores raise toasts through `notify`/`showToast` hooks the model wires to `ToastStore`; the model never toasts a second time for the same action.
|
||||
- **Closing.** A window close, a project switch and ⌘Q all run `prepareToClose()` first: every unsaved file (at most the open one plus a vanished-file buffer) is asked about, and a cancel keeps everything open. Then `closeProject()` waits for running work, writes the session and ends the terminals.
|
||||
- **Lifecycle.** `start()`: recents → config (applied to every store and the terminals) → git, tree and the `.clean-copy` baseline in parallel → `editor.restore` → watcher → git polling (`git.refreshInterval`) → the PHP class list 1.5 s later. Watcher events: `.cleanCopy` (`.clean-copy` in the root, 150 ms debounce, fired besides `.project`) makes `CleanCopyStore` re-read the file and opens the `.cleanCopy` overlay for new non-blank text (the text found at load is the baseline; another open overlay makes it wait, keeping only the newest); `.project` re-reads git, the tree, the open file and every unsaved buffer (the edits kept), invalidates the symbol index and reloads the class list 2 s after the last change; `.git` re-reads git; `.config` re-resolves and re-applies the config. ⌘R re-reads git and the tree and lets the disk win in the open file. A project switch or window close saves the session, stops the watcher and polling, and ends both terminals.
|
||||
- **Terminals.** `TerminalStore` owns both panes' handles. Ending a pane goes through the store (`terminateAll`, `restart`, or `release` when a pane's window closes), which signals the child and lets `ChildReaper` collect it, so no zombie or orphan is left. A pane whose child exited restarts on the next key press. Right-click raises `contextMenuRequested`; the model shows the app's own menu (`.terminal` target: Copy with a selection, Paste). Font size follows `layout.textScale` (⌘0/⌘+/⌘−) live.
|
||||
- **Terminals.** `TerminalStore` owns both panes' handles. Ending a pane goes through the store (`terminateAll`, `restart`, or `release` when a pane's window closes), which signals the child and lets `ChildReaper` collect it, so no zombie or orphan is left. A pane whose child exited restarts on the next key press. Right-click raises `contextMenuRequested`; the model shows the app's own menu (`.terminal` target: Copy with a selection, Paste). Font size follows `layout.textScale` (⌘0/⌘+/⌘−) live. The Explorer's tail block is a third kind, `.tail` (`TerminalLaunch.tail`: `/usr/bin/tail -f <path>`, no shell): `startTail` ends the old one and bumps `tailGeneration`, which the block uses as its pane's `.id`, so each file gets a fresh view and process; `closeTail` and `terminateAll` end it, and `tailedPath` is never persisted.
|
||||
- **Git view.** ⌘G toggles `LayoutStore.isGitViewOpen` (never persisted, reset on a project switch). `WorkspaceView` draws `GitView` as an overlay over title bar, columns and status bar, under `OverlayHost`, so every overlay and toast sits above it; the columns stay mounted. `KeyContext.gitViewOpen` sends keys to `KeyRouter.gitViewKey` (column keys rest, ⌘↵ commits) and makes a bare Esc `.closeGitView` once no overlay is open; `inGitConsole` (first responder is a `GitConsoleFieldEditor`) keeps ⌘↵ from committing out of the console. `openGitView()` / `closeGitView()` in `+Commands` move the focus request (commit message in, previous `activePanel` out). Design source: `design/README.md`.
|
||||
- **Schema view.** ⌘D toggles `LayoutStore.isSchemaViewOpen` (never persisted, reset on a project switch); `openGitView`/`openSchemaView` close each other. It exists only when `SchemaStore.isLaravelApp` (an `artisan` file): the title-bar toggle, `KeyContext.schemaAvailable` for ⌘D and the View menu item follow it. `WorkspaceView` draws `SchemaView` like `GitView`. `SchemaStore.body` picks the command-missing prompt, the no-dump state or the diagram. The watcher's `.project` events and ⌘R carry `RefreshScope.schema`: `refresh(readingDump:)` re-checks the command and re-reads the dump only when its modification date moved, keeping viewport and positions (`SchemaLayout.positions(_:saved:)`). Card positions go to `AppServices.schemaLayouts` when a drag ends; the first dump in a store fits once the canvas has a size. `run()` streams `SchemaServicing.runDump` like the Git console and toasts through `notify`. Esc over the view: selection (`.clearSchemaSelection`), then the search text while `SchemaSearchFieldEditor` has the keyboard (`.clearSchemaSearch`), then `.closeSchemaView`. The canvas lays each card out at 100% and scales it into its on-screen frame, so the click and `.pointerHand()` area stay unscaled; scroll and pinch arrive through a local event monitor (`SchemaScrollCatcher`), since the cards would take them otherwise. Contract: [schema.md](schema.md).
|
||||
- **Git commands.** Every git write and every typed console command goes through `SourceControlStore.run`, which chains onto `commandTail` so two commands never race for `.git/index.lock`, logs `$ git …` and streams lines via `GitServicing.execute` → `ProcessRunning.stream` into the console (`GitOutputClassifier`, one per run). `execute` never throws and switches off prompts, editors and pagers (`GIT_TERMINAL_PROMPT=0`, `GIT_EDITOR=true`, `GIT_PAGER=cat`), so a run can never wait on input. Typed commands run without literal pathspecs (globs work); buttons always pass explicit paths, never `add -A`. Push/pull/fetch and typed commands get `remoteTimeout` (120 s). Commit always runs git, even when `canCommitNow` is false, so git's refusal is the error the user sees. Branch switching is refused in the store while `isDirty`, without asking git. The status read (`load`) stays on `ProcessRunning.run`.
|
||||
- **Git commands.** Every git write and every typed console command goes through `SourceControlStore.run`, which chains onto `commandTail` so two commands never race for `.git/index.lock`, logs `$ git …` and streams lines via `GitServicing.execute` → `ProcessRunning.stream` into the console (`GitOutputClassifier`, one per run). `execute` never throws and switches off prompts, editors and pagers (`GIT_TERMINAL_PROMPT=0`, `GIT_EDITOR=true`, `GIT_PAGER=cat`), so a run can never wait on input. Typed commands run without literal pathspecs (globs work); buttons always pass explicit paths, never `add -A`. Push/pull/fetch and typed commands get `remoteTimeout` (120 s). Commit always runs git, even when `canCommitNow` is false, so git's refusal is the error the user sees. Branch switching and merging are refused in the store while `isDirty`, without asking git. The status read (`load`) stays on `ProcessRunning.run`.
|
||||
- **Commit message generation.** `.generateCommitMessage` → `SourceControlStore.generateCommitMessage()`: `GitServicing.stagedDiff()` (stat + patch, outside `commandTail` and the console), `CommitMessagePrompt.make` (patch cut at 60 000 characters), then `WorkspaceServices.commitMessages` (`ClaudeCommitMessageService`: the binary from `ExecutableLocator.agent`, its folder first on PATH, the prompt via `ProcessRunning.run(input:)`, cleaned with `CommitMessagePrompt.clean`). Success goes through `setCommitMessage` (so it is lowercased) and `focusMessage`; a `CommitMessageError` toasts through `notify`. `isGeneratingMessage` drives the label and ignores a second click. A window close cancels the run with the rest of `work`, which kills the child.
|
||||
- **Git and files.** Git gets paths as literal pathspecs (`GIT_LITERAL_PATHSPECS=1`, so `pages/[id].vue` is one file). A changed file over `FileLimits.maxDiffFileBytes` (1 MB) keeps its row but loads no text: `GitFileChange.isTooBig` → `Diff.isTooBig`, and the Diff shows "Too big.". Saves are atomic (temp file, then rename, keeping permissions). Writes, creates, renames and deletes are refused when the entry's folder resolves (symlinks included) outside the project (`containedURL`). The watcher drops `IgnoreRules.walkIgnoredNames`, framework caches (`storage/framework/`, `bootstrap/cache/`, `.phpunit*`) and `files.exclude`.
|
||||
- **Processes.** Every new window (⇧⌘N, the Dock's New Window, Open Folder or Open Recent with no key window) is a new Helder process via `SystemActing.openNewInstance`: `NSWorkspace` with `createsNewApplicationInstance` in the bundle, `InstanceLauncher` (Foundation `Process`) under `swift run`. The folder travels as `-HelderProject <path>`, which `ProjectLocator.initialRoot` reads as its directory argument; a bare path could reach AppKit as a file to open. Switching projects (⌘O, Open Recent in a window) stays in the process. `AppName` renames the process to the project's title (the launcher is "Helder"), so Mission Control, the Dock and ⌘Tab tell projects apart. Windows are not restorable and `NSQuitAlwaysKeepsWindows` is off, so a launch opens exactly one window.
|
||||
- **Editor.** `EditorStore` shows exactly one file (`activePath`); opening another replaces it, and there are no tabs. Every `open` (Git view, Explorer, search, recent files, links) re-reads the file from disk; the disk wins. Unsaved edits do not outlive switching: opening any file, the same one included, while the open file is dirty asks Save / Don't Save / Cancel (with `editor.autoSave` on it saves silently). Cancel moves nothing, Explorer selection included; a failed save keeps the dirty file open. `dirtyPaths` is therefore at most the open file plus a vanished-file buffer, and the close/quit flow asks about each. ⌘W closes the open file (asking first when dirty) and shows the empty state. `EditorBar` above the code shows the type badge, the path, the unsaved dot and `+N`/`−N`, then a Preview button for Markdown and a Diff button for a changed file (`EditorPresentation.barButtons`). A changed file shows Actual (the live buffer with changed lines marked), an unchanged one plain code; ⌘M only flips Markdown between code and preview. The session stores the open file and its mode and side; a stored `openTabs` list and unknown modes are ignored.
|
||||
@@ -43,7 +44,8 @@ Sources/HelderCore/
|
||||
Diff/ Diff models, LineDiff, DiffViews, ViewMode
|
||||
Files/ FileNode + FileTree, PathUtils, FileType (language, badge), limits + ignore rules, ContextActions (menus)
|
||||
Git/ GitStatus/Change/GitSnapshot, Porcelain parsing (incl. behind/upstream), GitDerivation (rows, commit text),
|
||||
GitSections (the four sections, InlineDiff), GitConsole (echo, input parsing, line classifier), GitBranches
|
||||
GitSections (the four sections, InlineDiff), GitConsole (echo, input parsing, line classifier), GitBranches,
|
||||
GitCommitLog (recent commits, relative time), CommitMessagePrompt (staged-diff prompt, answer cleaning)
|
||||
Schema/ SchemaDump (tolerant schema.json decoding), SchemaModel, SchemaLayout (default lanes), SchemaGeometry
|
||||
(lines, fit, zoom, centre), SchemaHighlight + SchemaSearch, ArtisanConsole, SchemaCommandPrompt, SchemaPaths
|
||||
Highlight/ SyntaxHighlighter and one grammar per language
|
||||
@@ -53,9 +55,11 @@ Sources/HelderCore/
|
||||
Symbols/ PHP symbol models and line parsers
|
||||
Sources/HelderServices/
|
||||
Files/ FileServicing (read, readText → .binary), FileService, FSEventsWatcher + WatchDebounce
|
||||
Agent/ CommitMessageGenerating + ClaudeCommitMessageService (`claude -p`, prompt on stdin, no tools, 90 s)
|
||||
Git/ GitServicing, GitService, GitDirectory (worktrees)
|
||||
Logging/ Log (unified log) + FileLogger (~/Library/Logs/Helder/helder.log)
|
||||
Process/ ProcessRunner (`run`, and `stream` for line-by-line output), ExecutableLocator, ChildReaper, InstanceLauncher
|
||||
Process/ ProcessRunner (`run`, `run(input:)` for stdin, `stream` for line-by-line output), ExecutableLocator
|
||||
(`.agent` adds ~/.local/bin and ~/.claude/local), ChildReaper, InstanceLauncher
|
||||
Project/ ConfigService, RecentStores, SessionStore, ProjectLocator
|
||||
Schema/ SchemaServicing + SchemaService (`php artisan helder:schema` via PHPLocator, the dump), SchemaLayoutPersisting
|
||||
Search/ SearchServicing + RipgrepSearchService, ProjectScanner (rg, or a Swift walk)
|
||||
@@ -68,7 +72,7 @@ Sources/HelderUI/
|
||||
Components/ OverlayShell/OverlayCard/OverlayHeader/OverlayFooter, ContextMenuPanel/Header/Row/Separator,
|
||||
Keycap, EscChip, Primary/Secondary button styles, focusRing, SegmentButton, Splitter,
|
||||
ButtonGroup (pane toggles, toolbar), Tooltip, TypeBadge, PanelLabel/PanelHeader, Hairline, selectableRow, Blink
|
||||
GitView/ the full-screen Git view (⌘G): top bar, commit block, sections with inline diffs, console, branches;
|
||||
GitView/ the full-screen Git view (⌘G): top bar, commit block, sections with inline diffs, console, branches, commits;
|
||||
GitIcon and the console log/input the Schema view reuses
|
||||
SchemaView/ the full-screen Schema view (⌘D): top bar, table list, canvas with cards and lines, detail panel,
|
||||
artisan console, the no-dump and command-missing states
|
||||
|
||||
+25
-5
@@ -50,7 +50,7 @@ From top to bottom:
|
||||
|
||||
### Top bar
|
||||
|
||||
`[ git ]`, the current branch in amber, and its place against the upstream: `in sync with origin`, `N ahead of origin`, `N behind origin`, `N ahead · M behind origin`, or `no upstream`. Ahead and behind come from the status header. On the right: **Pull** (with `↓N` when behind), **Push** (with `↑N` when ahead) and **Close** (`⌘G`).
|
||||
`[ git ]`, the current branch in amber, and its place against the upstream: `in sync with origin`, `N ahead of origin`, `N behind origin`, `N ahead · M behind origin`, or `no upstream`. Ahead and behind come from the status header. On the right: **Pull** (with `↓N` when behind), **Push** (with `↑N` when ahead), **Clean up** and **Close** (`⌘G`).
|
||||
|
||||
Opening the view reads the author and the branches, re-reads git and runs `git fetch origin`, but only when an origin exists, so ahead/behind are current.
|
||||
|
||||
@@ -58,14 +58,21 @@ Opening the view reads the author and the branches, re-reads git and runs `git f
|
||||
- **Push** runs `git push`; when git reports there is no upstream, it retries with `git push -u origin <branch>`. `Cmd+P` pushes from anywhere.
|
||||
- Both time out after 120 seconds. While one runs its button reads `Pulling…` / `Pushing…`, the console header says so, and a second pull or push is ignored. Git never prompts: no terminal prompt, no editor, no pager.
|
||||
- The result is a toast: `Pushed N commits to origin/<branch>`, `Pulled N commits from origin/<branch>`, or `Push failed` / `Pull failed` with git's first error line.
|
||||
- **Clean up** goes back to the staged state: every unstaged change is reverted to the index (`git restore --worktree -- .`, only when a tracked file has unstaged changes) and every untracked file and folder is removed (`git clean -fd`, only when there are new files). Staged changes stay, and so do ignored files (`.env`, `vendor/`, `node_modules/`). It always asks first, whatever `git.confirmDiscard` says: `Clean up N files?` with **Clean up** in the destructive style. The toast reads `Cleaned up N files` or `Clean up failed` with git's first error line; the Explorer and the open file follow the disk. The button is disabled (dimmed, arrow cursor) when nothing is unstaged or untracked, during a merge conflict, or while a pull or push runs.
|
||||
|
||||
### Commit block
|
||||
|
||||
- The **commit message**: always one lowercase line. Capitals become lowercase and line breaks become spaces as the user types or pastes, so `Enter` never starts a second line. The field grows with wrapped text from 56 to 180 points. An amber underline shows focus.
|
||||
- **Gen. Commit Message**, a small secondary button with the pass-on spark, first on the left of the footer. It asks the Claude CLI for a message for the **staged** changes and puts the answer in the message field, replacing the draft, then focuses the field. The answer goes through the same one-lowercase-line rule as typed text.
|
||||
- The prompt holds the writing rules (one sentence, no quotes, no prefix, no body, English, a verb in the third person or past tense, two separate changes joined with ` - `), three example messages, `git diff --cached --stat` in full and `git diff --cached` cut after 60 000 characters (the prompt says when it is cut).
|
||||
- It runs `claude -p --output-format text --no-session-persistence --strict-mcp-config --disable-slash-commands --tools ""` with the prompt on stdin, in the project root, with the CLI's default model and no tools; `claude` is looked up on PATH, Homebrew, `~/.local/bin` and `~/.claude/local`. The run times out after 90 seconds. The first non-empty line of the answer, without surrounding quotes or backticks, becomes the message.
|
||||
- While it runs the label reads `Generating…` and a second click is ignored. It is disabled (dimmed, arrow cursor) when nothing is staged or while it runs.
|
||||
- A failure leaves the draft alone and toasts `Couldn't generate a commit message` with the reason: `claude not found`, the CLI's first error line, or `timed out`.
|
||||
- The **author**, `user.name <user.email>` from git config.
|
||||
- A `⌘↵ commits` hint.
|
||||
- A **Commit** split button: `Commit N files`, or `Nothing staged`. It is amber when something is staged and the message is not empty, grey otherwise. The caret opens **Commit** and **Commit and push**.
|
||||
- A commit always runs `git commit -m`, also from the grey button, so git's own refusal shows in the console. On success the message clears and a toast says `Committed N files` with the subject; on failure the message stays, a toast says `Commit failed`, and an empty message takes the focus back. **Commit and push** pushes only after a successful commit.
|
||||
- Three buttons side by side: **Add, Stage & Commit** and **Commit** (`Commit N files`, or `Nothing staged`), both secondary buttons with a hairline border, and **Commit and push**, the primary one. Commit and push is amber when something is staged and the message is not empty, grey otherwise. With nothing staged Commit and Commit and push are disabled: dimmed, the arrow pointer, and a click does nothing.
|
||||
- **Add, Stage & Commit** stages every unstaged path (edits, deletions and new files) with `git add -- <paths>`, then commits as **Commit** does, without a push. With an empty message it stages nothing, runs no git, and the message field takes the focus. It is disabled when there are no changes at all, during a merge conflict (staging a conflicted file marks it resolved), and while a push or pull runs. When `git add` fails, no commit runs.
|
||||
- With files staged a commit always runs `git commit -m`, also from the grey button, so git's own refusal (an empty message) shows in the console. `Cmd+Return` always runs it, staged files or not. On success the message clears and a toast says `Committed N files` with the subject; on failure the message stays, a toast says `Commit failed`, and an empty message takes the focus back. **Commit and push** pushes only after a successful commit.
|
||||
|
||||
### Sections
|
||||
|
||||
@@ -83,6 +90,10 @@ Four colour-coded sections, each only when it has rows, in this order:
|
||||
- **Discard** reverts unstaged changes (modified and deleted files from the index, new files removed). **Discard** and **Delete** ask first (`git.confirmDiscard`, default on); **Restore** never asks. Stage and unstage never ask.
|
||||
- **Right-click** a row: **Open in editor** (left out for a deleted file), **Pass on reference**, **Copy reference**. Open in editor and Pass on reference close the view first.
|
||||
|
||||
### Bottom strip
|
||||
|
||||
230pt tall: the console left, the branches right, sharing the width equally up to 820pt each. When the room left over is at least 260pt, the **commits** list fills it, after a hairline; otherwise that room stays empty.
|
||||
|
||||
### Console
|
||||
|
||||
The bottom-left panel. Every action logs the exact git command (`$ git add -- path`) and streams its output line by line, coloured by kind: errors, hints, staged and unstaged lines of `status`, and the ref update of a push. Below the log, a `$ git` input runs typed commands, with or without a leading `git`. `clear` empties the log, a bare `log` runs `log --oneline --decorate -n 30`, and `Up` recalls earlier input. Commands, typed or from buttons, run one at a time. The log keeps the last 400 lines.
|
||||
@@ -91,6 +102,14 @@ The bottom-left panel. Every action logs the exact git command (`$ git add -- pa
|
||||
|
||||
The bottom-right panel: **local** branches, then **remote · origin**. The current branch is marked; a remote branch with a local counterpart reads `tracked`. A click switches (`switch →`); a remote branch without a local one is checked out as a new tracking branch (`checkout →`). While there are uncommitted changes, switching is locked: the header says so, the other branches dim, and a click shows a toast instead of running git.
|
||||
|
||||
**Right-click** a branch other than the current one: the menu, headed by the branch name, has one item, **Merge into <current>**, which runs `git merge --no-edit <branch>` (local and `origin/` branches alike). With uncommitted changes the item is disabled: dimmed, with the arrow and the tooltip `Commit or discard your changes first`; `Up`/`Down` skip it and a click does nothing. The current branch opens no menu. The merge always asks first, `Merge <branch> into <current>?`, and runs only on **Merge**. A merge that stops on conflicts says `Merge conflict — resolve, then commit`.
|
||||
|
||||
### Commits
|
||||
|
||||
The bottom strip's right end on a wide window, headed `[ commits ]` with the current branch muted on the right. A scrolling list of the last 30 commits of the current branch (HEAD), newest first, one row each: the short hash (amber), the subject on one line, and right-aligned `author · 3 h ago`. The relative time ticks along. Rows are read-only: no click, no hover, the arrow cursor. A repository without commits reads `no commits yet`; outside a repository `— no repository`.
|
||||
|
||||
The list is read when the view opens and after every command, with the branches.
|
||||
|
||||
### Empty states
|
||||
|
||||
- Not a repository: `— Not a git repository.`
|
||||
@@ -153,6 +172,7 @@ The second column. A standard project file tree.
|
||||
- The tree hides paths matched by `files.exclude` and, when `files.followGitignore` is on, paths ignored by git.
|
||||
- **Right-click** a file offers **Copy reference**, which copies the file's project-relative path to the clipboard (the file-level form of the editor's Copy reference).
|
||||
- A Markdown file (`.md`) also offers **Read aloud**, in its own group after the pass-on and copy items, in the Explorer. Helder reads the text with the system voice: headings, paragraphs, list items, quotes and table cells, with the markup and link URLs left out and code blocks skipped. The open file is read as it stands in the editor, unsaved edits included. A file with nothing to read shows `Nothing to read`. A new Read aloud replaces the one that is playing. A `$` is read as "dollar", except before a digit (`$5` stays "five dollars").
|
||||
- A `.log` file (any case) also offers **Tail log**, in its own group after the pass-on and copy items (after Read aloud when both apply). It opens a block at the bottom of the Explorer, under the tree, about 40% of the column high: a header with `Tail` and the file name, a close button (`Stop tailing`) on the right, and a small live terminal that runs `tail -f <path>` in the project root. One tail runs at a time: Tail log on another file ends the running tail and starts a fresh one. The close button ends the tail and removes the block. A project switch or window close ends it, and a project always opens without one. The block has no splitter and no settings.
|
||||
|
||||
---
|
||||
|
||||
@@ -245,7 +265,7 @@ The bottom pane of the fourth column.
|
||||
|
||||
### Right-click in a terminal
|
||||
|
||||
Right-clicking in the agent pane or the terminal pane shows a menu without a header line. With a selection it holds **Copy**, **Paste**, a separator, **Read aloud selection**, a separator and **Plak**; the agent pane adds a separator and **Wait what?**. Without a selection it holds only **Paste**.
|
||||
Right-clicking in the agent pane or the terminal pane shows a menu without a header line. With a selection it holds **Copy**, **Paste**, a separator, **Read aloud selection**, a separator and **Plak**; the agent pane adds a separator and **Wait what?**. Without a selection it holds only **Paste**. The Explorer's tail block holds the same items minus **Paste** and **Wait what?**, so without a selection it opens no menu.
|
||||
|
||||
**Read aloud selection** reads the selected text with the system voice, as prose with the Markdown markup left out. A selection with no prose left, such as one code block, is read as it is. Blank text reads nothing and shows the toast "Nothing to read".
|
||||
|
||||
@@ -292,7 +312,7 @@ The pointer shows what a left click does at that spot. It depends only on what l
|
||||
|
||||
- **Pointing hand** only where a left click runs an action: buttons (title-bar toggles and tools, `?`, Preview, Diff, the Git view's buttons and section headers, dialog buttons, Collapse, search chips), clickable rows (Git view file rows and switchable branches, Schema table rows, cards and relation rows, Explorer rows, search results, recent files and projects, launcher rows, symbol popup rows, context-menu items) and the project name in the title bar. Never on a view that only reacts to a right-click, a tooltip or hover.
|
||||
- **I-beam** where a click places a caret or starts a selection: the code (also below the last line), the Markdown preview, both terminals, the commit message, the Git console and every overlay input.
|
||||
- **Arrow** everywhere else: labels, headers, folder labels, the gutter, the status bar, scrims, toasts, empty states, and a disabled button such as Commit with nothing staged.
|
||||
- **Arrow** everywhere else: labels, headers, folder labels, the gutter, the status bar, scrims, toasts, empty states, a disabled button such as Commit with nothing staged, and a disabled context-menu item.
|
||||
- With an overlay open, every column behind it, and the Git view, shows the arrow; the overlay's own buttons, rows and inputs keep theirs.
|
||||
- A splitter shows a resize arrow; `Cmd` over a known PHP class name in the code shows the hand. No other pointers are used: the Schema canvas pans with the arrow, without a grab hand.
|
||||
|
||||
|
||||
@@ -110,6 +110,26 @@ After the action:
|
||||
- A deleted file closes in the File view.
|
||||
- A [notification](notifications.md) confirms each action, or says why it failed.
|
||||
|
||||
### Tail a log file
|
||||
|
||||
Right-click a `.log` file and choose **Tail log**. A block opens at the bottom of the Explorer, under the tree:
|
||||
|
||||
```text
|
||||
|-------------------------------------|
|
||||
| TAIL laravel.log x |
|
||||
|-------------------------------------|
|
||||
| [2026-11-04 10:12:01] local.INFO ...|
|
||||
| [2026-11-04 10:12:03] local.ERROR ..|
|
||||
+-------------------------------------+
|
||||
```
|
||||
|
||||
- It is a small live terminal that runs `tail -f` on the file, so new lines show up as they are written.
|
||||
- It takes about 40% of the column. It has no splitter.
|
||||
- One tail runs at a time. Tail log on another file replaces the running one.
|
||||
- Click `x` (**Stop tailing**) to end the tail and close the block.
|
||||
- Switching projects or closing the window ends the tail. A project always opens without one.
|
||||
- Select text to copy it. Right-click a selection for **Copy**, **Read aloud selection** and **Plak**.
|
||||
|
||||
### Stay up to date
|
||||
|
||||
The tree follows the disk. Helder watches the project folder and reloads the tree after a short pause when files change. `Cmd+R` reloads it by hand, together with git and the open file.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Git commit form
|
||||
|
||||
The commit form is the block at the top of the [Git](git.md) view, under its top bar. It holds the commit message, the author, and the Commit split button.
|
||||
The commit form is the block at the top of the [Git](git.md) view, under its top bar. It holds the commit message, the Gen. Commit Message button, the author, and the three commit buttons.
|
||||
|
||||
[Guide index](index.md) · Related: [Git](git.md), [Notifications](notifications.md), [Keyboard shortcuts](keyboard-shortcuts.md)
|
||||
|
||||
@@ -10,21 +10,21 @@ The commit form is the block at the top of the [Git](git.md) view, under its top
|
||||
+----------------------------------------------------------------------------+
|
||||
| (1) fix the login form_ |
|
||||
|----------------------------------------------------------------------------|
|
||||
| (2) Jonathan <jonathan@example.com> (3) Cmd+Enter commits |
|
||||
| (4) [ Commit 2 files | v ] |
|
||||
| (2) [ * Gen. Commit Message ] (3) Jonathan <jonathan@example.com> |
|
||||
| (4) Cmd+Enter commits |
|
||||
| (5) [ Add, Stage & Commit ] (6) [ Commit 2 files ] (7) [ Commit and push ] |
|
||||
+----------------------------------------------------------------------------+
|
||||
(5)
|
||||
+------------------------+
|
||||
| v Commit |
|
||||
| ^ Commit and push |
|
||||
+------------------------+
|
||||
```
|
||||
|
||||
1. **Message field**: the commit message. The grey placeholder `Commit message` shows while it is empty.
|
||||
2. **Author**: `user.name <user.email>` from your git config, read when the view opens. With no email set, only the name shows; with no name, nothing.
|
||||
3. **Hint**: `⌘↵ commits`.
|
||||
4. **Commit button**: `Commit N files`, or `Nothing staged`. The caret on its right opens the menu.
|
||||
5. **Commit menu**: **Commit** and **Commit and push**.
|
||||
2. **Gen. Commit Message button**: asks Claude to write the message for your staged changes. See [Generate a message](#generate-a-message).
|
||||
3. **Author**: `user.name <user.email>` from your git config, read when the view opens. With no email set, only the name shows; with no name, nothing.
|
||||
4. **Hint**: `⌘↵ commits`.
|
||||
5. **Add, Stage & Commit button**: stages every change, new files included, then commits. No push.
|
||||
6. **Commit button**: `Commit N files`, or `Nothing staged`. Commits without pushing.
|
||||
7. **Commit and push button**: the amber one. Commits, then pushes.
|
||||
|
||||
In the app all of row 2 to 7 is one footer line: the Gen. Commit Message button, the author and the hint on the left, the three commit buttons on the right.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -38,17 +38,30 @@ The commit form is the block at the top of the [Git](git.md) view, under its top
|
||||
- This keeps dictated or pasted text as one short subject line.
|
||||
- The draft stays in the field while the view is closed.
|
||||
|
||||
### Generate a message
|
||||
- Stage the files first. Then click **Gen. Commit Message**.
|
||||
- Helder sends the staged changes to the Claude Code CLI (`claude`, the same tool the agent terminal runs) and asks for one short sentence, such as `Adds a new button on the header to navigate to profile`. Two separate changes are joined with ` - `.
|
||||
- The answer replaces what is in the field, as one lowercase line, and the cursor goes to the field so you can edit it before you commit. Nothing is committed for you.
|
||||
- While Claude writes, the button reads `Generating…` and further clicks do nothing. It is dimmed when nothing is staged.
|
||||
- Only the staged diff is sent. A very large diff is cut after 60 000 characters; the list of changed files is always sent in full.
|
||||
- When it fails, your draft stays and a [notification](notifications.md) says `Couldn't generate a commit message`, with the reason: `claude not found` (install the Claude Code CLI), Claude's first error line (for example a sign-in problem), or `timed out` (after 90 seconds).
|
||||
|
||||
### Commit
|
||||
You can commit in three ways:
|
||||
You can commit in two ways:
|
||||
|
||||
- Click **Commit N files**.
|
||||
- Choose **Commit** from the caret menu.
|
||||
- Press `Cmd+Enter` while the view is open. This works from the message field too, but not from the console input.
|
||||
|
||||
The button is amber when at least one file is staged and the message is not empty. Otherwise it is grey. A click always runs `git commit`, also when the button is grey, so git's own refusal shows in the [console](git.md#console).
|
||||
With nothing staged **Commit N files** and **Commit and push** are dimmed and do nothing; `Cmd+Enter` still runs `git commit`. With files staged a click always runs `git commit`, also with an empty message, so git's own refusal shows in the [console](git.md#console).
|
||||
|
||||
### Commit and push
|
||||
- Choose **Commit and push** from the caret menu. It commits, and when the commit succeeds it pushes, the same as the **Push** button. See [Pull and push](git.md#pull-and-push).
|
||||
- Click **Commit and push**. It is amber when at least one file is staged and the message is not empty, grey otherwise. It commits, and when the commit succeeds it pushes, the same as the **Push** button. See [Pull and push](git.md#pull-and-push).
|
||||
|
||||
### Add, Stage & Commit
|
||||
- Click **Add, Stage & Commit** to stage every change and commit it in one go: edited, deleted and new files. It does not push.
|
||||
- With an empty message nothing is staged and nothing runs; the cursor goes to the message field.
|
||||
- It is dimmed and does nothing when there are no changes, during a merge conflict (resolve it first), or while a push or pull runs.
|
||||
- When staging fails, for example because another git process holds the index, nothing is committed. The error is in the [console](git.md#console).
|
||||
|
||||
### After a commit
|
||||
- The message field clears.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Right-click menu
|
||||
|
||||
Helder draws its own right-click menu, in the same dark style everywhere. This page lists every menu in the app: on Git view rows and the Commit button, in the Explorer, in the code, in the Diff, and in the two terminal panes.
|
||||
Helder draws its own right-click menu, in the same dark style everywhere. This page lists every menu in the app: on Git view rows and branches, in the Explorer, in the code, in the Diff, and in the two terminal panes.
|
||||
|
||||
[Guide index](index.md) · Related: [Git](git.md), [Explorer](explorer.md), [Dialogs](dialogs.md), [Pass on to Agent](pass-on-to-agent.md), [File view](file-view.md), [File view: Diff](file-view-diff.md)
|
||||
|
||||
@@ -21,7 +21,7 @@ Helder draws its own right-click menu, in the same dark style everywhere. This p
|
||||
+----------------------------------------+
|
||||
```
|
||||
|
||||
1. **Header**: what you clicked: a path, or the project name ending in `/`. Folder, code, Diff, terminal and commit menus have no header.
|
||||
1. **Header**: what you clicked: a path, or the project name ending in `/`. Folder, code, Diff and terminal menus have no header.
|
||||
2. **Highlighted item**: an amber rule on the left. The first item is highlighted when the menu opens.
|
||||
3. **Separator**: a thin line between groups of items.
|
||||
4. **Destructive item**: Delete reads in amber-deep, so it stands out.
|
||||
@@ -79,20 +79,6 @@ Right-click a file row in the [Git](git.md) view. The header is the file's path.
|
||||
|
||||
Stage, unstage, discard, delete and restore are buttons on the row itself, not menu items. See [Row actions](git.md#row-actions).
|
||||
|
||||
### Commit menu
|
||||
|
||||
Click the caret on the right of the **Commit** button in the [Git](git.md) view. The menu hangs under the caret and has no header.
|
||||
|
||||
```text
|
||||
+----------------------------------------+
|
||||
| v Commit |
|
||||
| ^ Commit and push |
|
||||
+----------------------------------------+
|
||||
```
|
||||
|
||||
- **Commit**: the same as the Commit button.
|
||||
- **Commit and push** (bold): commits, then pushes when the commit succeeded. See [Git commit form](git-commit-form.md#commit-and-push).
|
||||
|
||||
### Explorer: file
|
||||
|
||||
Right-click a file in the [Explorer](explorer.md). The header is the file's path.
|
||||
@@ -132,6 +118,16 @@ A Markdown file (`.md`) in the Explorer gets one extra group after the copy item
|
||||
|
||||
- **Read aloud**: reads the headings, paragraphs, list items, quotes and table cells aloud. Markup and link addresses are left out, and code blocks are skipped. The open file is read as it stands in the editor, unsaved edits included. A file with nothing to read shows `Nothing to read`. Reading another file stops the first one.
|
||||
|
||||
A `.log` file gets one extra group after the copy items:
|
||||
|
||||
```text
|
||||
|----------------------------------------|
|
||||
| >_ Tail log |
|
||||
|----------------------------------------|
|
||||
```
|
||||
|
||||
- **Tail log**: opens the [tail block](explorer.md#tail-a-log-file) at the bottom of the Explorer, running `tail -f` on the file. A running tail on another file stops first.
|
||||
|
||||
- **Rename file**: opens the [name prompt](dialogs.md#name-prompt) with the current name. Only the part before the extension is selected, so typing keeps the extension.
|
||||
- **Delete file**: always asks first; see [Dialogs](dialogs.md#delete-file-or-folder). The file is deleted for good, not moved to the Trash.
|
||||
|
||||
@@ -282,6 +278,8 @@ Without a selection:
|
||||
+----------------------------------------+
|
||||
```
|
||||
|
||||
The [tail block](explorer.md#tail-a-log-file) in the Explorer has the same menu without **Paste** and **Wait what?**. Without a selection it opens no menu.
|
||||
|
||||
- **Copy** (only with a selection): copies the selected terminal text.
|
||||
- **Paste**: types the clipboard text into that pane, as a normal paste would. With an empty clipboard nothing happens.
|
||||
- **Read aloud selection** (only with a selection): reads the selected text with the system voice. Markdown markup is left out. With nothing left to read, a [notification](notifications.md) says `Nothing to read`. Stop it with **Stop** in the [title bar](title-bar.md#read-aloud).
|
||||
@@ -319,7 +317,7 @@ Delete file and Delete folder always ask; no setting turns that off.
|
||||
|
||||
- [Dialogs](dialogs.md): the confirm dialog and the name prompt that menu items open.
|
||||
- [Pass on to Agent](pass-on-to-agent.md): what happens after a Pass on item.
|
||||
- [Git](git.md): the rows and the Commit button behind the git menus.
|
||||
- [Git](git.md): the rows and branches behind the git menus.
|
||||
- [Explorer](explorer.md): the rows behind the file, folder and empty-space menus.
|
||||
- [File view: Diff](file-view-diff.md): where Show diff leads.
|
||||
- [Notifications](notifications.md): the confirmations after Copy and file actions.
|
||||
|
||||
Reference in New Issue
Block a user