Repository navigation
Expand file tree
/
Copy pathzz-selector.sh
More file actions
executable file
·359 lines (315 loc) · 11.6 KB
/
Copy pathzz-selector.sh
File metadata and controls
executable file
·359 lines (315 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env bash
set -euo pipefail
# ============================================================================
# CONFIG — edit these values to suit your setup
# ============================================================================
SELECTOR="$HOME/repos/*" # shell glob: all bash syntax supported, because it's just `eval`ed
GET_DEST="$HOME/repos" # where `zz get <url>` clones into.
# ============================================================================
#
# zz - selector (glob) + zellij with fuzzy finder
#
# Workspace model: glob-based selector.
# - Repo discovery: expand SELECTOR (a shell glob pattern); each matching
# directory is treated as a repo.
# - Path resolution: absolute paths returned by the glob expansion.
# - Cloning: git clone into GET_DEST.
#
# SELECTOR examples:
# Flat: "$HOME/repos/*"
# Multi-root: "$HOME/{work,personal,oss}/*"
# Nested 2-level: "$HOME/code/*/*"
# Deep nested: "$HOME/src/**" (requires globstar, on by default)
#
# Notes on glob expansion:
# - `*`, `?`, `[...]` work as standard.
# - `**` (recursive) works because globstar is enabled.
# - Brace expansion `{a,b,c}` works because the pattern is expanded via a
# controlled `eval` (with nullglob + globstar set). Bash's brace expansion
# does not normally apply to variable expansions, so `eval` is required to
# support the natural shell syntax. The user owns SELECTOR (it's defined in
# this script), so this is no different in practice from running a glob in
# their own shell.
# - Unmatched globs produce no entries (nullglob), not the literal pattern.
# Expand SELECTOR into an array of absolute directory paths.
# Uses `eval` so brace expansion and ~ work; nullglob + globstar are set first
# so unmatched patterns disappear and `**` recursion works.
SELECTOR_PATHS=()
_zz_expand_selector() {
local pattern="${SELECTOR/#\~/$HOME}"
local expanded
expanded=$(
shopt -s nullglob globstar
# shellcheck disable=SC2086,SC2294
eval "printf '%s\n' $pattern"
)
SELECTOR_PATHS=()
while IFS= read -r p; do
[[ -n "$p" ]] && SELECTOR_PATHS+=("$p")
done <<< "$expanded"
}
# Normalize ~ in GET_DEST (in case the user wrote a literal tilde rather than
# using "$HOME").
_zz_resolve_get_dest() {
GET_DEST="${GET_DEST/#\~/$HOME}"
}
#=============================================================================
# Utilities
#=============================================================================
die() {
echo "Error: $1" >&2
exit 1
}
# List all repo paths (absolute) matched by SELECTOR, excluding git worktrees.
list_repos() {
local dir
for dir in "${SELECTOR_PATHS[@]}"; do
[[ -d "$dir" ]] || continue
dir="${dir%/}"
# worktrees have a .git file, not a .git directory
[[ -d "$dir/.git" || ! -e "$dir/.git" ]] && echo "$dir"
done
# Guard against the final compound `[[ ... ]] && echo` returning 1 when the
# last entry is filtered out — under `set -e` (bash 5.x), a non-zero return
# from a function invoked via command substitution propagates into the
# variable assignment and aborts the script.
return 0
}
# List repos that have active zz sessions
list_session_repos() {
local sessions
sessions=$(list_zz_sessions)
[[ -z "$sessions" ]] && return 1
while read -r s; do
lookup_path_from_session "$s" 2>/dev/null
done <<< "$sessions"
# Guard against the final `lookup_path_from_session` returning 1 (stale
# session for a deleted repo) when it's the last entry — under `set -e`,
# that propagates through command substitution and aborts the caller.
return 0
}
# Full path -> session name
path_to_session() {
local relpath="${1#$HOME/}"
echo "zz:${relpath//\//.}"
}
# Session name -> full path (O(n) lookup via list_repos)
lookup_path_from_session() {
local session=${1#zz:}
while IFS= read -r repo_path; do
if [[ "$(path_to_session "$repo_path")" == "zz:$session" ]]; then
echo "$repo_path"
return 0
fi
done < <(list_repos)
return 1
}
# Query matching
# 1. path query (starts with . or /): accept any existing directory
# 2. exact basename match: narrow candidates to it for 3 and 4
# 3. zoxide frecency match filtered to selector candidates
# 4. fallback: substring match against full path (for repos not yet in zoxide DB)
query_match() {
local candidates="$1"; shift
local query="$*"
# 1. path query: accept any existing directory, not just selector repos
if [[ "$query" == .* || "$query" == /* ]]; then
local resolved
resolved=$(realpath -m "$query")
[[ -d "$resolved" ]] || die "Not a directory: $query"
echo "$resolved"
return
fi
# 2. exact basename match: without this, `zz foo` opens foo-bar whenever
# zoxide ranks it above foo.
if [[ $# -eq 1 ]]; then
local exact
exact=$(awk -F/ -v q="$1" '$NF == q' <<< "$candidates")
if [[ -n "$exact" ]]; then
candidates="$exact"
fi
fi
# 3. zoxide: frecency-ranked match, filtered to selector candidates
# Note: `|| true` prevents pipefail from exiting when zoxide or the while
# loop exits non-zero (no match found).
local match
match=$(zoxide query --list -- "$@" 2>/dev/null | while IFS= read -r p; do
echo "$candidates" | grep -qxF "$p" && echo "$p" && break
done) || true
[[ -n "$match" ]] && { echo "$match"; return; }
# 4. fallback for repos not yet in zoxide DB
match=$(echo "$candidates" | while IFS= read -r p; do
local ok=1
for word in "$@"; do
[[ "$p" != *"$word"* ]] && ok=0 && break
done
[[ $ok -eq 1 ]] && echo "$p"
done | head -1) || true
[[ -n "$match" ]] && { echo "$match"; return; }
die "No match: $query"
}
select_repo() {
local candidates
if [[ "$SESSION_ONLY" == true ]]; then
candidates=$(list_session_repos) || die "No zz sessions found."
else
candidates=$(list_repos)
fi
[[ -z "$candidates" ]] && die "No repos found."
if [[ $# -gt 0 ]]; then
query_match "$candidates" "$@"
else
local prompt="Repo: "
[[ "$SESSION_ONLY" == true ]] && prompt="Session: "
fzf --prompt="$prompt" -1 <<< "$candidates" || die "No selection"
fi
}
#=============================================================================
# Zellij helpers
#=============================================================================
list_zz_sessions() {
zellij list-sessions -s 2>/dev/null | grep '^zz:' || true
}
open_zellij_session() {
local session_name="$1" repo_path="$2"
if zellij list-sessions -s 2>/dev/null | grep -qx "$session_name"; then
zellij attach "$session_name"
else
zellij -s "$session_name" options --default-cwd "$repo_path"
fi
}
#=============================================================================
# Commands
#=============================================================================
cmd_help() {
cat <<'EOF'
Usage: zz [command] [args]
Selector (glob) + zellij session manager
Commands:
[query] Select repo (basename match) → zellij session
a, attach [q] Alias for default (explicit attach)
query [q] Print the full path of the selected repo
get <url> Clone repo (git clone into GET_DEST)
list, ls List existing zz sessions
list -a, --all List all repos with session status
delete, d [q] Delete zellij session
delete -a, --all Delete all zz sessions
Flags:
-s, --session Select from existing zz sessions only
-h, --help Show this help
Configuration:
Edit the CONFIG block at the top of this script. Two values:
SELECTOR — shell glob pattern matched directly to repo dirs.
`*`, `?`, `[...]`, `**` (globstar) and `{a,b,c}` (brace
expansion) all work. Unmatched globs are skipped silently.
GET_DEST — destination dir for `zz get`.
Examples:
zz # interactive select repo (fzf) → zellij session
zz myrepo # attach to repo matching "myrepo" by basename
zz query # print selected repo path
zz query foo # print path of repo matching "foo"
zz ls # list existing sessions
zz ls -a # list all repos with session status
zz -s # select from existing sessions
zz d myrepo # delete session matching "myrepo"
zz d -a # delete all zz sessions
EOF
}
cmd_attach() {
[[ -n "${ZELLIJ:-}" ]] && die "cannot switch sessions from inside zellij. Detach first with Ctrl+o d"
local repo_path
repo_path=$(select_repo "$@")
zoxide add "$repo_path"
open_zellij_session "$(path_to_session "$repo_path")" "$repo_path"
}
cmd_ls() {
local sessions_full
sessions_full=$(zellij list-sessions -n 2>/dev/null | grep '^zz:' || true)
print_repo() {
local repo_path="$1" session_name
session_name=$(path_to_session "$repo_path")
if [[ "$sessions_full" == *"$session_name "*EXITED* ]]; then
echo -e "${RED}○${RESET} $session_name"
elif [[ "$sessions_full" == *"$session_name "* ]]; then
echo -e "${GREEN}●${RESET} $session_name"
else
echo " $session_name"
fi
}
local repos
if [[ "$LIST_ALL" == true ]]; then
repos=$(list_repos) || die "No repositories found."
else
repos=$(list_session_repos) || die "No zz sessions found."
fi
while read -r repo_path; do
print_repo "$repo_path"
done <<< "$repos"
}
cmd_delete() {
local sessions
sessions=$(list_zz_sessions)
[[ -z "$sessions" ]] && die "No zz sessions found."
if [[ "$DELETE_ALL" == true ]]; then
while read -r session; do
zellij delete-session -f "$session"
echo "Deleted session: $session"
done <<< "$sessions"
else
local session
session=$(echo "$sessions" | fzf --prompt="Delete session: " -1 -q "$*") || die "No session selected"
zellij delete-session -f "$session"
echo "Deleted session: $session"
fi
}
cmd_get() {
[[ $# -ge 1 ]] || die "Usage: zz get <url>"
[[ -d "$GET_DEST" ]] || die "GET_DEST does not exist: $GET_DEST (edit the CONFIG block at the top of this script)"
local dest="$GET_DEST/$(basename "${1%.git}")"
git clone "$1" "$dest"
zoxide add "$dest"
}
#=============================================================================
# Main
#=============================================================================
# Global constants
GREEN='\033[32m' RED='\033[31m' RESET='\033[0m'
# Global flags
SHOW_HELP=false
SESSION_ONLY=false
LIST_ALL=false
DELETE_ALL=false
args=()
parse_flags=true
for arg in "$@"; do
if [[ "$parse_flags" == true ]]; then
case "$arg" in
--) parse_flags=false ;;
-h|--help) SHOW_HELP=true ;;
-s|--session) SESSION_ONLY=true ;;
-a|--all) LIST_ALL=true; DELETE_ALL=true ;;
get) args+=("$arg"); parse_flags=false ;;
-*) die "Unknown flag: $arg" ;;
*) args+=("$arg") ;;
esac
else
args+=("$arg")
fi
done
set -- "${args[@]+"${args[@]}"}"
if [[ "$SHOW_HELP" == true ]]; then
cmd_help
exit 0
fi
# Resolve selector configuration after help-short-circuit so `--help` works
# even if config vars are unset.
_zz_expand_selector
_zz_resolve_get_dest
case "${1:-}" in
get) shift; cmd_get "$@" ;;
query) shift; select_repo "$@" ;;
list|ls) cmd_ls ;;
delete|d) shift; cmd_delete "$@" ;;
a|attach) shift; cmd_attach "$@" ;;
*) cmd_attach "$@" ;;
esac