-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutable_dot_zsh_functions
More file actions
509 lines (458 loc) · 15.8 KB
/
Copy pathexecutable_dot_zsh_functions
File metadata and controls
509 lines (458 loc) · 15.8 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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
#!/usr/bin/env zsh
# -*-mode:zsh-*- vim:ft=zsh
#
# ~/.zsh_functions
# ====================================
#
# Change the current working when exiting yazi
function y() {
local tmp="$(mktemp -t "yazi-cwd.XXXXXX")" cwd
yazi "$@" --cwd-file="$tmp"
IFS= read -r -d '' cwd < "$tmp"
[ -n "$cwd" ] && [ "$cwd" != "$PWD" ] && builtin cd -- "$cwd"
rm -f -- "$tmp"
}
# Print path to command if exist
function cmd_path() {
if [[ $ZSH_VERSION ]]; then
whence -cp "$1" 2> /dev/null
else # bash
type -P "$1" # No output if not in $PATH
fi
}
#
# Alias helper functions
#
# Overwrite alias if argument is an aliase otherwi
function __alias () {
if (( $+aliases[$1] )); then
unalias "$1"
alias "$1"="$2"
elif type -w "$1" >/dev/null 2>&1; then
local x=$(type -w "$1")
echo "'$1' cannot be assigned as an alias, already exists as: '$x'" >&2
else
alias "$1"="$2"
fi
}
# Print paths on new line and count
function syspath(){
echo $PATH | sed 's/:/\n/g' | sort | uniq -c
}
# fbc - fuzzy Find Branch or tag to Checkout
# checkout git branch (including remote branches), sorted by most recent commit, limit 30 last branches
# reference: https://github.com/junegunn/fzf/wiki/examples#git
function fcb() {
local tags branches target
branches=$(
git --no-pager branch --all \
--format="%(if)%(HEAD)%(then)%(else)%(if:equals=HEAD)%(refname:strip=3)%(then)%(else)%1B[0;34;1mbranch%09%1B[m%(refname:short)%(end)%(end)" \
| sed '/^$/d') || return
tags=$(
git --no-pager tag | awk '{print "\x1b[35;1mtag\x1b[m\t" $1}') || return
target=$(
(echo "$branches"; echo "$tags") |
fzf --no-hscroll --no-multi -n 2 \
--ansi) || return
git checkout $(awk '{print $2}' <<<"$target" )
}
alias glNoGraph='git log --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr% C(auto)%an"'
_gitLogLineToHash="echo {} | grep -o '[a-f0-9]\{7\}' | head -1"
_viewGitLogLine="$_gitLogLineToHash | xargs -I % sh -c 'git -c diff.external=difft show --ext-diff %'"
# fcoc_preview - checkout git commit with previews
function fcoc_preview() {
local commit
commit=$(glNoGraph |
fzf --no-sort --reverse --tiebreak=index --no-multi \
--ansi --preview="$_viewGitLogLine") &&
git checkout $(echo "$commit" | sed "s/ .*//")
}
# fshow_preview - git commit browser with previews
function glshow() {
glNoGraph "$@" |
fzf --no-sort --reverse --tiebreak=index --no-multi \
--ansi --preview="$_viewGitLogLine" \
--header "enter to view, alt-y to copy hash" \
--bind "enter:execute:$_viewGitLogLine" \
--bind "alt-y:execute:$_gitLogLineToHash | pbcopy"
}
# fcs - get git commit sha
# example usage: git rebase -i `fcs`
function fcs() {
local commits commit
commits=$(git log --color=always --pretty=oneline --abbrev-commit --reverse) &&
commit=$(echo "$commits" | fzf --tac +s +m -e --ansi --reverse) &&
echo -n $(echo "$commit" | sed "s/ .*//")
}
# fuzzy find alias
function fzfa() {
alias | bat --paging=never -n -f -l bash | fzf --ansi
}
function print_color_band() {
echo -n "
# Check term support for true color. Prints a color band showing gradients
# if there is a difference between gradients i.e no smooth color band, then
# there is something wrong with true color support.
#
# See clicolors() for full list of console colors
"
awk 'BEGIN{
s="/\\/\\/\\/\\/\\"; s=s s s s s s s s;
for (colnum = 0; colnum<77; colnum++) {
r = 255-(colnum*255/76);
g = (colnum*510/76);
b = (colnum*255/76);
if (g>255) g = 510-g;
printf "\033[48;2;%d;%d;%dm", r,g,b;
printf "\033[38;2;%d;%d;%dm", 255-r,255-g,255-b;
printf "%s\033[0m", substr(s,colnum+1,1);
}
printf "\n";
}'
}
# colors, a lot of colors!
function clicolors() {
local i=1
local c=""
for color in {000..255}; do
c=$c"$FG[$color]$color✔$reset_color ";
if [ `expr $i % 8` -eq 0 ]; then
c=$c"\n"
fi
i=`expr $i + 1`
done;
echo $c | sed 's/%//g' | sed 's/{//g' | sed 's/}//g' | sed '$s/..$//';
}
function edit_dot_files() {
if (( ${+commands[chezmoi]} )) && (( ${+commands[nvim]} )) && [[ -d $CHEZMOI_SOURCE_PATH ]]; then
nvim $CHEZMOI_SOURCE_PATH
chezmoi apply
fi
}
function has_man_page() {
man "$1" > /dev/null 2>&1
}
function help() {
# NAME
# help - Get help for a command
#
# SYNOPSIS
# help <command>
#
# DESCRIPTION
# Displays help information for a given command.
# It first checks for a man page and displays it if available.
# If 'batman' is installed, it's used to display the man page.
# If no man page is found, it attempts to run the command with the '--help' flag
# and pipes the output to 'bat' for syntax highlighting.
#
# PARAMETERS
# $1 - The command to get help for.
#
# EXAMPLES
# help ls
# help git commit
#
if [[ -z "$1" ]]; then
echo "No command specified. The input string is empty."
return 1
fi
local command_name="$1"
local has_man=false
# Check if man page exists
if has_man_page "$command_name"; then
has_man=true
fi
# Show man page if available (prefer batman if installed)
if [[ "$has_man" == "true" ]]; then
if (( ${+commands[batman]} )); then
batman "$@"
else
man "$command_name"
fi
echo
fi
# Show --help output if no man page found
if [[ "$has_man" == "false" ]]; then
"$@" --help 2>&1 | bat --plain --language=help
echo
fi
}
function print_pr_basics() {
if ! (( ${+commands[gh]} )); then
echo "Requires gh to be installed."
return 1
fi
if [[ "$1" == "slack" ]]; then
local template='
#### {{.title}}
- Number: {{.number}}
- Title: {{.title}}
- State: {{.state}}
- Is Draft: {{.isDraft}}
- Updated At: {{.updatedAt}}
- Merge Status: {{.mergeStateStatus}}
- URL: (PR:{{.number}})[{{.url | printf "%.120s"}}]
'
gh pr view --json number,title,url,updatedAt,state,author,isDraft,mergeable,mergeStateStatus --template "$template" | mdcat --
else
local template='
#### {{.title}}
| Attribute | Value |
|-----------------|----------------------------|
| State | {{.state}} |
| Is Draft PR | {{.isDraft}} |
| Updated At | {{.updatedAt}} |
| Merge Status | {{.mergeStateStatus}} |
| URL | (PR:{{.number}})[{{.url | printf "%.120s"}}] |
'
gh pr view --json number,title,url,updatedAt,state,author,isDraft,mergeable,mergeStateStatus --template "$template" | mdcat --
fi
}
function print_pr_failed_checks(){
local template='
Failed Checks:
--------------
{{- range . }}
{{- if eq .state "FAILURE" }}
{{ .name }}: {{ .description }}
{{- end }}
{{- end }}
'
if (( ${+commands[gh]} )); then
gh pr checks $1 --json name,description,state --template $template
return 0
else
echo "Requires gh to be installed." && (return 1)
return 1
fi
}
function print_pr_review_request(){
local ask="Please review the following PR(s):"
local header=$(print_pr_basics)
local body=$(print_pr_failed_checks)
if ! (( $+commands[mdcat] )); then
print -u2 "mdcat command not found. Please install mdcat to view markdown."
return 1
fi
if ! (( $+commands[gmktemp] )); then
print -u2 "gmktemp command not found. Please install coreutils."
return 1
fi
local tmp_md=$(gmktemp --suffix=.md pr_review_XXXXXX)
printf "%s\n%s\n%s\n" "$ask" "$header" "$body" > "$tmp_md"
mdcat "$tmp_md"
}
# Git worktrees cd hook - enables `git worktrees` to change parent shell directory
function _git_worktrees_cd_hook() {
local target_file="${TMPDIR:-/tmp}/git-worktrees-cd-target"
if [[ -f "$target_file" ]]; then
local dir
dir="$(<"$target_file")"
rm -f "$target_file"
# Use cd (not builtin cd) to trigger direnv wrapper
[[ -d "$dir" ]] && cd "$dir"
fi
}
# Register hook only if add-zsh-hook is available
# precmd is a special function in zsh that runs automatically before each prompt is displayed.
# ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
# │ User runs │────▶│ Command │────▶│ precmd() │────▶│ Prompt │
# │ command │ │ executes │ │ runs │ │ displayed │
# └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
if (( ${+functions[add-zsh-hook]} )); then
add-zsh-hook precmd _git_worktrees_cd_hook
fi
function watch_pr_checks() {
# NAME
# watch_pr_checks - Watch a PR's CI checks until they finish
#
# SYNOPSIS
# watch_pr_checks [number|url|branch]
# watch_pr_checks -h|--help
#
# DESCRIPTION
# Polls CI checks on a pull request, reprinting the status table each
# interval until every check has left the pending state (or until the
# operator interrupts with Ctrl-C).
#
# - Defaults to the open PR for the current branch when no argument is given.
# - Always prints the full gh checks table (name, description, elapsed, url).
# - On completion, logs the final state and prints a full link to the PR.
# - A Ghostty OSC 777 desktop notification is sent only when all checks pass.
# No alert is sent on failure or interrupt.
# - A PR with zero checks is treated as already passed.
#
# EXIT CODES
# 0 all checks passed (or no checks reported)
# 1 one or more checks failed/cancelled, or PR/lookup error
# 130 interrupted with Ctrl-C
#
# DEPENDENCIES
# gh; gum is used for structured logging when available.
#
# EXAMPLES
# watch_pr_checks
# watch_pr_checks 123
# watch_pr_checks feature/my-branch
# watch_pr_checks --help
#
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
# Print the leading man-style docstring from this function's source file.
# functions_source (zsh/parameter) records the path a function was sourced from.
zmodload zsh/parameter 2>/dev/null
local src_file="${functions_source[$0]-}"
if [[ -n "$src_file" && -r "$src_file" ]]; then
command awk -v fn="$0" '
$0 ~ ("^function[[:space:]]+" fn "[[:space:]]*[(]") { in_fn = 1; next }
in_fn && /^[[:space:]]*#/ {
line = $0
sub(/^[[:space:]]*# ?/, "", line)
print line
next
}
in_fn { exit }
' "$src_file"
else
print -r -- "Usage: $0 [number|url|branch]"
print -r -- "Watch a PR's CI checks until they finish. See source for full docs."
fi
return 0
fi
local -i poll_interval=10
local pr_id="${1:-}"
if ! (( ${+commands[gh]} )); then
if (( ${+commands[gum]} )); then
gum log --time rfc822 --level error "Required command (gh) not found."
else
print -u2 "Required command (gh) not found."
fi
return 1
fi
local pr_number pr_url pr_head pr_meta
# Single gh call; built-in --jq avoids an external jq dependency.
if ! pr_meta=$(gh pr view ${pr_id:+"$pr_id"} \
--json number,url,headRefName \
--jq '[.number, .url, .headRefName] | @tsv' 2>/dev/null) \
|| [[ -z "$pr_meta" ]]; then
if (( ${+commands[gum]} )); then
gum log --time rfc822 --level error "Could not find PR ${pr_id:-for current branch}"
else
print -u2 "Could not find PR ${pr_id:-for current branch}"
fi
return 1
fi
pr_number=${pr_meta%%$'\t'*}
pr_meta=${pr_meta#*$'\t'}
pr_url=${pr_meta%%$'\t'*}
pr_head=${pr_meta#*$'\t'}
local watch_label="${pr_head:-PR} #${pr_number}"
if (( ${+commands[gum]} )); then
gum log --time rfc822 --level info "Watching checks for ${watch_label}..."
else
print "Watching checks for ${watch_label}..."
fi
# Clean exit on operator interrupt — no pass alert
trap 'if (( ${+commands[gum]} )); then
gum log --time rfc822 --level warn "Stopped watching PR #${pr_number} (interrupted)."
else
print -u2 "Stopped watching PR #${pr_number} (interrupted)."
fi
trap - INT
return 130' INT
# gh pr checks --watch streams the status table until checks leave pending.
# Exit codes: 0=all pass, 1=failure, 2=cancelled (gh), 130=SIGINT.
local -i checks_ec
gh pr checks ${pr_id:+"$pr_id"} --watch --interval "$poll_interval"
checks_ec=$?
trap - INT
# If the watch was interrupted (shell or gh cancel), exit without a fail alert.
if (( checks_ec == 130 || checks_ec == 2 )); then
if (( ${+commands[gum]} )); then
gum log --time rfc822 --level warn "Stopped watching PR #${pr_number} (interrupted)."
else
print -u2 "Stopped watching PR #${pr_number} (interrupted)."
fi
return 130
fi
# Final line includes a full link to the PR.
# On a TTY, wrap the label in OSC-8 so "Click here..." is clickable; always
# append the bare URL so the full link is copyable in logs/scrollback too.
local pr_link
if [[ -n "$pr_url" && -t 1 ]]; then
pr_link=$'\e]8;;'"${pr_url}"$'\e\\'"Click here to view PR #${pr_number} on GitHub"$'\e]8;;\e\\'" ${pr_url}"
else
pr_link="Click here to view PR #${pr_number} on GitHub${pr_url:+ ${pr_url}}"
fi
if (( checks_ec == 0 )); then
# Pass-only Ghostty OSC 777 notification
# Sequence: ESC ] 777 ; notify ; TITLE ; MESSAGE BEL
printf '\e]777;notify;%s;✅ PR #%s checks passed\a' "${pr_head:-pr}" "$pr_number"
if (( ${+commands[gum]} )); then
gum log --time rfc822 --level info "Checks finished with state: SUCCESS"
else
print "Checks finished with state: SUCCESS"
fi
print -r -- "$pr_link"
return 0
fi
if (( ${+commands[gum]} )); then
gum log --time rfc822 --level info "Checks finished with state: FAILURE"
else
print "Checks finished with state: FAILURE"
fi
print -r -- "$pr_link"
return 1
}
# set_java_home_to <version>
# Sets JAVA_HOME and updates PATH for the specified Java version using Coursier.
# Usage: set_java_home_to 8
function set_java_home_to() {
local version="$1"
if [[ -z "$version" ]]; then
gum log --level info "Usage: set_java_home_to <version>\n"
return 1
fi
local old=$(java -version 2>&1 | head -n 1)
export JAVA_HOME="$(cs java-home --architecture arm64 --jvm "corretto:${version}")"
export PATH="$JAVA_HOME/bin:${PATH}"
local new=$(java -version 2>&1 | head -n 1)
gum log --structured --level info "Changed Java version from" old $old to new $new
}
# Enhanced function to set Java version with .envrc creation
# Usage: set_java_version 8
function set_java_version() {
local version=${1:-"17"}
export PROJECT_JAVA_VERSION="$version"
export JAVA_HOME="$(cs java-home --architecture arm64 --jvm corretto:${version})"
export PATH="${JAVA_HOME}/bin:${PATH}"
# Create .envrc for persistence
cat > .envrc << EOF
export PROJECT_JAVA_VERSION="${version}"
export JAVA_HOME="\$(cs java-home --architecture arm64 --jvm corretto:\${PROJECT_JAVA_VERSION})"
export PATH="\${JAVA_HOME}/bin:\${PATH}"
export METALS_JAVA_HOME="\$(cs java-home --architecture arm64 --jvm corretto:17)"
EOF
gum log --structured --level info "✓ Java version set to ${version}"
gum log --structured --level info "✓ Created .envrc - run 'direnv allow' for auto-switching"
}
# Override cd to support automatic direnv reloading
function cd() {
builtin cd "$@"
if [[ -f .envrc ]] && command -v direnv >/dev/null 2>&1; then
direnv reload
fi
}
function print_login_connecting_msg(){
# Get the SSH config details
local SSH_CONFIG_DETAILS=$(ssh -G $1 | rg '^(host\b|hostname\b|user\b)')
# Style the header
local HEADER=$(gum style --foreground "#90EE90" "Connecting to...")
# Style the details (e.g., with a different color or border)
local DETAILS=$(gum style \
--foreground "#ADD8E6" \
--padding "0 1" \
"$SSH_CONFIG_DETAILS")
# Join them vertically
gum join --vertical "$HEADER" "$DETAILS"
}