diff --git a/Package.swift b/Package.swift index aba188f..197f3f7 100644 --- a/Package.swift +++ b/Package.swift @@ -19,6 +19,11 @@ let package = Package( exclude: ["Artwork"], resources: [.process("Resources")] ), + .testTarget( + name: "TimberTests", + dependencies: ["Timber", "TimberModel"], + path: "Tests/TimberTests" + ), .testTarget( name: "TimberModelTests", dependencies: ["TimberModel"], diff --git a/README.md b/README.md index fdc5447..c994cd8 100644 --- a/README.md +++ b/README.md @@ -19,17 +19,18 @@ managed Git worktrees. Requires the `timber` CLI and an Xcode toolchain. - Delete is two-phase: first click arms (red), second click runs `timber remove`. Any list change or selection move disarms. - `+` header button opens a `timber repo add [--name]` form. -- Failures post a macOS notification; never silently. +- Action failures post a macOS notification. - Keyboard: Up/Down move, Return activates, Esc closes form / clears filter, Ctrl+U clears. - Right-click (or Ctrl-click) the menubar icon for an Open at Login toggle and Quit; left-click toggles the popover. -Notes on parity: enumeration is implemented natively with FileManager -(`timber repo list -q` plus a worktree-root scan) instead of the bash + -globstar script, since macOS ships bash 3.2. `timber repo add` here has no -`--alias` flag, so the form has URL + Name only. +Worktree names and locations come from `timber list --json`, including custom checkout locations and worktrees created directly with Git for registered repositories. +The app opens the returned path rather than inferring a path from the worktree name. +If the CLI listing fails, the app retains its cached list. +Repository names for creation come from `timber repo list -q`. +The repository form has URL + Name only, since `timber repo add` has no `--alias` flag. ## Layout @@ -49,6 +50,7 @@ globstar script, since macOS ships bash 3.2. `timber repo add` here has no `mise run build` compiles it to `Assets.car` via `actool`, and `CFBundleIconName` in `packaging/Info.plist` points at it. - `Tests/TimberModelTests/` — unit tests for the model. +- `Tests/TimberTests/` — CLI enumeration and refresh integration tests. ## Build & run @@ -58,7 +60,7 @@ pin `DEVELOPER_DIR` to Xcode explicitly (or run ```sh mise run # builds dist/Timber.app and opens it (recommended) -mise test # swift test (TimberModel suite) +mise test # swift test (model and CLI integration suites) mise lint # SwiftLint (strict) + SwiftFormat check mise format # format Sources and Tests in place ``` diff --git a/Sources/Timber/TimberCommand.swift b/Sources/Timber/TimberCommand.swift index 395660c..77ca22c 100644 --- a/Sources/Timber/TimberCommand.swift +++ b/Sources/Timber/TimberCommand.swift @@ -2,9 +2,9 @@ import Foundation import TimberModel import UserNotifications -// Shell-out layer: runs the `timber` CLI, enumerates repos/worktrees the -// same way omarchy-timber's listScript does, opens paths in Zed, and posts -// notifications. Menubar apps launched from Finder do not inherit a shell +// Shell-out layer: runs the `timber` CLI, lists repos/worktrees, opens +// paths in Zed, and posts notifications. +// Menubar apps launched from Finder do not inherit a shell // PATH, so executables are located by searching well-known directories. enum TimberCommand { @@ -81,30 +81,10 @@ enum TimberCommand { // MARK: - Enumeration - /// Status/Todo details for known worktrees, keyed by `name@repo`. - /// Empty when `timber list --json` fails: the filesystem scan below - /// stays the source of truth for membership, so one unreadable - /// worktree hides its badges instead of failing the whole listing. - static func listDetails() -> [String: TimberListDetail] { - guard let result = try? runTimber(["list", "--json"]), result.code == 0, - let data = result.stdout.data(using: .utf8), - let rows = try? JSONDecoder().decode([TimberListDetail].self, from: data) - else { return [:] } - var details: [String: TimberListDetail] = [:] - for row in rows { - details[TimberModel.worktreeValue(name: row.name, repo: row.repo)] = row - } - return details - } - - /// Same enumeration timber's own zsh completion uses: registered repo - /// names plus a scan of the worktree root for `//**/` - /// directories containing `.git`. The scan (not `timber list`) owns - /// membership: its styled table still emits ANSI under NO_COLOR and it - /// enriches every row with git status, so one missing worktree - /// directory fails the whole listing. `timber list --json` only - /// enriches scanned rows with Status/Todo details. - static func enumerate() -> (repos: [TimberRepo], worktrees: [TimberWorktree]) { + /// The CLI owns worktree names and paths, including checkouts outside + /// Timber's default layout. A failed listing throws so callers can + /// retain the previous cache instead of treating failure as an empty list. + static func enumerate() throws -> (repos: [TimberRepo], worktrees: [TimberWorktree]) { let fm = FileManager.default var repoNames: [String] = [] if let result = try? runTimber(["repo", "list", "-q"]), result.code == 0 { @@ -120,35 +100,24 @@ enum TimberCommand { } } - let root = ProcessInfo.processInfo.environment["TIMBER_WORKTREE_ROOT"] - ?? fm.homeDirectoryForCurrentUser.appendingPathComponent("worktrees").path + let result = try runTimber(["list", "--json"]) + guard result.code == 0 else { + throw NSError( + domain: "Timber", code: Int(result.code), + userInfo: [NSLocalizedDescriptionKey: result.stderr] + ) + } + let rows = try JSONDecoder().decode([TimberListDetail].self, from: Data(result.stdout.utf8)) let gitExe = findExecutable("git") - let details = listDetails() - var worktrees: [TimberWorktree] = [] - for repo in repoNames { - let base = URL(fileURLWithPath: root).appendingPathComponent(repo) - for dir in walkDirectories(at: base, matching: repo, maxDepth: 8) { - let parent = dir.deletingLastPathComponent() - let rel = parent.path.hasPrefix(base.path + "/") - ? String(parent.path.dropFirst(base.path.count + 1)) - : "" - guard !rel.isEmpty else { continue } - let detail = details[TimberModel.worktreeValue(name: rel, repo: repo)] - worktrees.append(TimberWorktree( - name: rel, - repo: repo, - path: dir.path, - lastCommitAt: commitDate(atPath: dir.path, gitExe: gitExe), - ahead: detail?.ahead ?? 0, - behind: detail?.behind ?? 0, - merged: detail?.merged ?? false, - statusError: detail?.statusError ?? false, - todoDone: detail?.todoDone ?? 0, - todoTotal: detail?.todoTotal ?? 0 - )) - } + let worktrees = rows.map { row in + TimberWorktree( + name: row.name, repo: row.repo, path: row.path, + lastCommitAt: commitDate(atPath: row.path, gitExe: gitExe), + ahead: row.ahead, behind: row.behind, merged: row.merged, + statusError: row.statusError, todoDone: row.todoDone, todoTotal: row.todoTotal + ) } - return (repoNames.map { TimberRepo(name: $0) }, worktrees.sorted { $0.value < $1.value }) + return (repoNames.map { TimberRepo(name: $0) }, worktrees) } /// Newest commit date for recency sorting, falling back to the @@ -168,33 +137,6 @@ enum TimberCommand { return Double(result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)) } - /// Directories named `name` containing a `.git` entry, up to maxDepth - /// below (and excluding) the base itself. - private static func walkDirectories(at base: URL, matching name: String, maxDepth: Int) -> [URL] { - var found: [URL] = [] - var stack: [(URL, Int)] = [(base, 0)] - let fm = FileManager.default - while let (dir, depth) = stack.popLast() { - guard depth < maxDepth else { continue } - guard let entries = try? fm.contentsOfDirectory( - at: dir, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles] - ) else { continue } - for entry in entries { - guard (try? entry.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true else { continue } - if entry.lastPathComponent == "node_modules" { - continue - } - if entry.lastPathComponent == name { - if fm.fileExists(atPath: entry.appendingPathComponent(".git").path) { - found.append(entry) - } - } - stack.append((entry, depth + 1)) - } - } - return found - } - // MARK: - Open /// Open a path in Zed (`zed --new`), falling back to Finder `open` @@ -246,40 +188,3 @@ enum TimberCommand { } } } - -private extension TimberWorktree { - var value: String { - TimberModel.worktreeValue(name: name, repo: repo) - } -} - -/// One `timber list --json` row: the Status/Todo columns for a worktree. -/// File scope (not nested in TimberCommand) for the nesting lint. -/// Decodes defensively (missing keys default) so a newer or older timber -/// still enriches rows instead of failing the parse. -struct TimberListDetail: Decodable { - var name = "" - var repo = "" - var ahead = 0 - var behind = 0 - var merged = false - var statusError = false - var todoDone = 0 - var todoTotal = 0 - - enum CodingKeys: String, CodingKey { - case name, repo, ahead, behind, merged, statusError, todoDone, todoTotal - } - - init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - name = (try? container.decode(String.self, forKey: .name)) ?? "" - repo = (try? container.decode(String.self, forKey: .repo)) ?? "" - ahead = (try? container.decode(Int.self, forKey: .ahead)) ?? 0 - behind = (try? container.decode(Int.self, forKey: .behind)) ?? 0 - merged = (try? container.decode(Bool.self, forKey: .merged)) ?? false - statusError = (try? container.decode(Bool.self, forKey: .statusError)) ?? false - todoDone = (try? container.decode(Int.self, forKey: .todoDone)) ?? 0 - todoTotal = (try? container.decode(Int.self, forKey: .todoTotal)) ?? 0 - } -} diff --git a/Sources/Timber/TimberState.swift b/Sources/Timber/TimberState.swift index 2865617..da71747 100644 --- a/Sources/Timber/TimberState.swift +++ b/Sources/Timber/TimberState.swift @@ -16,6 +16,8 @@ final class TimberState: ObservableObject { @Published var selectedID: TimberItem.ID? @Published var cursorActive = false @Published var armedRemoveValue = "" + /// `name@repo` of a delete in flight. The row spinner reads this. + @Published var removingValue = "" @Published var repoFormOpen = false @Published var repoURL = "" @Published var repoName = "" @@ -45,12 +47,14 @@ final class TimberState: ObservableObject { /// popover — filter text, selection, and cursor stay as they are. func refreshInBackground() { background { - let (repos, worktrees) = TimberCommand.enumerate() + let snapshot = try? TimberCommand.enumerate() self.onMain { - self.repos = repos - self.worktrees = worktrees + if let (repos, worktrees) = snapshot { + self.repos = repos + self.worktrees = worktrees + self.rebuild() + } self.listing = false - self.rebuild() } } } @@ -73,12 +77,14 @@ final class TimberState: ObservableObject { armedRemoveValue = "" listing = true background { - let (repos, worktrees) = TimberCommand.enumerate() + let snapshot = try? TimberCommand.enumerate() self.onMain { - self.repos = repos - self.worktrees = worktrees + if let (repos, worktrees) = snapshot { + self.repos = repos + self.worktrees = worktrees + self.rebuild() + } self.listing = false - self.rebuild() } } } diff --git a/Sources/Timber/TimberStateActions.swift b/Sources/Timber/TimberStateActions.swift index 58ffd19..532911c 100644 --- a/Sources/Timber/TimberStateActions.swift +++ b/Sources/Timber/TimberStateActions.swift @@ -99,13 +99,14 @@ extension TimberState { private func remove(_ item: TimberItem) { busy = true + removingValue = item.value background { do { let result = try TimberCommand.runTimber(TimberModel.removeArgs(value: item.value)) self.onMain { - self.busy = false if result.code == 0 { - self.refresh() + self.worktrees.removeAll { $0.name == item.name && $0.repo == item.repo } + self.rebuild() } else { TimberCommand.notify( subject: "worktree remove", @@ -113,10 +114,13 @@ extension TimberState { failure: true ) } + self.busy = false + self.removingValue = "" } } catch { self.onMain { self.busy = false + self.removingValue = "" TimberCommand.notify(subject: "worktree remove", detail: error.localizedDescription, failure: true) } } diff --git a/Sources/Timber/TimberViews.swift b/Sources/Timber/TimberViews.swift index 8fedc4a..34ce0c2 100644 --- a/Sources/Timber/TimberViews.swift +++ b/Sources/Timber/TimberViews.swift @@ -26,7 +26,7 @@ struct TimberPopover: View { .onChange(of: state.filter) { _, _ in state.filterChanged() } .disabled(state.busy) - if state.busy { + if state.busy, state.removingValue.isEmpty { ProgressView() .scaleEffect(0.6) .frame(width: 20, height: 20) @@ -142,6 +142,10 @@ struct TimberRow: View { state.armedRemoveValue == item.value } + private var removing: Bool { + state.removingValue == item.value + } + private let iconBox: CGFloat = 22 private let iconSize: CGFloat = 14 @@ -182,54 +186,67 @@ struct TimberRow: View { // jumps and the window never clips the row when buttons // appear, while still making the hovered row obvious. HStack(spacing: 4) { - Button { - state.openInZed(item) - } label: { - Image(nsImage: TimberIcons.zed) - .renderingMode(.template) - .resizable() - .frame(width: iconSize, height: iconSize) - .foregroundStyle(.primary) - } - .buttonStyle(.plain) - .frame(width: iconBox, height: iconBox) - .help(item.kind == .open ? "Open in Zed" : "Create and open in Zed") - - Button { - state.openInHerdr(item) - } label: { - Image(nsImage: TimberIcons.herdr) - .renderingMode(.template) - .resizable() - .frame(width: iconSize, height: iconSize) - .foregroundStyle(.primary) - } - .buttonStyle(.plain) - .frame(width: iconBox, height: iconBox) - .help(item.kind == .open ? "Open in Herdr" : "Create in Herdr") + HStack(spacing: 4) { + Button { + state.openInZed(item) + } label: { + Image(nsImage: TimberIcons.zed) + .renderingMode(.template) + .resizable() + .frame(width: iconSize, height: iconSize) + .foregroundStyle(.primary) + } + .buttonStyle(.plain) + .frame(width: iconBox, height: iconBox) + .disabled(!selected || state.busy) + .help(item.kind == .open ? "Open in Zed" : "Create and open in Zed") - if item.kind == .open { Button { - state.armOrRemove(item) + state.openInHerdr(item) } label: { - Image(systemName: "trash") + Image(nsImage: TimberIcons.herdr) + .renderingMode(.template) + .resizable() .frame(width: iconSize, height: iconSize) + .foregroundStyle(.primary) } .buttonStyle(.plain) .frame(width: iconBox, height: iconBox) - .foregroundStyle(armed ? .red : .primary) - .help(armed ? "Click again to remove \(item.value)" : "Remove \(item.value)") - } else { - // Invisible placeholder keeps the cluster width stable. - Image(systemName: "trash") - .frame(width: iconSize, height: iconSize) - .frame(width: iconBox, height: iconBox) - .opacity(0) + .disabled(!selected || state.busy) + .help(item.kind == .open ? "Open in Herdr" : "Create in Herdr") + } + .opacity(selected ? 1 : 0.2) + + Group { + if item.kind == .open { + if removing { + ProgressView() + .controlSize(.small) + .frame(width: iconBox, height: iconBox) + } else { + Button { + state.armOrRemove(item) + } label: { + Image(systemName: "trash") + .frame(width: iconSize, height: iconSize) + } + .buttonStyle(.plain) + .frame(width: iconBox, height: iconBox) + .foregroundStyle(armed ? .red : .primary) + .disabled(!selected || state.busy) + .help(armed ? "Click again to remove \(item.value)" : "Remove \(item.value)") + } + } else { + // Invisible placeholder keeps the cluster width stable. + Image(systemName: "trash") + .frame(width: iconSize, height: iconSize) + .frame(width: iconBox, height: iconBox) + .opacity(0) + } } + .opacity(selected || removing ? 1 : 0.2) } .layoutPriority(1) - .opacity(selected ? 1 : 0.2) - .disabled(!selected || state.busy) } .frame(height: 32) .contentShape(Rectangle()) diff --git a/Sources/TimberModel/TimberListDetail.swift b/Sources/TimberModel/TimberListDetail.swift new file mode 100644 index 0000000..7cebcb3 --- /dev/null +++ b/Sources/TimberModel/TimberListDetail.swift @@ -0,0 +1,32 @@ +import Foundation + +/// One `timber list --json` row. Identity and location are required. +/// Optional Status/Todo fields default for compatibility across CLI versions. +public struct TimberListDetail: Decodable { + public var name = "" + public var repo = "" + public var path: String + public var ahead = 0 + public var behind = 0 + public var merged = false + public var statusError = false + public var todoDone = 0 + public var todoTotal = 0 + + enum CodingKeys: String, CodingKey { + case name, repo, path, ahead, behind, merged, statusError, todoDone, todoTotal + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + name = try container.decode(String.self, forKey: .name) + repo = try container.decode(String.self, forKey: .repo) + path = try container.decode(String.self, forKey: .path) + ahead = (try? container.decode(Int.self, forKey: .ahead)) ?? 0 + behind = (try? container.decode(Int.self, forKey: .behind)) ?? 0 + merged = (try? container.decode(Bool.self, forKey: .merged)) ?? false + statusError = (try? container.decode(Bool.self, forKey: .statusError)) ?? false + todoDone = (try? container.decode(Int.self, forKey: .todoDone)) ?? 0 + todoTotal = (try? container.decode(Int.self, forKey: .todoTotal)) ?? 0 + } +} diff --git a/Tests/TimberTests/TimberEnumerationTests.swift b/Tests/TimberTests/TimberEnumerationTests.swift new file mode 100644 index 0000000..351b3d1 --- /dev/null +++ b/Tests/TimberTests/TimberEnumerationTests.swift @@ -0,0 +1,113 @@ +import Combine +import Foundation +@testable import Timber +import TimberModel +import XCTest + +final class TimberEnumerationTests: XCTestCase { + func testEnumerationUsesCLIIdentitiesAndPathsOutsideManagedLayout() throws { + let json = """ + [ + {"name":"feature/topic","repo":"sample","path":"/custom/checkouts/review copy", + "ahead":2,"behind":1,"todoDone":1,"todoTotal":3}, + {"name":"other/review copy","repo":"sample","path":"/elsewhere/review copy", + "statusError":true}, + {"name":"standard","repo":"sample","path":"/worktrees/sample/standard/sample","merged":true} + ] + """ + try withTimber(listJSON: json) { + let (repos, worktrees) = try TimberCommand.enumerate() + XCTAssertEqual(repos, [TimberRepo(name: "sample")]) + let items = TimberModel.itemsForTerm(repos: repos, worktrees: worktrees, term: "", sort: .worktree) + XCTAssertEqual(items, [ + TimberItem( + kind: .open, name: "feature/topic", repo: "sample", value: "feature/topic@sample", + path: "/custom/checkouts/review copy", statusText: "↑2 ↓1", todoText: "1/3" + ), + TimberItem( + kind: .open, name: "other/review copy", repo: "sample", value: "other/review copy@sample", + path: "/elsewhere/review copy", statusText: "error" + ), + TimberItem( + kind: .open, name: "standard", repo: "sample", value: "standard@sample", + path: "/worktrees/sample/standard/sample", statusText: "merged" + ), + ]) + } + } + + func testEnumerationDistinguishesEmptyListingFromFailedListing() throws { + try withTimber(listJSON: "[]") { + let (_, worktrees) = try TimberCommand.enumerate() + XCTAssertTrue(worktrees.isEmpty) + } + try withTimber(listJSON: "[]", exitCode: 1) { + XCTAssertThrowsError(try TimberCommand.enumerate()) + } + try withTimber(listJSON: "not JSON") { + XCTAssertThrowsError(try TimberCommand.enumerate()) + } + try withTimber(listJSON: #"[{"name":"feature","repo":"sample"}]"#) { + XCTAssertThrowsError(try TimberCommand.enumerate()) + } + } + + func testFailedBackgroundRefreshPreservesVisibleRowsAndFilter() throws { + try withTimber(listJSON: "[]", exitCode: 1) { + let state = TimberState() + state.repos = [TimberRepo(name: "sample")] + state.worktrees = [TimberWorktree(name: "feature", repo: "sample", path: "/custom/checkout")] + state.filter = "feature" + state.rebuild() + state.cursorActive = true + let originalItems = state.items + let originalSelection = state.selectedID + let completed = expectation(description: "Background refresh completes") + let subscription = state.$listing.dropFirst().sink { listing in + if !listing { + completed.fulfill() + } + } + defer { subscription.cancel() } + + state.refreshInBackground() + wait(for: [completed], timeout: 5) + + XCTAssertEqual(state.items, originalItems) + XCTAssertEqual(state.worktrees, [TimberWorktree(name: "feature", repo: "sample", path: "/custom/checkout")]) + XCTAssertEqual(state.repos, [TimberRepo(name: "sample")]) + XCTAssertEqual(state.filter, "feature") + XCTAssertEqual(state.selectedID, originalSelection) + XCTAssertTrue(state.cursorActive) + } + } + + private func withTimber(listJSON: String, exitCode: Int = 0, body: () throws -> Void) throws { + let fm = FileManager.default + let directory = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try fm.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: directory) } + try Data(listJSON.utf8).write(to: directory.appendingPathComponent("listing.json")) + let script = """ + #!/bin/sh + case "$1" in + repo) printf 'sample\\n' ;; + list) /bin/cat "$(/usr/bin/dirname "$0")/listing.json"; exit \(exitCode) ;; + *) exit 2 ;; + esac + """ + let executable = directory.appendingPathComponent("timber") + try Data(script.utf8).write(to: executable) + try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) + let originalPATH = ProcessInfo.processInfo.environment["PATH"] + setenv("PATH", directory.path, 1) + defer { + if let originalPATH { + setenv("PATH", originalPATH, 1) + } else { + unsetenv("PATH") + } + } + try body() + } +} diff --git a/mise.toml b/mise.toml index 2029960..76ad962 100644 --- a/mise.toml +++ b/mise.toml @@ -63,7 +63,7 @@ codesign --verify --verbose dist/Timber.app """ [tasks.test] -description = "Run the TimberModel test suite" +description = "Run the model and CLI integration test suites" run = """ set -euo pipefail if [ -z "${DEVELOPER_DIR:-}" ] && [ -d /Applications/Xcode.app ]; then