Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
14 changes: 8 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <url> [--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

Expand All @@ -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

Expand All @@ -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
```
Expand Down
141 changes: 23 additions & 118 deletions Sources/Timber/TimberCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 `<root>/<repo>/**/<repo>`
/// 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 {
Expand All @@ -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
Expand All @@ -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`
Expand Down Expand Up @@ -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
}
}
22 changes: 14 additions & 8 deletions Sources/Timber/TimberState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ""
Expand Down Expand Up @@ -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()
}
}
}
Expand All @@ -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()
}
}
}
Expand Down
8 changes: 6 additions & 2 deletions Sources/Timber/TimberStateActions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,24 +99,28 @@ 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",
detail: Self.lastLine(result.stderr) ?? "exit \(result.code)",
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)
}
}
Expand Down
Loading
Loading