From 61c92baef14b129075ab63328c0a6017e64c1683 Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Sun, 20 Sep 2026 21:03:12 -0500 Subject: [PATCH] First draft of the Timber macOS menubar app This is the first draft of the Timber macOS menubar frontend to the timber CLI, ported from omarchy-timber. --- .github/workflows/ci.yml | 24 ++ .github/workflows/release.yml | 40 ++ .gitignore | 17 + .swiftformat | 8 + .swiftlint.yaml | 27 ++ Package.swift | 28 ++ README.md | 65 +++- Sources/Timber/Artwork/herdr.svg | 5 + Sources/Timber/Artwork/zed.svg | 3 + Sources/Timber/Resources/herdr.png | Bin 0 -> 256 bytes Sources/Timber/Resources/herdr@2x.png | Bin 0 -> 508 bytes Sources/Timber/Resources/herdr@3x.png | Bin 0 -> 745 bytes Sources/Timber/Resources/zed.png | Bin 0 -> 365 bytes Sources/Timber/Resources/zed@2x.png | Bin 0 -> 589 bytes Sources/Timber/Resources/zed@3x.png | Bin 0 -> 748 bytes Sources/Timber/TimberApp.swift | 348 ++++++++++++++++++ Sources/Timber/TimberCommand.swift | 206 +++++++++++ Sources/Timber/TimberState.swift | 154 ++++++++ Sources/Timber/TimberStateActions.swift | 162 ++++++++ Sources/Timber/main.swift | 8 + Sources/TimberModel/TimberModel.swift | 262 +++++++++++++ Tests/TimberModelTests/TimberModelTests.swift | 224 +++++++++++ mise.toml | 64 ++++ packaging/Info.plist | 20 + 24 files changed, 1664 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 .swiftformat create mode 100644 .swiftlint.yaml create mode 100644 Package.swift create mode 100644 Sources/Timber/Artwork/herdr.svg create mode 100644 Sources/Timber/Artwork/zed.svg create mode 100644 Sources/Timber/Resources/herdr.png create mode 100644 Sources/Timber/Resources/herdr@2x.png create mode 100644 Sources/Timber/Resources/herdr@3x.png create mode 100644 Sources/Timber/Resources/zed.png create mode 100644 Sources/Timber/Resources/zed@2x.png create mode 100644 Sources/Timber/Resources/zed@3x.png create mode 100644 Sources/Timber/TimberApp.swift create mode 100644 Sources/Timber/TimberCommand.swift create mode 100644 Sources/Timber/TimberState.swift create mode 100644 Sources/Timber/TimberStateActions.swift create mode 100644 Sources/Timber/main.swift create mode 100644 Sources/TimberModel/TimberModel.swift create mode 100644 Tests/TimberModelTests/TimberModelTests.swift create mode 100644 mise.toml create mode 100644 packaging/Info.plist diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..769aa3d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + pull_request: + +jobs: + verify: + name: Lint, build, and test + runs-on: macos-latest + steps: + - name: Check out + uses: actions/checkout@v4 + + - name: Install tools + uses: jdx/mise-action@v2 + + - name: Lint and format check + run: mise run lint + + - name: Build app bundle + run: mise run build + + - name: Run tests + run: mise run test diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..a2a06d3 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,40 @@ +name: Release + +on: + push: + tags: + - "v*" + +permissions: + contents: write + +jobs: + release: + name: Build and attach app bundle + runs-on: macos-latest + steps: + - name: Check out + uses: actions/checkout@v4 + + - name: Install tools + uses: jdx/mise-action@v2 + + - name: Stamp version from tag + run: | + set -euo pipefail + VERSION="${GITHUB_REF_NAME#v}" + /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $VERSION" packaging/Info.plist + /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $VERSION" packaging/Info.plist + grep -A1 CFBundleShortVersionString packaging/Info.plist | head -n 2 + + - name: Package app bundle + run: mise run package + + - name: Create release with asset + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + gh release create "$GITHUB_REF_NAME" dist/Timber.zip \ + --title "$GITHUB_REF_NAME" \ + --generate-notes diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..db4d40e --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +# SwiftPM build products and caches +.build/ +.swiftpm/ + +# Packaged app output (built by `make build`) +dist/ + +# Xcode +*.xcodeproj/ +*.xcworkspace/ +xcuserdata/ +DerivedData/ +*.o +*.d + +# macOS +.DS_Store diff --git a/.swiftformat b/.swiftformat new file mode 100644 index 0000000..ebc2140 --- /dev/null +++ b/.swiftformat @@ -0,0 +1,8 @@ +--swiftversion 6.0 +--indent 4 +--maxwidth 120 +--wraparguments before-first +--wrapparameters before-first +--wrapcollections before-first +--ifdef no-indent +--disable unusedArguments diff --git a/.swiftlint.yaml b/.swiftlint.yaml new file mode 100644 index 0000000..7916b9b --- /dev/null +++ b/.swiftlint.yaml @@ -0,0 +1,27 @@ +opt_in_rules: + - sorted_imports + - modifier_order + - redundant_nil_coalescing + - force_unwrapping + +disabled_rules: + - todo + - trailing_comma + +excluded: + - .build + - dist + - DerivedData + +line_length: 120 +identifier_name: + min_length: 2 + excluded: + - id + - x + - y + +force_unwrapping: + severity: error + +reporter: emoji diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..aba188f --- /dev/null +++ b/Package.swift @@ -0,0 +1,28 @@ +// swift-tools-version: 5.9 +import PackageDescription + +let package = Package( + name: "Timber", + platforms: [.macOS(.v14)], + targets: [ + // Pure model logic (filter, items, argv), no UI/process deps. + .target( + name: "TimberModel", + path: "Sources/TimberModel" + ), + // SwiftUI menubar frontend to the `timber` CLI. + // Requires an Xcode toolchain (SwiftUI macros). + .executableTarget( + name: "Timber", + dependencies: ["TimberModel"], + path: "Sources/Timber", + exclude: ["Artwork"], + resources: [.process("Resources")] + ), + .testTarget( + name: "TimberModelTests", + dependencies: ["TimberModel"], + path: "Tests/TimberModelTests" + ), + ] +) diff --git a/README.md b/README.md index d50bd14..8755c48 100644 --- a/README.md +++ b/README.md @@ -1 +1,64 @@ -# macos-timber \ No newline at end of file +# Timber — macOS menubar frontend to `timber` + +A macOS menubar port of [omarchy-timber](https://github.com/nnutter/omarchy-timber) +(the QuickShell bar widget): a timber icon in the menubar plus a popover for +managed Git worktrees. Requires the `timber` CLI and an Xcode toolchain. + +## Behavior (mirrors Panel.qml) + +- Popover lists existing worktrees as `name@repo` rows, with a fuzzy filter + field (`type worktree@repo`). `@` narrows by repo, e.g. `f@scribble`. +- Typing a qualified `name@repo` that does not exist yet offers a `+` row + to create it (`timber create --no-herdr`), then opens it in Zed. +- Row click or Return opens the worktree in Zed (`zed --new`). +- Selected rows show Zed / Herdr / delete buttons. Herdr runs + `timber herdr space --new` (or creates with `--herdr`) and posts a + notification instead of opening Zed. +- 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. +- Keyboard: Up/Down move, Return activates, Esc closes form / clears + filter, Ctrl+U clears. +- Right-click (or Ctrl-click) the menubar icon for a Quit menu; + 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. + +## Layout + +- `Sources/Timber/TimberApp.swift` — AppKit status item + (left-click popover, right-click Quit menu), popover UI, action state. +- `Sources/Timber/main.swift` — plain AppKit entry point (no + SwiftUI App scene, so no stray windows). +- `Sources/Timber/TimberCommand.swift` — `timber`/`zed` + processes, enumeration, notifications. +- `Sources/Timber/Resources/` — Zed/Herdr action icons, + rasterized from upstream `zed.svg`/`herdr.svg` (originals kept in + `Artwork/`; the Herdr glyph was stripped of its light-mode background + and whitened so both render as monochrome template images). +- `Sources/TimberModel/TimberModel.swift` — pure filter/argv logic ported + from `TimberModel.js`, UI-independent. +- `Tests/TimberModelTests/` — unit tests for the model. + +## Build & run + +Your `xcode-select` may point at the Command Line Tools; the mise tasks +pin `DEVELOPER_DIR` to Xcode explicitly (or run +`sudo xcode-select -s /Applications/Xcode.app` once). + +```sh +mise run # builds dist/Timber.app and opens it (recommended) +mise test # swift test (TimberModel suite) +mise lint # SwiftLint (strict) + SwiftFormat check +mise format # format Sources and Tests in place +``` + +`mise run` ships a real `.app` bundle (with `LSUIElement`, so no Dock +icon). That also matters for notifications: `UNUserNotificationCenter` +traps in a raw binary, so the app posts native notifications only from +the bundle and falls back to `osascript display notification` otherwise +(e.g. `swift run Timber`). diff --git a/Sources/Timber/Artwork/herdr.svg b/Sources/Timber/Artwork/herdr.svg new file mode 100644 index 0000000..c0486a0 --- /dev/null +++ b/Sources/Timber/Artwork/herdr.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Sources/Timber/Artwork/zed.svg b/Sources/Timber/Artwork/zed.svg new file mode 100644 index 0000000..06b5c18 --- /dev/null +++ b/Sources/Timber/Artwork/zed.svg @@ -0,0 +1,3 @@ + + + diff --git a/Sources/Timber/Resources/herdr.png b/Sources/Timber/Resources/herdr.png new file mode 100644 index 0000000000000000000000000000000000000000..cbcf766ce478f6707f351550eeb7dda547bb2e73 GIT binary patch literal 256 zcmeAS@N?(olHy`uVBq!ia0vp^d?3uh1|;P@bT0xawj^(N7l!{JxM1({$v}~o0P8TyRx_{=>DntPm=@=SQ{|bHCS$7 zUG_?-f@xo)-;^Vg7yO<0e=x~4raxfV^XJuyvc}q1Qfti%jhn7aBo>Jeclj=G3lbiffAET+Daxz!4xnmVq238(Aom^z>it7p_Z@oq)!QTMBz@d+Az9WN5=Qm55L^@o4*v!R?P z)zw&^RcF=jv7T2it2flOqRd{zrq}Te->J{kH|nD(?@M(s?B>)9=FpLo-~=!f_iJPw zoq!ryhdu>HfN5YV?Ct?q^QyM(Sg3Vi3D_5pmVpDn-UhR~z_$o&6}S(41|B!_n1-gqIl%;9vYAsU0#FYF3snV6Wf&Z-DppnSBiYdJj$le@ y0eDzduo7xgZ>mc>I)~c`UpG5+SIo}ELN);Es7>n7A4d!T0000~L%@dzanwyJ)db zb+hx$JMVq-?d*({l9G~=l9Eya&O!vJm((O_#5s4vKiej$SyHv6*OIO{=iXY(R}#Pp zU;-Eint*k{AXE7boB=BTg~_eJaiAHP2P_6YN0s zKAU0o&y+#u4Zh4XaM_#P4Xgnwfcd~$U^x5-yv~Ahnp_0jF0!;kKqt^kP`4AnA)qlY zE(7!t)N}{X?N{RHFPkJL zGfZB-lfV+7-?zU3Km6}^Knp=B0Nf;a(Xzh%6`1Yg3Xu&r;+k~8od~g3U@q_ssPM6; zfWyERpc>djP^T9{<1PZL^UV|^uF>|0u}6WWz}<+xcHjsw3S0+Xg!;ySmB87!CSw^T z$k=Ga*vEd-D0;k^{2G1*Gypr9x@G;f(H%(yJy~EcL0xwM#|XBpDqtV*J*i-vFGO98 zn0%b1bCNDeS}5s*q>YjuN$QrA_%k}~p#)ej=}DZ}ax!g3opVnmbxQhGemg~c#0>;$ zB{fQ_m$XXK3P}x;YKjc|KkzR{7YX*mQn5NX_epBA&?VB3SQvu4`7KEsEcE7Bh(zI>`v?q3S{Bir bNvih;cv;RWLzwrL00000NkvXXu0mjfma$E7 literal 0 HcmV?d00001 diff --git a/Sources/Timber/Resources/zed.png b/Sources/Timber/Resources/zed.png new file mode 100644 index 0000000000000000000000000000000000000000..7315fbb82589276101c26443bff842e30afb274c GIT binary patch literal 365 zcmV-z0h0cSP)3) zfMS`#I`tO5K$O_oSnNWIh!(D#t92Ym zGFuWzGDz|%$)K4}N^%doSiQtBU{Y0YF~iSx zt>V!fwb|?4iSv8h#u47*4sKx^O_IH;+J}`s#BV&q3tYu^J82zv=b?XKRei%T#u(v# zk{kV87k1n!&JMr9yy*xMOk$@@8Q8yMq%XP1HNz${P;*wZ^Rn+fJ@jGZ}~ z?w7_oz^A}_VAI!Co7kdm3TS3qz*Y^pEH0-N=IOlxLVYTr$!G%{z&?W&5R zMN?&Otf~z72K)$MVH&rA&%iA&kg_`C?XSL3D*l7)RdeBK)H|NC5JquP->hP3mwo~( zX7(rLtncC3gnAB=a7V8V8O8Z6viMtu$09DRm{a bB^~?=nO?Eu#j00000NkvXXu0mjf61@Vk literal 0 HcmV?d00001 diff --git a/Sources/Timber/Resources/zed@3x.png b/Sources/Timber/Resources/zed@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..a4682e64a3be52b04e56140433faf78e3e440d1e GIT binary patch literal 748 zcmVnmHUcye(mB))nhFVwW%!aAUw}au1xx@NX7(m-VwoL1ozp*VC+C6Vz-wSCZgQC%4Zh@2;9%%;6Hp3dp~cE* z-OSd#8&^2D0mCnx!jMo7^aJp~jkmmql4gMgN)%3%3WJ*2BCr^I=5}%(AF}jLdaA6C zmhF>isw78~!YygS*#K5tByy`XXohg_0?xbf_oC~R3jLtN9aLdZ7w#qesEh)46%w!( znD(#edTF7*0qm!H2oQ$!ax#xz=Jf9=5j5(zH==MJ6X>Hc`U5;Mvxfya^A%G};S3}v z!^)ha!z`RAWdf}m5;A}`0TQ?PTQ~k1Hbzu;2bhyIS0Td@cU?_#8Z)z#QHGcnG!C>X z!RuGzpO?t0k7z;ftLN(J2hcXN`?+RiJscQ@f(H;`Lt`KvPd{kWARW_AP)XC;c^o}k zGa~?!UO1*-CTTbDlkOn_z-QoTeRw^cpnJFhur1?MT->x0000: NSHostingView { + var onLayout: ((NSSize) -> Void)? + + required init(rootView: Content) { + super.init(rootView: rootView) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func layout() { + super.layout() + onLayout?(fittingSize) + } +} + +/// Action icons, loaded from the bundled PNGs by explicit URL (proven to +/// resolve) instead of named lookup, with every scale wired so Retina +/// picks the right representation. +enum TimberIcons { + static let zed = load("zed") + static let herdr = load("herdr") + + private static func load(_ name: String) -> NSImage { + let image = NSImage() + for scale in ["@3x", "@2x", ""] { + guard let url = Bundle.module.url(forResource: "\(name)\(scale)", withExtension: "png"), + let src = NSImage(contentsOf: url) + else { continue } + for rep in src.representations { + rep.size = NSSize(width: 14, height: 14) + image.addRepresentation(rep) + } + } + image.size = NSSize(width: 14, height: 14) + return image + } +} + +final class AppDelegate: NSObject, NSApplicationDelegate { + private var statusItem: NSStatusItem? + private var popover: NSPopover? + private let state = TimberState() + private var refreshTimer: Timer? + + private let popoverWidth: CGFloat = 400 + private let backgroundRefreshInterval: TimeInterval = 60 + + func applicationDidFinishLaunching(_ notification: Notification) { + // Menubar-only even as a raw binary (no .app bundle). + NSApplication.shared.setActivationPolicy(.accessory) + + let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) + if let button = item.button { + button.image = NSImage(systemSymbolName: "arrow.triangle.branch", accessibilityDescription: "Timber") + button.image?.isTemplate = true + button.action = #selector(statusItemClicked(_:)) + button.sendAction(on: [.leftMouseUp, .rightMouseUp]) + } + statusItem = item + + let hostingView = SizingHostingView(rootView: TimberPopover(state: state)) + let viewController = NSViewController() + viewController.view = hostingView + let popover = NSPopover() + popover.behavior = .transient + popover.contentViewController = viewController + popover.contentSize = NSSize(width: popoverWidth, height: 160) + hostingView.onLayout = { [weak popover, popoverWidth] size in + guard let popover, popover.isShown, size.height > 0, + abs(popover.contentSize.height - size.height) > 0.5 + else { return } + popover.contentSize = NSSize(width: popoverWidth, height: size.height) + } + self.popover = popover + + // Keep the list warm so the popover is ready on open: one load + // now, then a quiet reload (filter/selection untouched) every + // minute. The poll pauses while the popover is shown so rows never + // shift under the cursor; opening the popover still does a full + // refresh. + state.refreshInBackground() + refreshTimer = Timer.scheduledTimer( + withTimeInterval: backgroundRefreshInterval, + repeats: true + ) { [weak self] _ in + guard let self, self.popover?.isShown != true else { return } + state.refreshInBackground() + } + } + + @objc private func statusItemClicked(_ sender: Any?) { + let secondary = NSApp.currentEvent.map { $0.type == .rightMouseUp } ?? false + switch TimberModel.statusItemClickAction(isSecondaryClick: secondary) { + case .showContextMenu: + showContextMenu() + case .togglePopover: + togglePopover() + } + } + + private func togglePopover() { + guard let button = statusItem?.button, let popover else { return } + if popover.isShown { + popover.performClose(nil) + } else { + // Show the warmed cache instantly, then catch up quietly: the + // background poll preserves selection by row id, so the list + // never blanks out or visibly reloads on open. + state.presentFromCache() + state.refreshInBackground() + popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY) + popover.contentViewController?.view.window?.makeKey() + } + } + + private func showContextMenu() { + guard let button = statusItem?.button, let popover else { return } + popover.performClose(nil) + let menu = NSMenu() + menu.addItem(NSMenuItem( + title: "Quit Timber", + action: #selector(NSApplication.terminate(_:)), + keyEquivalent: "q" + )) + menu.popUp(positioning: nil, at: NSPoint(x: 0, y: button.bounds.height), in: button) + } +} + +// Note: there is deliberately no SwiftUI App scene here. The entry point +// is main.swift (plain AppKit lifecycle); a Settings scene would open a +// blank window at launch. + +// MARK: - Views + +struct TimberPopover: View { + @ObservedObject var state: TimberState + @FocusState private var filterFocused: Bool + @FocusState private var formFocused: Bool + + private let maxRows = 8 + private let rowHeight: CGFloat = 32 + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 8) { + TextField("type worktree@repo", text: $state.filter) + .textFieldStyle(.roundedBorder) + .focused($filterFocused) + .onSubmit { state.primaryAction() } + .onChange(of: state.filter) { _, _ in state.filterChanged() } + .disabled(state.busy) + + if state.busy { + ProgressView() + .scaleEffect(0.6) + .frame(width: 20, height: 20) + } + + Button(state.repoFormOpen ? "−" : "+") { + state.repoFormOpen.toggle() + } + .help(state.repoFormOpen ? "Close repository form" : "Add repository (timber repo add)") + .disabled(state.busy) + } + + if state.repoFormOpen { + TextField("Remote URL or path", text: $state.repoURL) + .textFieldStyle(.roundedBorder) + .focused($formFocused) + .onSubmit { state.submitRepoForm() } + .disabled(state.busy) + TextField("Name (optional, derived from URL)", text: $state.repoName) + .textFieldStyle(.roundedBorder) + .focused($formFocused) + .onSubmit { state.submitRepoForm() } + .disabled(state.busy) + HStack(spacing: 8) { + Button(state.busy ? "Adding…" : "Add repository") { + state.submitRepoForm() + } + .disabled(state.busy) + Button("Cancel") { + state.repoFormOpen = false + } + .disabled(state.busy) + } + } + + if state.listing { + Text("Loading worktrees…") + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .center) + } else if state.items.isEmpty { + Text(state.worktrees.isEmpty + ? "No worktrees yet — type name@repo to create one" + : "No matches") + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .center) + .multilineTextAlignment(.center) + } else { + ScrollView { + LazyVStack(spacing: 4) { + ForEach(state.items) { item in + TimberRow(state: state, item: item) + } + } + } + .frame(maxHeight: CGFloat(maxRows) * rowHeight) + } + } + .padding() + .frame(width: 400) + .onAppear { + filterFocused = true + } + .onKeyPress(.upArrow) { state.move(-1); return .handled } + .onKeyPress(.downArrow) { state.move(1); return .handled } + .onKeyPress(.escape) { + if formFocused { + return .ignored + } + if state.repoFormOpen { + state.repoFormOpen = false + } else if !state.filter.isEmpty { + state.clearFilter() + } + return .handled + } + .onKeyPress(characters: CharacterSet(charactersIn: "u"), phases: .down) { press in + guard press.modifiers == .control, !formFocused else { return .ignored } + state.clearFilter() + return .handled + } + } +} + +struct TimberRow: View { + @ObservedObject var state: TimberState + let item: TimberItem + + private var selected: Bool { + state.cursorActive && state.selectedID == item.id + } + + private var armed: Bool { + state.armedRemoveValue == item.value + } + + private let iconBox: CGFloat = 22 + private let iconSize: CGFloat = 14 + + var body: some View { + HStack(spacing: 6) { + RoundedRectangle(cornerRadius: 1.5) + .fill(Color.accentColor) + .frame(width: 3, height: 20) + .opacity(selected ? 1 : 0) + + Text((item.kind == .create ? "+ " : "") + item.value) + .lineLimit(1) + .truncationMode(.tail) + .opacity(item.kind == .create && !selected ? 0.72 : 1) + + Spacer(minLength: 8) + + // The action cluster is always in the layout (hidden when the + // row is not selected) so the popover width never jumps and + // the window never clips the row when buttons appear. + 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") + + if item.kind == .open { + Button { + state.armOrRemove(item) + } label: { + Image(systemName: "trash") + .frame(width: iconSize, height: iconSize) + } + .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) + } + } + .layoutPriority(1) + .opacity(selected ? 1 : 0) + .disabled(!selected || state.busy) + } + .frame(height: 32) + .contentShape(Rectangle()) + .onHover { hovering in + if hovering { + state.select(id: item.id) + } + } + .onTapGesture { + state.clickActivate(item) + } + } +} diff --git a/Sources/Timber/TimberCommand.swift b/Sources/Timber/TimberCommand.swift new file mode 100644 index 0000000..c784f6e --- /dev/null +++ b/Sources/Timber/TimberCommand.swift @@ -0,0 +1,206 @@ +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 +// PATH, so executables are located by searching well-known directories. + +enum TimberCommand { + struct RunResult { + let code: Int32 + let stdout: String + let stderr: String + } + + private static let searchDirs = [ + "/opt/homebrew/bin", + "/usr/local/bin", + "/opt/local/bin", + FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".local/bin").path, + "/usr/bin", + "/bin", + ] + + /// Locate an executable, honoring the inherited PATH first (covers + /// `swift run` / Terminal launches) then well-known install dirs. + static func findExecutable(_ name: String) -> URL? { + if name.contains("/") { + let url = URL(fileURLWithPath: name) + if FileManager.default.isExecutableFile(atPath: url.path) { + return url + } + return nil + } + let pathDirs = (ProcessInfo.processInfo.environment["PATH"] ?? "").split(separator: ":").map(String.init) + for dir in pathDirs + searchDirs { + let url = URL(fileURLWithPath: dir).appendingPathComponent(name) + if FileManager.default.isExecutableFile(atPath: url.path) { + return url + } + } + return nil + } + + /// Run `timber `, capturing output. Throws if timber is missing + /// or the process cannot start. + @discardableResult + static func runTimber(_ args: [String]) throws -> RunResult { + guard let exe = findExecutable("timber") else { + let message = "timber executable not found in PATH" + + " or /opt/homebrew/bin, /usr/local/bin, ~/.local/bin" + throw NSError( + domain: "Timber", code: 1, + userInfo: [NSLocalizedDescriptionKey: message] + ) + } + return try run(exe, args: args) + } + + static func run(_ exe: URL, args: [String]) throws -> RunResult { + let proc = Process() + proc.executableURL = exe + proc.arguments = args + // Children (notably `timber herdr`, which shells out to `herdr`) + // inherit this PATH, so augment it: GUI launches provide only + // /usr/bin:/bin:/usr/sbin:/sbin. + var env = ProcessInfo.processInfo.environment + env["PATH"] = TimberModel.childPATH(current: env["PATH"], extraDirs: searchDirs) + proc.environment = env + let outPipe = Pipe() + let errPipe = Pipe() + proc.standardOutput = outPipe + proc.standardError = errPipe + try proc.run() + proc.waitUntilExit() + let out = String(data: outPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" + let err = String(data: errPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" + return RunResult(code: proc.terminationStatus, stdout: out, stderr: err) + } + + // MARK: - Enumeration + + /// Same enumeration timber's own zsh completion uses: registered repo + /// names plus a scan of the worktree root for `//**/` + /// directories containing `.git`. `timber list` is avoided on purpose — + /// 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. + static func enumerate() -> (repos: [TimberRepo], worktrees: [TimberWorktree]) { + let fm = FileManager.default + var repoNames: [String] = [] + if let result = try? runTimber(["repo", "list", "-q"]), result.code == 0 { + repoNames = result.stdout.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + } + if repoNames.isEmpty { + let dataHome = ProcessInfo.processInfo.environment["XDG_DATA_HOME"] + ?? fm.homeDirectoryForCurrentUser.appendingPathComponent(".local/share").path + let reposDir = URL(fileURLWithPath: dataHome).appendingPathComponent("timber/repos") + if let bare = try? fm.contentsOfDirectory(atPath: reposDir.path) { + repoNames = bare.filter { $0.hasSuffix(".git") }.map { String($0.dropLast(4)) }.sorted() + } + } + + let root = ProcessInfo.processInfo.environment["TIMBER_WORKTREE_ROOT"] + ?? fm.homeDirectoryForCurrentUser.appendingPathComponent("worktrees").path + 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 } + worktrees.append(TimberWorktree(name: rel, repo: repo, path: dir.path)) + } + } + return (repoNames.map { TimberRepo(name: $0) }, worktrees.sorted { $0.value < $1.value }) + } + + /// 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` + /// when Zed is not installed. + static func openPath(_ path: String) throws { + if let zed = findExecutable("zed") { + let result = try run(zed, args: ["--new", path]) + if result.code == 0 { + return + } + } + guard let open = findExecutable("open") else { + throw NSError( + domain: "Timber", + code: 2, + userInfo: [NSLocalizedDescriptionKey: "neither zed nor open found"] + ) + } + _ = try run(open, args: [path]) + } + + // MARK: - Notifications + + /// Post a user notification (failures critical-style via title prefix; + /// UNUserNotificationCenter has no urgency levels for local notes). + /// Never throws: notification failure must not break the action. + /// + /// UNUserNotificationCenter requires app-bundle identity and traps + /// (`bundleProxyForCurrentProcess is nil`, uncatchable from Swift) + /// when called from a raw binary, so outside an `.app` bundle this + /// falls back to `osascript display notification`. + static func notify(subject: String, detail: String, failure: Bool = false) { + let title = failure ? "Timber \(subject) failed" : "Timber \(subject)" + let body = detail.isEmpty ? (failure ? "unknown error" : "done") : detail + if TimberModel.usesUserNotifications(bundleURL: Bundle.main.bundleURL) { + let center = UNUserNotificationCenter.current() + center.requestAuthorization(options: [.alert, .sound]) { granted, _ in + guard granted else { return } + let content = UNMutableNotificationContent() + content.title = title + content.body = body + let request = UNNotificationRequest( + identifier: UUID().uuidString, content: content, trigger: nil + ) + center.add(request) + } + } else if let osascript = findExecutable("osascript") { + _ = try? run(osascript, args: TimberModel.appleScriptNotifyArgs(title: title, body: body)) + } + } +} + +private extension TimberWorktree { + var value: String { + TimberModel.worktreeValue(name: name, repo: repo) + } +} diff --git a/Sources/Timber/TimberState.swift b/Sources/Timber/TimberState.swift new file mode 100644 index 0000000..b72a681 --- /dev/null +++ b/Sources/Timber/TimberState.swift @@ -0,0 +1,154 @@ +import Foundation +import SwiftUI +import TimberModel + +// MARK: - State + +/// Selection is tracked by row id, never by numeric index: typing rebuilds +/// the list on every keystroke, and a stale index into a shorter array +/// traps (Array._checkSubscript). Rows likewise receive their item value +/// directly instead of subscripting the array in `body`. +final class TimberState: ObservableObject { + @Published var filter = "" + @Published var items: [TimberItem] = [] + @Published var repos: [TimberRepo] = [] + @Published var worktrees: [TimberWorktree] = [] + @Published var selectedID: TimberItem.ID? + @Published var cursorActive = false + @Published var armedRemoveValue = "" + @Published var repoFormOpen = false + @Published var repoURL = "" + @Published var repoName = "" + @Published var busy = false + @Published var listing = true + + func onMain(_ work: @escaping () -> Void) { + if Thread.isMainThread { + work() + } else { + DispatchQueue.main.async(execute: work) + } + } + + func background(_ work: @escaping () -> Void) { + DispatchQueue.global(qos: .userInitiated).async(execute: work) + } + + func selectedItem() -> TimberItem? { + items.first(where: { $0.id == selectedID }) + } + + // MARK: List + + /// Background poll: reload repos/worktrees without disturbing an open + /// popover — filter text, selection, and cursor stay as they are. + func refreshInBackground() { + background { + let (repos, worktrees) = TimberCommand.enumerate() + self.onMain { + self.repos = repos + self.worktrees = worktrees + self.listing = false + self.rebuild() + } + } + } + + /// Open the popover instantly from the warmed cache: clear the filter, + /// reset selection, and rebuild without waiting on `timber`. Callers + /// follow with `refreshInBackground()` to catch up quietly. + func presentFromCache() { + filter = "" + selectedID = nil + cursorActive = false + armedRemoveValue = "" + rebuild() + } + + func refresh() { + filter = "" + selectedID = nil + cursorActive = false + armedRemoveValue = "" + listing = true + background { + let (repos, worktrees) = TimberCommand.enumerate() + self.onMain { + self.repos = repos + self.worktrees = worktrees + self.listing = false + self.rebuild() + } + } + } + + /// Called by the filter field's onChange (the binding owns the text). + func filterChanged() { + selectedID = nil + cursorActive = true + rebuild() + } + + func clearFilter() { + filter = "" + } + + func rebuild() { + // Any list change disarms a pending delete. + armedRemoveValue = "" + items = TimberModel.itemsForTerm(repos: repos, worktrees: worktrees, term: filter) + if let id = selectedID, items.contains(where: { $0.id == id }) { + return + } + selectedID = items.first?.id + } + + func select(id: TimberItem.ID) { + guard items.contains(where: { $0.id == id }) else { return } + cursorActive = true + selectedID = id + armedRemoveValue = "" + } + + func move(_ delta: Int) { + guard !items.isEmpty else { return } + if !cursorActive { + cursorActive = true + selectedID = (delta < 0 ? items.last : items.first)?.id + } else { + let current = items.firstIndex(where: { $0.id == selectedID }) ?? 0 + let next = (current + delta + items.count) % items.count + selectedID = items[next].id + } + armedRemoveValue = "" + } + + // MARK: Actions + + /// Return / row click: open in Zed (creating first for create rows). + func primaryAction() { + guard !busy, !items.isEmpty else { return } + if cursorActive, let item = selectedItem() { + activate(item) + } else { + cursorActive = true + if selectedID == nil { + selectedID = items.first?.id + } + } + } + + func clickActivate(_ item: TimberItem) { + guard !busy, items.contains(where: { $0.id == item.id }) else { return } + select(id: item.id) + activate(item) + } + + func activate(_ item: TimberItem) { + if item.kind == .open { + openInZed(item) + } else { + create(item, withHerdr: false) + } + } +} diff --git a/Sources/Timber/TimberStateActions.swift b/Sources/Timber/TimberStateActions.swift new file mode 100644 index 0000000..58ffd19 --- /dev/null +++ b/Sources/Timber/TimberStateActions.swift @@ -0,0 +1,162 @@ +import Foundation +import SwiftUI +import TimberModel + +// MARK: - TimberState actions + +extension TimberState { + func openInZed(_ item: TimberItem) { + if item.kind == .open { + guard !busy, !item.path.isEmpty else { return } + busy = true + background { + try? TimberCommand.openPath(item.path) + self.onMain { self.busy = false } + } + } else { + create(item, withHerdr: false) + } + } + + func openInHerdr(_ item: TimberItem) { + guard !busy else { return } + if item.kind == .open { + busy = true + background { + do { + let result = try TimberCommand.runTimber(TimberModel.herdrSpaceArgs(value: item.value)) + self.onMain { + self.busy = false + if result.code == 0 { + TimberCommand.notify(subject: "Herdr space created", detail: item.value) + } else { + TimberCommand.notify( + subject: "herdr space", + detail: Self.lastLine(result.stderr) ?? "exit \(result.code)", + failure: true + ) + } + } + } catch { + self.onMain { + self.busy = false + TimberCommand.notify(subject: "herdr space", detail: error.localizedDescription, failure: true) + } + } + } + } else { + create(item, withHerdr: true) + } + } + + /// Create the worktree; without Herdr the resulting path opens in Zed, + /// with Herdr a notification posts instead (mirrors Panel.qml). + func create(_ item: TimberItem, withHerdr: Bool) { + guard !busy else { return } + busy = true + background { + do { + let args = TimberModel.createArgs(value: item.value, withHerdr: withHerdr) + let result = try TimberCommand.runTimber(args) + self.onMain { + self.busy = false + guard result.code == 0 else { + TimberCommand.notify( + subject: "worktree create", + detail: Self.lastLine(result.stderr) ?? "exit \(result.code)", + failure: true + ) + return + } + if withHerdr { + TimberCommand.notify(subject: "Herdr space created", detail: item.value) + self.refresh() + } else if let path = Self.lastLine(result.stdout), !path.isEmpty { + self.clearFilter() + try? TimberCommand.openPath(path) + } else { + TimberCommand.notify(subject: "worktree create", detail: "reported no path", failure: true) + } + } + } catch { + self.onMain { + self.busy = false + TimberCommand.notify(subject: "worktree create", detail: error.localizedDescription, failure: true) + } + } + } + } + + /// Two-phase delete: first click arms the row, second click removes. + func armOrRemove(_ item: TimberItem) { + guard item.kind == .open, !busy else { return } + let step = TimberModel.armOrConfirmRemove(armed: armedRemoveValue, value: item.value) + armedRemoveValue = step.armed + if step.confirmed { + remove(item) + } + } + + private func remove(_ item: TimberItem) { + busy = true + background { + do { + let result = try TimberCommand.runTimber(TimberModel.removeArgs(value: item.value)) + self.onMain { + self.busy = false + if result.code == 0 { + self.refresh() + } else { + TimberCommand.notify( + subject: "worktree remove", + detail: Self.lastLine(result.stderr) ?? "exit \(result.code)", + failure: true + ) + } + } + } catch { + self.onMain { + self.busy = false + TimberCommand.notify(subject: "worktree remove", detail: error.localizedDescription, failure: true) + } + } + } + } + + // MARK: Repo form + + func submitRepoForm() { + guard !busy, let args = TimberModel.repoAddArgs(url: repoURL, name: repoName) else { return } + busy = true + background { + do { + let result = try TimberCommand.runTimber(args) + self.onMain { + self.busy = false + if result.code == 0 { + self.repoFormOpen = false + self.repoURL = "" + self.repoName = "" + self.refresh() + } else { + TimberCommand.notify( + subject: "repo add", + detail: Self.lastLine(result.stderr) ?? "exit \(result.code)", + failure: true + ) + } + } + } catch { + self.onMain { + self.busy = false + TimberCommand.notify(subject: "repo add", detail: error.localizedDescription, failure: true) + } + } + } + } + + private static func lastLine(_ text: String) -> String? { + let line = text.split(separator: "\n").last.map(String.init)?.trimmingCharacters(in: .whitespacesAndNewlines) + return (line?.isEmpty == false) ? line : nil + } +} diff --git a/Sources/Timber/main.swift b/Sources/Timber/main.swift new file mode 100644 index 0000000..5490592 --- /dev/null +++ b/Sources/Timber/main.swift @@ -0,0 +1,8 @@ +import AppKit + +// Timber entry point. Plain AppKit lifecycle (no SwiftUI App scene) +// so no stray windows open: just the status item, popover, and menu. +let delegate = AppDelegate() +let app = NSApplication.shared +app.delegate = delegate +app.run() diff --git a/Sources/TimberModel/TimberModel.swift b/Sources/TimberModel/TimberModel.swift new file mode 100644 index 0000000..3c7fada --- /dev/null +++ b/Sources/TimberModel/TimberModel.swift @@ -0,0 +1,262 @@ +import Foundation + +// Pure model logic for the Timber menubar app, ported from TimberModel.js +// in omarchy-timber (which itself mirrors timber's tui_create_wizard.go). +// No UI or process dependencies so it stays unit-testable in isolation. + +public struct TimberRepo: Equatable { + public let name: String + public init(name: String) { + self.name = name + } +} + +public struct TimberWorktree: Equatable { + public let name: String + public let repo: String + public let path: String + public init(name: String, repo: String, path: String) { + self.name = name + self.repo = repo + self.path = path + } +} + +public struct TimberItem: Equatable, Identifiable { + /// Stable identity for SwiftUI rows: open and create rows never share + /// a value within one listing, so kind+value is unique. + public var id: String { + "\(kind):\(value)" + } + + public enum Kind: Equatable { + case open + case create + } + + public let kind: Kind + public let name: String + public let repo: String + /// "name@repo". + public let value: String + /// Worktree path for `.open` rows, empty for `.create` rows. + public let path: String + public init(kind: Kind, name: String, repo: String, value: String, path: String) { + self.kind = kind + self.name = name + self.repo = repo + self.value = value + self.path = path + } +} + +public enum TimberModel { + // MARK: - Values + + /// Split "name@repo" on the LAST "@". Returns nil unless qualified + /// (both halves non-empty). + public static func splitValue(_ value: String) -> (name: String, repo: String)? { + guard let idx = value.lastIndex(of: "@") else { return nil } + let name = String(value[.. String { + "\(name)@\(repo)" + } + + // MARK: - Fuzzy matching + + /// Case-insensitive fuzzy match: every char of term appears in order. + /// Returns match indexes, or nil for no match. Empty term matches all. + public static func fuzzyMatch(term: String, target: String) -> [Int]? { + let query = term.lowercased() + let candidate = target.lowercased() + if query.isEmpty { + return [] + } + var indexes: [Int] = [] + var pos = candidate.startIndex + for ch in query { + guard let found = candidate[pos...].firstIndex(of: ch) else { return nil } + indexes.append(candidate.distance(from: candidate.startIndex, to: found)) + pos = candidate.index(after: found) + } + return indexes + } + + private static func filterTerm(_ term: String, targets: [String]) -> [Int] { + if term.isEmpty { + return Array(targets.indices) + } + return targets.indices.filter { fuzzyMatch(term: term, target: targets[$0]) != nil } + } + + /// Split on the last separator. `qualified` is true only when both + /// halves are non-empty; `before` is still usable for filtering when + /// unqualified (e.g. "a@" filters on "a", "@b" matches everything). + private struct SplitParts { + let before: String + let after: String + let qualified: Bool + } + + private static func cutLast( + _ value: String, + separator: Character + ) -> SplitParts { + guard let idx = value.lastIndex(of: separator) else { + return SplitParts(before: value, after: "", qualified: false) + } + let before = String(value[.. [Int] { + let values = worktrees.map { worktreeValue(name: $0.name, repo: $0.repo) } + let worktreeTargets = values.map { cutLast($0, separator: "@").before } + let repoTargets = values.map { splitValue($0)?.repo ?? "" } + let parts = cutLast(term, separator: "@") + let worktreeRanks = filterTerm(parts.before, targets: worktreeTargets) + guard parts.qualified else { return worktreeRanks } + let repoSet = Set(filterTerm(parts.after, targets: repoTargets)) + return worktreeRanks.filter { repoSet.contains($0) } + } + + // MARK: - Display items + + /// Mirror wizardItemsForTerm: existing worktrees first, then one + /// `create` row per matching repo when the term is a qualified + /// `name@repo` with no second `@` in the name half. + public static func itemsForTerm( + repos: [TimberRepo], + worktrees: [TimberWorktree], + term: String + ) -> [TimberItem] { + var items: [TimberItem] = [] + for rank in filterWorktrees(term, worktrees: worktrees) { + let worktree = worktrees[rank] + let value = worktreeValue(name: worktree.name, repo: worktree.repo) + let item = TimberItem( + kind: .open, name: worktree.name, repo: worktree.repo, value: value, path: worktree.path + ) + items.append(item) + } + + guard let termSplit = splitValue(term), + !termSplit.name.isEmpty, + !termSplit.name.contains("@") + else { return items } + + let repoNames = repos.map(\.name) + for repoIndex in filterTerm(termSplit.repo, targets: repoNames) { + let repo = repos[repoIndex] + let exists = worktrees.contains { $0.name == termSplit.name && $0.repo == repo.name } + if exists { + continue + } + let value = worktreeValue(name: termSplit.name, repo: repo.name) + items.append(TimberItem(kind: .create, name: termSplit.name, repo: repo.name, value: value, path: "")) + } + return items + } + + // MARK: - timber argv builders (after `timber`) + + /// `timber create [--herdr|--no-herdr] `. + public static func createArgs(value: String, withHerdr: Bool) -> [String] { + ["create", withHerdr ? "--herdr" : "--no-herdr", value] + } + + /// `timber herdr space --new `. + public static func herdrSpaceArgs(value: String) -> [String] { + ["herdr", "space", "--new", value] + } + + /// `timber remove `. + public static func removeArgs(value: String) -> [String] { + ["remove", value] + } + + /// `timber repo add [--name ]`. Returns nil when the + /// URL is blank so callers can refuse to run instead of registering + /// nothing. (This timber build has no `--alias` flag.) + public static func repoAddArgs(url: String, name: String) -> [String]? { + let cleanURL = url.trimmingCharacters(in: .whitespacesAndNewlines) + guard !cleanURL.isEmpty else { return nil } + var args = ["repo", "add"] + let cleanName = name.trimmingCharacters(in: .whitespacesAndNewlines) + if !cleanName.isEmpty { + args += ["--name", cleanName] + } + args.append(cleanURL) + return args + } + + // MARK: - Status-item clicks + + /// Left-click toggles the popover; right-click (or Ctrl-click) shows + /// the context menu (Quit). Kept pure so the mapping stays tested. + public enum StatusItemClickAction: Equatable { + case togglePopover + case showContextMenu + } + + public static func statusItemClickAction(isSecondaryClick: Bool) -> StatusItemClickAction { + isSecondaryClick ? .showContextMenu : .togglePopover + } + + // MARK: - Notification routing + + /// True when running inside an `.app` bundle, the only context where + /// UNUserNotificationCenter is safe to touch: from a raw binary it + /// traps with `bundleProxyForCurrentProcess is nil`, which is + /// uncatchable from Swift, so callers must use the osascript fallback. + public static func usesUserNotifications(bundleURL: URL) -> Bool { + bundleURL.pathExtension.lowercased() == "app" + } + + /// argv for `osascript` showing a notification; split out so the + /// AppleScript quoting stays unit-tested. + public static func appleScriptNotifyArgs(title: String, body: String) -> [String] { + ["-e", "display notification \(appleScriptString(body)) with title \(appleScriptString(title))"] + } + + private static func appleScriptString(_ text: String) -> String { + "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" + } + + // MARK: - Child process environment + + /// PATH handed to `timber` children. GUI apps launch with a minimal + /// PATH that lacks Homebrew etc., and `timber herdr` shells out to the + /// `herdr` CLI via PATH lookup, so prepend the well-known install dirs + /// (skipping ones already present). + public static func childPATH(current: String?, extraDirs: [String]) -> String { + let currentDirs = (current ?? "").split(separator: ":").map(String.init).filter { !$0.isEmpty } + let missing = extraDirs.filter { dir in !dir.isEmpty && !currentDirs.contains(dir) } + return (missing + currentDirs).joined(separator: ":") + } + + // MARK: - Two-phase delete + + /// One two-phase delete step for the armed value. Clicking the armed + /// row confirms the remove; clicking any other row arms it instead + /// (disarming the previous one). A blank value changes nothing. + public static func armOrConfirmRemove(armed: String, value: String) -> (armed: String, confirmed: Bool) { + guard !value.isEmpty else { return (armed, false) } + if armed == value { + return ("", true) + } + return (value, false) + } +} diff --git a/Tests/TimberModelTests/TimberModelTests.swift b/Tests/TimberModelTests/TimberModelTests.swift new file mode 100644 index 0000000..11a083b --- /dev/null +++ b/Tests/TimberModelTests/TimberModelTests.swift @@ -0,0 +1,224 @@ +@testable import TimberModel +import XCTest + +final class TimberModelTests: XCTestCase { + private let repos = [ + TimberRepo(name: "timber"), + TimberRepo(name: "scribble"), + ] + private let worktrees = [ + TimberWorktree(name: "feature/login", repo: "timber", path: "/wt/timber/feature/login/timber"), + TimberWorktree(name: "fix-crash", repo: "scribble", path: "/wt/scribble/fix-crash/scribble"), + ] + + // MARK: - splitValue + + func testSplitValueQualified() { + let split = TimberModel.splitValue("feature/login@timber") + XCTAssertEqual(split?.name, "feature/login") + XCTAssertEqual(split?.repo, "timber") + } + + func testSplitValueSplitsOnLastAt() { + let split = TimberModel.splitValue("a@b@c") + XCTAssertEqual(split?.name, "a@b") + XCTAssertEqual(split?.repo, "c") + } + + func testSplitValueUnqualified() { + XCTAssertNil(TimberModel.splitValue("plain")) + XCTAssertNil(TimberModel.splitValue("name@")) + XCTAssertNil(TimberModel.splitValue("@repo")) + XCTAssertNil(TimberModel.splitValue("")) + } + + // MARK: - fuzzyMatch + + func testFuzzyMatchInOrder() { + XCTAssertNotNil(TimberModel.fuzzyMatch(term: "fl", target: "feature/login")) + XCTAssertNotNil(TimberModel.fuzzyMatch(term: "FLogin", target: "feature/login")) + } + + func testFuzzyMatchOutOfOrderFails() { + XCTAssertNil(TimberModel.fuzzyMatch(term: "lf", target: "feature/login")) + XCTAssertNil(TimberModel.fuzzyMatch(term: "zzz", target: "feature/login")) + } + + func testFuzzyMatchEmptyTermMatchesAll() { + XCTAssertEqual(TimberModel.fuzzyMatch(term: "", target: "anything"), []) + } + + // MARK: - itemsForTerm + + func testEmptyTermListsAllWorktrees() { + let items = TimberModel.itemsForTerm(repos: repos, worktrees: worktrees, term: "") + XCTAssertEqual(items.map(\.value), ["feature/login@timber", "fix-crash@scribble"]) + XCTAssertTrue(items.allSatisfy { $0.kind == .open }) + XCTAssertEqual(items[0].path, "/wt/timber/feature/login/timber") + } + + func testFilterMatchesWorktreeHalf() { + let items = TimberModel.itemsForTerm(repos: repos, worktrees: worktrees, term: "fix") + XCTAssertEqual(items.map(\.value), ["fix-crash@scribble"]) + } + + func testQualifiedTermIntersectsRepoHalf() { + let items = TimberModel.itemsForTerm(repos: repos, worktrees: worktrees, term: "f@timber") + XCTAssertEqual( + items.map { ($0.kind, $0.value) }.map { "\($0.0):\($0.1)" }, + ["open:feature/login@timber", "create:f@timber"] + ) + } + + func testQualifiedTermYieldsOnlyCreateRowWhenNothingOpen() { + // "login" matches no worktree under scribble, so the only row + // offers to create login@scribble. + let items = TimberModel.itemsForTerm(repos: repos, worktrees: worktrees, term: "login@scribble") + XCTAssertEqual(items.map { ($0.kind, $0.value) }.map { "\($0.0):\($0.1)" }, ["create:login@scribble"]) + } + + func testQualifiedTermIntersectsBothHalves() { + // "f" alone matches both worktrees; "@scribble" narrows the open + // rows to one (plus the create offer for f@scribble). + let items = TimberModel.itemsForTerm(repos: repos, worktrees: worktrees, term: "f@scribble") + XCTAssertEqual( + items.map { ($0.kind, $0.value) }.map { "\($0.0):\($0.1)" }, + ["open:fix-crash@scribble", "create:f@scribble"] + ) + } + + func testCreateRowForNewQualifiedValue() { + let items = TimberModel.itemsForTerm(repos: repos, worktrees: worktrees, term: "new-thing@tim") + XCTAssertEqual(items.map { ($0.kind, $0.value) }.map { "\($0.0):\($0.1)" }, ["create:new-thing@timber"]) + XCTAssertEqual(items[0].path, "") + } + + func testNoCreateRowWhenWorktreeExists() { + let items = TimberModel.itemsForTerm(repos: repos, worktrees: worktrees, term: "feature/login@timber") + XCTAssertEqual(items.map(\.kind), [.open]) + } + + func testNoCreateRowWhenTermUnqualified() { + let items = TimberModel.itemsForTerm(repos: repos, worktrees: worktrees, term: "new-thing") + XCTAssertTrue(items.isEmpty) + } + + // MARK: - row identity + + func testItemIDsUniqueWithinListing() { + // The popover diffs rows by id; a duplicate would collapse two + // rows into one and desync selection. Exercise open-heavy, + // create-heavy, and empty terms. + for term in ["", "f", "f@timber", "new@tim", "login@scribble", "@", "zzz"] { + let ids = TimberModel.itemsForTerm(repos: repos, worktrees: worktrees, term: term).map(\.id) + XCTAssertEqual(ids.count, Set(ids).count, "duplicate row ids for term \(term.debugDescription)") + } + } + + // MARK: - status-item clicks + + func testSecondaryClickShowsContextMenu() { + XCTAssertEqual( + TimberModel.statusItemClickAction(isSecondaryClick: true), + .showContextMenu + ) + } + + func testPrimaryClickTogglesPopover() { + XCTAssertEqual( + TimberModel.statusItemClickAction(isSecondaryClick: false), + .togglePopover + ) + } + + // MARK: - notification routing + + func testUsesUserNotificationsOnlyInsideAppBundle() { + XCTAssertTrue(TimberModel + .usesUserNotifications(bundleURL: URL(fileURLWithPath: "/Applications/Timber.app"))) + XCTAssertFalse(TimberModel + .usesUserNotifications( + bundleURL: URL(fileURLWithPath: "/Users/nnutter/worktrees/macos-timber/alpha/macos-timber/dist") + )) + XCTAssertFalse(TimberModel + .usesUserNotifications( + bundleURL: URL(fileURLWithPath: "/Users/nnutter/worktrees/macos-timber/alpha/macos-timber/.build/debug") + )) + } + + func testAppleScriptNotifyArgs() { + XCTAssertEqual( + TimberModel.appleScriptNotifyArgs(title: "Timber Hi", body: "done"), + ["-e", "display notification \"done\" with title \"Timber Hi\""] + ) + } + + func testAppleScriptNotifyArgsEscapesQuotes() { + // A quote or backslash in the detail must not break out of the + // AppleScript string literal (or the notify fallback crashes). + XCTAssertEqual( + TimberModel.appleScriptNotifyArgs(title: "Timber x", body: #"said "hi" C:\wt"#), + ["-e", #"display notification "said \"hi\" C:\\wt" with title "Timber x""#] + ) + } + + // MARK: - child PATH + + func testChildPATHPrependsMissingDirs() { + XCTAssertEqual( + TimberModel.childPATH(current: "/usr/bin:/bin", extraDirs: ["/opt/homebrew/bin", "/usr/bin"]), + "/opt/homebrew/bin:/usr/bin:/bin" + ) + } + + func testChildPATHHandlesNilAndEmpty() { + XCTAssertEqual(TimberModel.childPATH(current: nil, extraDirs: ["/opt/homebrew/bin"]), "/opt/homebrew/bin") + XCTAssertEqual(TimberModel.childPATH(current: "", extraDirs: []), "") + } + + // MARK: - argv builders + + func testCreateArgs() { + XCTAssertEqual( + TimberModel.createArgs(value: "x@timber", withHerdr: false), + ["create", "--no-herdr", "x@timber"] + ) + XCTAssertEqual(TimberModel.createArgs(value: "x@timber", withHerdr: true), ["create", "--herdr", "x@timber"]) + } + + func testHerdrSpaceArgs() { + XCTAssertEqual(TimberModel.herdrSpaceArgs(value: "x@timber"), ["herdr", "space", "--new", "x@timber"]) + } + + func testRemoveArgs() { + XCTAssertEqual(TimberModel.removeArgs(value: "x@timber"), ["remove", "x@timber"]) + } + + func testRepoAddArgs() { + XCTAssertEqual( + TimberModel.repoAddArgs(url: " https://example.com/r.git ", name: " r "), + ["repo", "add", "--name", "r", "https://example.com/r.git"] + ) + XCTAssertEqual( + TimberModel.repoAddArgs(url: "https://example.com/r.git", name: " "), + ["repo", "add", "https://example.com/r.git"] + ) + XCTAssertNil(TimberModel.repoAddArgs(url: " ", name: "r")) + } + + // MARK: - two-phase delete + + func testArmOrConfirmRemove() { + XCTAssertEqual(TimberModel.armOrConfirmRemove(armed: "", value: "x@r").armed, "x@r") + XCTAssertFalse(TimberModel.armOrConfirmRemove(armed: "", value: "x@r").confirmed) + let confirm = TimberModel.armOrConfirmRemove(armed: "x@r", value: "x@r") + XCTAssertEqual(confirm.armed, "") + XCTAssertTrue(confirm.confirmed) + let switchRow = TimberModel.armOrConfirmRemove(armed: "x@r", value: "y@r") + XCTAssertEqual(switchRow.armed, "y@r") + XCTAssertFalse(switchRow.confirmed) + let blank = TimberModel.armOrConfirmRemove(armed: "x@r", value: "") + XCTAssertEqual(blank.armed, "x@r") + XCTAssertFalse(blank.confirmed) + } +} diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..a78ab76 --- /dev/null +++ b/mise.toml @@ -0,0 +1,64 @@ +[tools] +swiftlint = "0.65.1" +swiftformat = "0.63.0" + +[env] +_.path = [ + "/opt/homebrew/bin", + "/usr/local/bin", + "~/.local/bin", +] + +[tasks.build] +description = "Build dist/Timber.app via SwiftPM" +run = """ +set -euo pipefail +# Prefer an already-selected toolchain (e.g. CI runners); fall back to the +# local Xcode install when nothing is selected. +if [ -z "${DEVELOPER_DIR:-}" ] && [ -d /Applications/Xcode.app ]; then + export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer +fi +# --disable-sandbox plus redirected shared dirs keep the build inside the +# sandbox so it runs without an approval prompt; scratch output already +# lives in .build. +SWIFT_PM_FLAGS="--disable-sandbox --cache-path /tmp/swiftpm-cache --config-path /tmp/swiftpm-config --security-path /tmp/swiftpm-security" +swift build $SWIFT_PM_FLAGS +BIN_DIR="$(swift build $SWIFT_PM_FLAGS --show-bin-path)" +rm -rf dist/TimberMenu.app dist/Timber.app +mkdir -p dist/Timber.app/Contents/MacOS dist/Timber.app/Contents/Resources +cp "$BIN_DIR/Timber" dist/Timber.app/Contents/MacOS/Timber +cp packaging/Info.plist dist/Timber.app/Contents/Info.plist +cp -R "$BIN_DIR/Timber_Timber.bundle" dist/Timber.app/Contents/Resources/ +""" + +[tasks.test] +description = "Run the TimberModel test suite" +run = """ +set -euo pipefail +if [ -z "${DEVELOPER_DIR:-}" ] && [ -d /Applications/Xcode.app ]; then + export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer +fi +swift test --disable-sandbox --cache-path /tmp/swiftpm-cache --config-path /tmp/swiftpm-config --security-path /tmp/swiftpm-security +""" + +[tasks.run] +description = "Build and open the menubar app" +depends = ["build"] +run = "/usr/bin/open dist/Timber.app" + +[tasks.package] +description = "Build and zip the app bundle for distribution" +depends = ["build"] +run = """ +set -euo pipefail +rm -f dist/Timber.zip +ditto -c -k --sequesterRsrc --keepParent dist/Timber.app dist/Timber.zip +""" + +[tasks.lint] +description = "Run SwiftLint (strict) and SwiftFormat in lint mode" +run = "swiftlint --strict --config .swiftlint.yaml --cache-path /tmp/swiftlint-cache && swiftformat Sources Tests --lint --cache ignore" + +[tasks.format] +description = "Format Swift sources" +run = "swiftformat Sources Tests --cache ignore" diff --git a/packaging/Info.plist b/packaging/Info.plist new file mode 100644 index 0000000..35932e9 --- /dev/null +++ b/packaging/Info.plist @@ -0,0 +1,20 @@ + + + + + CFBundleIdentifier + io.github.nnutter.Timber + CFBundleName + Timber + CFBundleExecutable + Timber + CFBundlePackageType + APPL + CFBundleShortVersionString + 0.1 + CFBundleVersion + 1 + LSUIElement + + +