From 9c7f94483b7a1082a7edf759d7f5fd84608f2eba Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Thu, 8 Oct 2026 23:13:52 -0500 Subject: [PATCH] Discover arbitrary Git worktrees through Timber's JSON listing Filesystem discovery assumed Timber's managed directory layout, so worktrees at arbitrary paths never appeared in the panel. Use Timber as the source of membership, paths, badges, and recency order instead. Keep repository discovery separate so empty repositories still offer create suggestions. Failed commands or invalid JSON retain the cached listing rather than replacing it with incomplete results. Regression tests cover arbitrary paths, qualified filtering, badges, empty repositories, invalid JSON, and recency across sort changes. --- Panel.qml | 41 ++++++++++++++-------------- README.md | 16 +++++------ TimberModel.js | 53 ++++++++++++++++-------------------- tests/model.test.mjs | 65 +++++++++++++++++++++++++++----------------- 4 files changed, 92 insertions(+), 83 deletions(-) diff --git a/Panel.qml b/Panel.qml index 36cbce5..9595d41 100644 --- a/Panel.qml +++ b/Panel.qml @@ -5,7 +5,7 @@ import qs.Commons import qs.Ui import "TimberModel.js" as TimberModel -// Bar-widget frontend to `timber` (managed Git worktrees), following the +// Bar-widget frontend to `timber` (registered Git worktrees), following the // agents panel: a bar icon plus an anchored popup. Toggle with the icon // or `omarchy-shell io.github.nnutter.omarchy-timber toggle`. Panel { @@ -66,26 +66,13 @@ Panel { readonly property int visibleRows: Math.max(1, Math.min(displayModel.count, root.maxVisibleRows)) readonly property int listHeight: root.visibleRows * root.rowHeight + (root.visibleRows - 1) * Style.space(4) - // The filesystem scan owns membership. Optional JSON enrichment supplies - // Status/Todo badges without hiding rows if timber list fails. + // Timber owns worktree discovery, paths, badges, and recency ordering. + // Keep the repository list separate so empty repos offer create rows. readonly property string listScript: [ - 'data_home=${XDG_DATA_HOME:-$HOME/.local/share};', - 'root=${TIMBER_WORKTREE_ROOT:-$HOME/worktrees};', - 'repos=$(timber repo list -q 2>/dev/null);', - 'if [ -z "$repos" ]; then', - ' repos=$(for d in "$data_home"/timber/repos/*.git; do [ -d "$d" ] || continue; b=${d##*/}; echo "${b%.git}"; done);', - 'fi;', + 'repos=$(timber repo list -q) || exit $?;', 'printf "%s\\n" "$repos" | while IFS= read -r repo; do [ -n "$repo" ] || continue; printf "R\\t%s\\n" "$repo"; done;', - 'shopt -s globstar nullglob;', - 'printf "%s\\n" "$repos" | while IFS= read -r repo; do [ -n "$repo" ] || continue;', - ' for d in "$root/$repo"/**/"$repo"; do [ -e "$d/.git" ] || continue;', - ' parent=${d%/*}; name=${parent#"$root/$repo"/}; [ -n "$name" ] || continue;', - ' stamp=$(git -C "$d" log -1 --format=%ct 2>/dev/null) || stamp=$(stat -c %Y -- "$d" 2>/dev/null);', - ' printf "W\\t%s@%s\\t%s\\t%s\\n" "$name" "$repo" "$d" "$stamp";', - ' done;', - 'done;', - 'details=$(timber list --json 2>/dev/null) && printf "D\\t%s\\n" "$details";', - 'exit 0' + 'printf "D\\t";', + 'exec timber list --json --sort recency' ].join("\n") function refresh() { @@ -421,10 +408,22 @@ Panel { id: listStdout waitForEnd: true } + stderr: StdioCollector { + id: listStderr + waitForEnd: true + } onExited: function(code) { root.listing = false - if (code === 0) root.applyListOutput(listStdout.text) - else root.notifyFailure("worktree list", "filesystem scan exited " + code) + if (code === 0) { + try { + root.applyListOutput(listStdout.text) + } catch (error) { + root.notifyFailure("worktree list", String(error)) + } + } else { + var detail = String(listStderr.text || "").trim().split("\n").pop() || ("exit " + code) + root.notifyFailure("worktree list", detail) + } if (root.refreshQueued) { root.refreshQueued = false Qt.callLater(root.refreshInBackground) diff --git a/README.md b/README.md index 3a9eeb4..00ad49f 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # omarchy-timber -Omarchy overlay plugin that fronts [`timber`](https://github.com/nnutter/timber) -managed Git worktrees, with the shared features of [macos-timber](https://github.com/nnutter/macos-timber). +Omarchy overlay plugin that fronts [`timber`](https://github.com/nnutter/timber) Git worktrees, with the shared features of [macos-timber](https://github.com/nnutter/macos-timber). +It lists both Timber-managed worktrees and arbitrary Git worktrees that Timber discovers for registered repositories. Fuzzy-filter the existing worktrees, type `name@repo` to create, press `enter` to open in Zed, or use the trailing Zed/Herdr icons to open in Zed or a Herdr space. ## Requirements @@ -37,14 +37,14 @@ omarchy-shell io.github.nnutter.omarchy-timber toggle ``` The centered sort picker offers **Recency** (default), **Repo**, and **Worktree**. -Recency uses the newest commit timestamp, with directory modification time as a fallback. +Recency follows the order from `timber list --json --sort recency`. Changing the sort preserves the selected row. Existing rows show the `timber ls` Status and Todo badges: - Status shows `merged`, `↑N`, `↓N`, or `error`, without the upstream suffix. - Todo shows `done/total` only when checklist items exist. -- Missing or unreadable JSON details hide badges without hiding the worktree. +- Listing failures or invalid JSON retain the cached rows and produce a critical desktop notification. The popup grows to fit names and badges within width and screen bounds. Long names truncate in the middle so the repository remains visible. @@ -99,10 +99,10 @@ Validate `Panel.qml` on a live Omarchy machine to check rendering, keyboard navi ## Notes -Worktrees are enumerated the way timber's own zsh completion does: `timber repo list -q` plus a scan of `$TIMBER_WORKTREE_ROOT`. -The filesystem scan owns membership. -`timber list --json` only enriches scanned rows with Status/Todo details. -Its failure does not invalidate the scan. +`timber list --json --sort recency` supplies worktree membership, paths, badges, and recency order. +The plugin does not assume a directory layout or scan `$TIMBER_WORKTREE_ROOT`. +`timber repo list -q` supplies create suggestions, including repositories with no worktrees. +If either command fails, the plugin retains its cached listing. Omarchy owns the bar, plugin enablement, and shell startup. The macOS Quit menu, Open at Login toggle, app icon, and packaging have no plugin equivalent. diff --git a/TimberModel.js b/TimberModel.js index 46621e2..7e7e1fd 100644 --- a/TimberModel.js +++ b/TimberModel.js @@ -6,37 +6,32 @@ // worktrees:[{ name: "feature/login", repo: "timber" }] // items: [{ kind: "open"|"create", name, repo, value: "name@repo" }] -// Parse the repository/worktree records produced by the filesystem scan. +// R-prefixed repository names, then D-prefixed timber list --json output. +// JSON owns membership and paths. Reject invalid data before replacing cache. function parseListing(text) { var repos = [] var worktrees = [] - var details = {} var lines = String(text || "").split("\n") + var dataIndex = -1 for (var i = 0; i < lines.length; i++) { - var parts = lines[i].split("\t") - if (parts[0] === "D") { - try { - var rows = JSON.parse(lines[i].slice(2)) - if (Array.isArray(rows)) { - for (var j = 0; j < rows.length; j++) { - var row = rows[j] - if (row && typeof row.name === "string" && typeof row.repo === "string") - details["worktree:" + worktreeValue(row)] = row - } - } - } catch (error) { - // Optional enrichment must never invalidate the filesystem listing. - } - } else if (parts[0] === "R" && parts[1]) repos.push({ name: parts[1] }) - else if (parts[0] === "W" && parts[1] && parts[2]) { - var split = splitValue(parts[1]) - if (split) worktrees.push({ name: split.name, repo: split.repo, path: parts[2], lastCommitAt: Number(parts[3]) || 0 }) + if (lines[i].slice(0, 2) === "D\t") { + dataIndex = i + break } + if (lines[i].slice(0, 2) === "R\t" && lines[i].length > 2) + repos.push({ name: lines[i].slice(2) }) } - for (var k = 0; k < worktrees.length; k++) { - var detail = details["worktree:" + worktreeValue(worktrees[k])] || {} - worktrees[k].statusText = listStatusText(detail) - worktrees[k].todoText = todoText(detail) + if (dataIndex === -1) throw new Error("Missing worktree JSON") + var rows = JSON.parse(lines.slice(dataIndex).join("\n").slice(2)) + if (!Array.isArray(rows)) throw new Error("Expected a worktree JSON array") + for (var j = 0; j < rows.length; j++) { + var row = rows[j] + if (!row || typeof row.name !== "string" || !row.name || + typeof row.repo !== "string" || !row.repo || + typeof row.path !== "string" || !row.path) + throw new Error("Invalid worktree JSON record") + worktrees.push({ name: row.name, repo: row.repo, path: row.path, + statusText: listStatusText(row), todoText: todoText(row) }) } return { repos: repos, worktrees: worktrees } } @@ -150,13 +145,13 @@ function compareText(a, b) { return a < b ? -1 : (a > b ? 1 : 0) } -// Sort a copy. Missing or tied commit dates fall back to name@repo. +// Sort a copy, preserving timber list --sort recency order by default. function sortWorktrees(worktrees, mode) { - return worktrees.slice().sort(function(a, b) { + var rows = worktrees.slice() + if (mode !== "repo" && mode !== "worktree") return rows + return rows.sort(function(a, b) { if (mode === "repo") return compareText(a.repo, b.repo) || compareText(a.name, b.name) - if (mode === "worktree") return compareText(a.name, b.name) || compareText(a.repo, b.repo) - var dateOrder = (b.lastCommitAt || 0) - (a.lastCommitAt || 0) - return dateOrder || compareText(worktreeValue(a), worktreeValue(b)) + return compareText(a.name, b.name) || compareText(a.repo, b.repo) }) } diff --git a/tests/model.test.mjs b/tests/model.test.mjs index 52fc639..cd4ca7b 100644 --- a/tests/model.test.mjs +++ b/tests/model.test.mjs @@ -25,9 +25,9 @@ const { const repos = [{ name: "timber" }, { name: "persona" }]; const worktrees = [ + { name: "alpha", repo: "persona" }, { name: "alpha", repo: "timber" }, { name: "beta", repo: "persona" }, - { name: "alpha", repo: "persona" }, ]; // Array.from re-roots the results in this realm: itemsForTerm returns @@ -83,10 +83,9 @@ describe("itemsForTerm", () => { }); }); -describe("Status and Todo enrichment", () => { - const scan = "R\ttimber\nW\talpha@timber\t/tmp/alpha\t100\n"; +describe("JSON worktree listing", () => { const display = (json) => { - const listing = parseListing(scan + "D\t" + json + "\n"); + const listing = parseListing("R\ttimber\nD\t" + json + "\n"); return itemsForTerm(listing.repos, listing.worktrees, ""); }; for (const [detail, status, todo] of [ @@ -98,38 +97,50 @@ describe("Status and Todo enrichment", () => { [{ ahead: "2", merged: "false", todoTotal: "4" }, "", ""], ]) { it(`renders ${JSON.stringify(detail)} as quiet or explicit badges`, () => { - const items = display(JSON.stringify([{ name: "alpha", repo: "timber", upstream: "origin/main", ...detail }])); + const items = display(JSON.stringify([{ name: "alpha", repo: "timber", path: "/tmp/alpha", upstream: "origin/main", ...detail }])); assert.equal(items[0].statusText, status); assert.equal(items[0].todoText, todo); assert.equal(items[0].path, "/tmp/alpha"); }); } - it("keeps scanned rows when enrichment is absent, malformed, or unrelated", () => { - for (const json of ["", "not JSON", "{}", "null", '[null, {"name":"ghost","repo":"timber","ahead":5}]']) { - const items = display(json); - assert.deepEqual(values(items), ["alpha@timber"]); - assert.equal(items[0].statusText, ""); - assert.equal(items[0].todoText, ""); + it("opens arbitrary paths from JSON and offers creation in empty repositories", () => { + const listing = parseListing("R\torg/repo\nR\tempty\nD\t" + JSON.stringify([ + { name: "feature/login", repo: "org/repo", path: "/srv/my projects/login", ahead: 2 }, + { name: "main", repo: "org/repo", path: "/opt/checkout" }, + ], null, 2)); + const items = itemsForTerm(listing.repos, listing.worktrees, "feature/login@org/repo"); + assert.deepEqual(kinds(items), ["open"]); + assert.equal(items[0].path, "/srv/my projects/login"); + assert.equal(items[0].statusText, "↑2"); + const created = itemsForTerm(listing.repos, listing.worktrees, "new@empty"); + assert.deepEqual(kinds(created), ["create"]); + assert.equal(created[0].statusText, ""); + assert.equal(created[0].todoText, ""); + }); + it("rejects malformed or incomplete JSON listings", () => { + for (const json of ["", "not JSON", "{}", "null", "[null]", + '[{"name":"alpha","repo":"timber"}]', + '[{"name":"alpha","repo":"timber","path":"/tmp/alpha"},{"name":"bad","path":"/tmp/bad"}]']) { + assert.throws(() => display(json)); } + assert.throws(() => parseListing("R\ttimber\n")); }); - it("never transfers badges to a create suggestion", () => { - const listing = parseListing(scan + 'D\t[{"name":"ghost","repo":"timber","ahead":5}]\n'); - const items = itemsForTerm(listing.repos, listing.worktrees, "ghost@timber"); - assert.deepEqual(kinds(items), ["create"]); - assert.equal(items[0].statusText, ""); - assert.equal(items[0].todoText, ""); + it("accepts an empty worktree list without losing create suggestions", () => { + const listing = parseListing("R\ttimber\nD\t[]\n"); + assert.deepEqual(values(itemsForTerm(listing.repos, listing.worktrees, "")), []); + assert.deepEqual(kinds(itemsForTerm(listing.repos, listing.worktrees, "new@timber")), ["create"]); }); }); describe("display sorting", () => { const rows = [ - { name: "z", repo: "a", lastCommitAt: 200 }, - { name: "a", repo: "z", lastCommitAt: 100 }, - { name: "a", repo: "a", lastCommitAt: 200 }, + { name: "z", repo: "a" }, + { name: "a", repo: "z" }, + { name: "a", repo: "a" }, { name: "b", repo: "a" }, ]; for (const [mode, expected] of [ - [undefined, ["a@a", "z@a", "a@z", "b@a"]], + [undefined, ["z@a", "a@z", "a@a", "b@a"]], ["repo", ["a@a", "b@a", "z@a", "a@z"]], ["worktree", ["a@a", "a@z", "b@a", "z@a"]], ]) { @@ -139,10 +150,14 @@ describe("display sorting", () => { assert.equal(rows[0].name, "z", "sorting does not reorder the cache"); }); } - it("uses scan timestamps and tolerates old records without a date", () => { - const listing = parseListing("R\ttimber\nW\told@timber\t/tmp/old\nW\tnew@timber\t/tmp/new\t300\n"); - const items = itemsForTerm(listing.repos, listing.worktrees, ""); - assert.deepEqual(values(items), ["new@timber", "old@timber"]); + it("restores Timber's recency order after another sort mode", () => { + const listing = parseListing("R\ttimber\nD\t" + JSON.stringify([ + { name: "z-new", repo: "timber", path: "/tmp/new" }, + { name: "a-old", repo: "timber", path: "/tmp/old" }, + ])); + assert.deepEqual(values(itemsForTerm(listing.repos, listing.worktrees, "", "worktree")), ["a-old@timber", "z-new@timber"]); + const items = itemsForTerm(listing.repos, listing.worktrees, "", "recency"); + assert.deepEqual(values(items), ["z-new@timber", "a-old@timber"]); assert.equal(items[0].path, "/tmp/new"); }); });