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:
@@ -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)))
|
||||
|
||||
Reference in New Issue
Block a user