main
 1#!/usr/bin/env bash
 2# Open a Pi tab in the Herdr workspace belonging to the selected Lazyworktree
 3# worktree. Lazyworktree passes WORKTREE_PATH to custom commands.
 4set -euo pipefail
 5
 6: "${WORKTREE_PATH:?WORKTREE_PATH must be set by lazyworktree}"
 7
 8herdr_bin="${HERDR_BIN:-herdr}"
 9worktree_path="$(realpath --no-symlinks --canonicalize-missing -- "$WORKTREE_PATH")"
10worktree_key="v1:$(printf %s "$worktree_path" | sha256sum | cut -c1-32)"
11
12workspaces="$($herdr_bin workspace list)"
13workspace_id="$(jq -er --arg key "$worktree_key" '
14  [.result.workspaces[] | select(.tokens.lazyworktree_id == $key)]
15  | if length == 0 then empty
16    elif length == 1 then .[0].workspace_id
17    else error("multiple Herdr workspaces are tagged for this worktree")
18    end
19' <<<"$workspaces" 2>/dev/null || true)"
20
21if [[ -z "$workspace_id" ]]; then
22  created="$($herdr_bin workspace create \
23    --cwd "$worktree_path" \
24    --label "$(basename -- "$worktree_path")" \
25    --no-focus)"
26  workspace_id="$(jq -er '.result.workspace.workspace_id' <<<"$created")"
27  "$herdr_bin" workspace report-metadata "$workspace_id" \
28    --source lazyworktree \
29    --token "lazyworktree_id=$worktree_key"
30fi
31
32tabs="$($herdr_bin tab list --workspace "$workspace_id")"
33pi_tab_id="$(jq -er '
34  [.result.tabs[] | select(.label == "pi")]
35  | if length == 0 then empty
36    elif length == 1 then .[0].tab_id
37    else error("multiple Pi tabs exist in the Herdr workspace")
38    end
39' <<<"$tabs" 2>/dev/null || true)"
40
41if [[ -n "$pi_tab_id" ]]; then
42  exec "$herdr_bin" tab focus "$pi_tab_id"
43fi
44
45created_tab="$($herdr_bin tab create \
46  --workspace "$workspace_id" \
47  --cwd "$worktree_path" \
48  --label pi \
49  --focus)"
50pane_id="$(jq -er '.result.root_pane.pane_id' <<<"$created_tab")"
51exec "$herdr_bin" pane run "$pane_id" pi