-
Notifications
You must be signed in to change notification settings - Fork 0
/
executable_dot_zsh_functions
488 lines (433 loc) · 14 KB
/
executable_dot_zsh_functions
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
#!/bin/zsh
# -*-mode:zsh-*- vim:ft=zsh
#
# ~/.zsh_functions
# ====================================
#
# 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
#
function __remove_alias() {
local CMDTYPE=$(type "$1")
case $CMDTYPE in
*"alias"*)
unalias $1 2> >(grep -Ev 'no such hash table element' >&2)
;;
*"function"*)
echo -e "\u001b[34mError: alias is a function\u001b[0m"
;;
*"not found"*)
;;
*)
echo -e "Error: unknown command type for $1 return message is '$CMDTYPE'"
;;
esac
}
function __alias () {
__remove_alias "$1"
alias "${1}"="${2}"
}
# Print paths on new line and count
function syspath(){
echo $PATH | sed 's/:/\n/g' | sort | uniq -c
}
# Open Marked 2, passing provided file path to the application
function marked() {
if [ -n "${1}" ]; then
open -a "Marked 2" "${1}"
else
open -a "Marked 2"
fi
}
# Print the difference between the target state and the destination state for
# targets. If no targets are specified, print the differences for all targets.
function chezmoidiff() {
if [ -n "${1}" ]; then
chezmoi diff --format=git "${1}" | delta
else
chezmoi diff --format=git
fi
}
# Install requirements.txt in conda environment
#
# Original solution via StackOverflow:
# http://stackoverflow.com/questions/35802939/install-only-available-packages-using-conda-install-yes-file-requirements-t
#
function conda_install_requirements() {
# Install via `conda` directly.
# This will fail to install all
# dependencies. If one fails,
# all dependencies will fail to install.
conda install --yes --file requirements.txt
#
# To go around issue above, one can
# iterate over all lines in the
# requirements.txt file.
while read requirement; do conda install --yes $requirement; done < requirements.txt
}
# using ripgrep combined with preview
# find-in-file - usage: fif <searchTerm>
# reference: https://github.com/junegunn/fzf/wiki/examples#searching-file-contents
function fif() {
if [ ! "$#" -gt 0 ]; then
echo "Need a string to search for!"
return 1
fi
rg --files-with-matches --no-messages "$1" | fzf \
-m \
--preview "highlight -O ansi -l {} 2> /dev/null | rg --colors 'match:bg:yellow' --ignore-case --pretty --context 10 '$1' || rg --ignore-case --pretty --context 10 '$1' {}" \
--bind="f9:execute:hx {} < /dev/tty"
}
# an alternative to the above using ripgrep-all (rga)
function fid() {
if [ ! "$#" -gt 0 ]; then
echo "Need a string to search for!"
return 1
fi
rga --files-with-matches --no-messages "$1" | fzf \
-m \
--preview "highlight -O ansi -l {} 2> /dev/null | rg --colors 'match:bg:yellow' --ignore-case --pretty --context 10 '$1' || rg --ignore-case --pretty --context 10 '$1' {}" \
--bind="f9:execute:hx {} < /dev/tty"
}
# fbc - fuzzy Find Branch 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 branches branch
branches=$(git for-each-ref --count=30 --sort=-committerdate refs/heads/ --format="%(refname:short)") &&
branch=$(echo "$branches" |
fzf-tmux -d $((2 + $(wc -l <<<"$branches"))) +m) &&
git checkout $(echo "$branch" | sed "s/.* //" | sed "s#remotes/[^/]*/##")
}
__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 show --color=always % | diff-so-fancy'"
# 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 fshow_preview() {
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 | less -R" \
--bind "alt-y:execute:$_gitLogLineToHash | xclip"
}
# 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/ .*//")
}
# Check the content length of a file and print size in MB
function contentlength() {
if [[ ! -z "$1" ]]; then
curl -sLI $1 | awk 'tolower($1) ~ /content-length/ {print $1, ($2/1000000), "MB"}'
else
echo "Enter URL to file"
fi
}
function update_tmux() {
echo " ";
echo " | | ._ _| _. _|_ _ _|_ ._ _ ._ | _ o ._ _ ";
echo " |_| |_) (_| (_| |_ (/_ |_ | | | |_| >< |_) | |_| (_| | | | _> ";
echo " | | _| ";
echo -e ' \u001b[34mUpdate all tmux plugins\u001b[0m'
echo -e ' \u001b[34mTPM updating plugins\u001b[0m'
echo -e '==========================='
echo -e ' \u001b[34mCreating TMUX main session or attaching if exists\u001b[0m'
tmux new-session -A -s main
if $HOME/.tmux/plugins/tpm/bin/update_plugins all; then
echo -e '==========================='
echo -e ' \u001b[34mTMUX plugins updated\u001b[0m'
if tmux source-file $HOME/.tmux.conf; then
echo -e ' \u001b[34mSourced tmux config\u001b[0m'
else
echo -e ' \u001b[34mError sourcing tmux configuration\u001b[0m'
fi
else
echo -e '==========================='
echo -e ' \u001b[34mError updating tmux plugins\u001b[0m'
echo -e ' \u001b[34mvisit: https://github.com/tmux-plugins/tpm/blob/master/docs/managing_plugins_via_cmd_line.md\u001b[0m'
fi
}
# fuzzy find alias
function fzfa() {
alias | bat --paging=never -n -f -l bash | fzf --ansi
}
# cd to the directory ranger was at when it closed
function rangerdir() {
if [ -f "$HOME/.rangerdir" ] && [ "$(awk '{print $1}' $HOME/.rangerdir)" != "$(echo -n `pwd`)" ];
then
cd -- "$(awk '{print $1}' $HOME/.rangerdir)"
fi
}
# Kubernetes namesapce visualization tool
# https://github.com/viralpoetry/kubesurveyor
function k8nsv() {
if [[ ! -z "$1" ]]; then
echo "Saving namespace data for $1"
kubesurveyor $1 --insecure --save > namespace.yaml
cat namespace.yaml| kubesurveyor $1 --load --out png
trash "$1"
else
echo "Namespace required"
fi
}
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() {
i=1
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/..$//';
c=''
}
function edit_dot_files() {
if (( ${+commands[chezmoi]} )) && (( ${+commands[zed]} )) && [[ -d $CHEZMOI_SOURCE_PATH ]]; then
zed --wait --new $CHEZMOI_SOURCE_PATH
chezmoi apply
fi
}
function update_term_tools() {
if (( ${+commands[atuin]} )); then
atuin sync
fi
if (( ${+commands[zpm]} )); then
zpm clean
zpm upgrade
fi
}
function has_tldr_page() {
tldr --language en "$1" > /dev/null 2>&1
}
function has_man_page() {
man "$1" > /dev/null 2>&1
}
function help() {
# Get some help for this command prefering the
#
if [[ -z "$1" ]]; then
echo "No command specified. The input string is empty."
else
if has_tldr_page "$1"; then
tldr "$@"
return
fi
if has_man_page "$1"; then
if (( ${+commands[batman]} )); then
batman "$@"
return
else
man "$1"
return
fi
fi
fi
"$@" --help 2>&1 | bat --plain --language=help
}
# Debug what the heck is going on with gpg
function debug-gpg(){
echo RELOADAGENT | gpg-connect-agent
echo "test" | gpg --clearsign
}
function sbt_clear_cache(){
echo -e "\nRun with '-a' to clean all cache files\n"
if [[ $1 == "-a" ]]; then
echo -e "\nEmptying the maven cache (this may take some time to rebuild)\n"
rm -fvr ~/.m2/repository
echo -e "\nEmptying the ivy cache (this may take some time to rebuild)\n"
rm -fvr ~/.ivy2/cache/*
find ~/.sbt ~/.ivy2 -name "*.lock" -print -delete
find ~/.sbt ~/.ivy2 -name "ivydata-*.properties" -print -delete
echo -e "\nRemoving all sbt project related class files\n"
rm -fvr ~/.sbt/1.0/plugins/target
rm -fvr ~/.sbt/1.0/plugins/project/target
rm -fvr ~/.sbt/1.0/target
rm -fvr ~/.sbt/0.13/plugins/target
rm -fvr ~/.sbt/0.13/plugins/project/target
rm -fvr ~/.sbt/0.13/target
rm -fvr ./project/target
rm -fvr ./project/project/target
rm -fvr .metals
rm -fvr .bsp
rm -fvr .bloop
fi
echo -e "\nEmptying the idl cache\n"
rm -fvr ./idl/lib
rm -fvr ~/.idl-sbt-cache
echo -e "\nRunning 'sbt clean update'\n"
rm -fvr ~/.idl-sbt-cache
sbt clean update
}
# Search all commits in heads or remotes for changes matching pattern
function grep_refs(){
echo "\t======= Searching '${1}' for '${2}' ========="
git grep -i "${2}" $(git for-each-ref --format='%(refname)' refs/"${1}")
}
function print_jvm_versions(){
echo -e "\nPrinting runtime and tool versions of the JVM.\n"
local arr=("java" "scala" "mvn" "sbt")
for i in "${arr[@]}"; do
echo -e "\n---- ${i} version ----\n"
if (( ${+commands[$i]} )); then
$i -version
fi
done
}
function afzf(){
atuin history list --cmd-only | fzf
}
function cd_with_fzf(){
echo "Use Yazi instead."
cd $HOME && cd $(fd -t d | fzf --preview="eza --long --tree --level=1 {}") && echo "${PWD}" && eza --long --tree --level=2
}
function batFollow(){
echo -e "\nNot the best tool. Consider these alternatives;"
echo "- batwatch"
echo "- lnav"
tail -f "${1}" | bat -l syslog --paging=never
}
function extract_file_from_image(){
if [ $# -eq 3 ]; then
echo -e "\nExtracting file [$2] from image [$1]"
echo -e "Saving file to [$3]\n"
local image=$1
local source_path=$2
local destination_path=$3
local container_id=$(docker create "$image")
docker cp "$container_id:$source_path" "$destination_path"
docker rm "$container_id"
else
echo -e "\nRequires <image id> <source path> <destination path>"
fi
}
function is_installed_by_brew(){
# Check if the file exists
local file="$1"
if [[ ! -e "$file" ]]; then
# Return an exit code without closing the shell while having -e set.
echo "File $file does not exist." && (exit 1)
fi
if (( ${+commands[rg]} )) && (( ${+commands[brew]} )); then
# Count the number of lines in the file
local pattern_cnt=$(wc -l "$file" | awk '{print $1}')
local rg_output=$(brew list --versions | rg -f "$file")
local line_count=$(echo "$rg_output" | sort | uniq | wc -l | awk '{print $1}')
# Compare line count with pattern_cnt
if (( "$line_count" == "$pattern_cnt" )); then
echo "The line count [$line_count] equals pattern_cnt [$pattern_cnt]." && (exit 0)
else
echo "The line count [$line_count] does not equal pattern_cnt [$pattern_cnt]." && (exit 2)
fi
else
echo "Requires ripgrep and brew to be installed." && (exit 1)
fi
}
function select_from_brew_info() {
# Select fields from brew info JSON of installed homebrew formulas.
# Defaults to 'name, full_name, desc, homepage' when field names are not provided.
if ! (( ${+commands[brew]} )) || ! (( ${+commands[duckdb]} )); then
echo "Requires brew and duckdb to be installed" && (exit 1)
fi
local _fields
local default_fields="name, full_name, \"desc\""
local brew_info_json_path=$TMPDIR/brew_info_.json
local query_rslt_path=$TMPDIR/brew_info_result.csv
local _fields=$default_fields
if [[ -z "$1" ]]; then
_fields=$default_fields
else
_fields="$1"
fi
local query=$(print -r -- "COPY (
select $_fields
from read_json_auto('${brew_info_json_path}', ignore_errors := true)
) TO '${query_rslt_path}';
")
brew info --installed --json > $brew_info_json_path
echo -e "\nQuerying brew info table of installed formulas"
echo -e "\tQuery: [$query]"
echo -e "\tInput path: $brew_info_json_path"
echo -e "\tOutput path: $query_rslt_path"
duckdb -c "${query}"
bat $query_rslt_path
}
function print_pr_basics(){
if (( ${+commands[gh]} )); then
gh pr view $1 --json number,title,url,state,labels --template \
'[#{{ .number }}] {{.title}}
{{.state}} | {{.url}}
{{.labels | join ", "}}
'
exit 0
else
echo "Requires gh to be installed." && (exit 1)
exit 1
fi
}
function print_pr_failed_checks(){
local template='
{{- range . }}
{{- if eq .state "FAILURE" }}
{{ .name }} | {{ .description }}
{{- end }}
{{- end }}
'
if (( ${+commands[gh]} )); then
gh pr checks $1 --json name,description,state --template $template | bat --plain
exit 0
else
echo "Requires gh to be installed." && (exit 1)
exit 1
fi
}
function print_pr_review_request(){
local ask="Please review the following PR:"
local header=$(print_pr_basics)
local body=$(print_pr_failed_checks)
local msg="$ask\n$header\n$body"
echo -e "$msg"
}