-
Notifications
You must be signed in to change notification settings - Fork 3
/
9-functions.rc
1668 lines (1421 loc) · 49.6 KB
/
9-functions.rc
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# shellcheck disable=SC2148 disable=SC1090 shell=bash
function mkcd {
dir="$*"
mkdir -p "$dir" && cd "$dir" || exit
}
# change /dev/null to youtube-dl-"$(date +%Y%m%d-%H%M%S)".log if you want logging
function git_sparse_clone() (
rurl="$1" localdir="$2" && shift 2
mkdir -p "$localdir"
cd "$localdir"
git init
git remote add -f origin "$rurl"
git sparse-checkout init
# Loops over remaining args
for i; do
echo "$i" >>.git/info/sparse-checkout
done
git pull origin main
git sparse-checkout list
)
# A function that checks a git repo for any incorrect casing / cashing clashes and force over-rides local changes if so
git-fix-casing() {
local original_dir
original_dir=$(pwd)
cd "$1" || return 1
sh -c 'git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached'
git status
if [[ $(git ls-files -ci --exclude-standard) ]]; then
echo "There are files with incorrect casing in the git repo"
git reset --hard
git status
fi
cd "$original_dir" || return 1
}
# wrapper for adding advanced git cli customisation
alias git='git_wrapper'
git_wrapper() {
set +m # Make jobs quiet by default
# If invoked by another function, alias or xargs, interpret it as normal
if [[ -n ${FUNCNAME[*]} ]] || [[ -n $ALIASES ]] || [[ -n $XARGS ]]; then
command git "$@"
return
fi
# clone with depth=1 if no depth is not specified
if [[ $1 == "clone" ]] && [[ $* != *"--depth"* ]]; then
shift
command git clone --depth=1 "$@"
# Move into the cloned directory (taking into account the destination directory might be provided)
if [[ $* == *" "* ]]; then
local dest_dir
dest_dir=$(echo "$*" | awk '{print $NF}')
cd "$dest_dir"
else
cd "$(basename "$1" .git)"
fi
# Update the fetch configuration to track all upstream branches
git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
# Fetch all branches in the background, silently
git fetch --all --quiet #&>/dev/null &
# Move back to the original directory
cd -
else
command git "$@"
fi
set -m # Make jobs verbose again
}
function gco() {
if [[ -n $1 ]]; then
if [[ $1 == "-b" ]]; then
# shift to remove -b from args
shift 1
fi
local branchname remote_branch_exist
branchname="$1"
# If the branch name is "main" or "master" just check it out
if [[ "$branchname" == "main" ]] || [[ "$branchname" == "master" ]]; then
command git switch "$branchname"
return
fi
# check to see if the branch exists locally, if it doesn't offer to create it and check it out otherwise just check it out
if command git show-ref --verify --quiet refs/heads/"$branchname"; then
echo "Branch exists locally, switching branch..."
command git switch "$branchname"
else
echo "Checking if branch exists remotely..."
remote_branch_exist=$(command git ls-remote --heads origin "$branchname")
if [ -n "$remote_branch_exist" ]; then
echo "Branch exists remotely, checking out and pulling..."
command git fetch # origin "$branchname"
# command git checkout "$branchname" "origin/${branchname}" || echo "Error - available branches: $(git branch -v -a)"
command git switch -c "$branchname" "origin/${branchname}" || echo "Error - available branches: $(git branch -v -a)"
command git pull
else
# If the branch doesn't exist either locally or remotely
echo "Branch doesn't exist locally or remotely, creating and switching..."
command git switch -c "$branchname"
fi
fi
else
# shellcheck disable=SC2033
command git branch --sort=-committerdate | fzf --header 'Checkout Recent Branch' --preview 'git diff --color=always {1}' --pointer='>' | xargs command git switch
echo -e "${_FMT_ITL}Hint: You can check remote branches with 'gcor'${_FMT_END}"
fi
}
function gcor() {
# list all remote branches and select one with fzf git branch -v -a
command git branch -v -a | fzf --header 'Checkout Remote Branch' --preview 'git diff --color=always {1}' --pointer='>' | awk '{print $1}' | xargs command git checkout
}
function gbd() {
if [[ -n $* ]]; then
command git branch -d "$@"
else
# shellcheck disable=SC2033
command git branch --sort=-committerdate | fzf --header 'Delete Git Branch' --preview 'git diff --color=always {1}' --pointer='>' | xargs command git branch -d
fi
}
# generate_commit_msg() {
# # This function generates a commit message using the ollama API
# # Map the function to a keybinding (e.g., gcm) in your .zshrc file:
# # bindkey '^Xg' generate_commit_msg
# local -r model="tinydolphin:1.1b- v2.8-q5_ K_ M"
# local -r prompt=$(git diff --cached --name-only | xargs -I{} echo "Why did you change {}?")
# local -r api_url="http://localhost:11434/api/generate"
# }
# A function that provides an untracked_files check for other functions
function __staged_changes() {
# Display all changes including untracked files
local STAGED_FILES
STAGED_FILES=$(git diff --cached --name-only)
if [[ -n "$STAGED_FILES" ]]; then
echo "Staged files:"
echo "$STAGED_FILES"
else
echo "No staged changes to add."
# Ask the user if they want to stage all changes
echo "Do you want to add all changes to the commit? (y/n)"
read -r yn
if [[ "$yn" =~ ^[Yy]$ ]]; then
# Stage all changes
git add .
else
echo "Staging cancelled by the user."
return 1 # Return failure to indicate staging was not done
fi
fi
}
function checkout-hotfix() {
local PREFIX="hotfix-${USER}"
local DATESTAMP
DATESTAMP=$(date +%Y-%m-%d)
# If the hotfix branch already exists, append a number to the branch name, if the number already exists increment it
if command git branch -a | grep -q "$PREFIX-$DATESTAMP"; then
local COUNT=1
while git branch -a | grep -q "$PREFIX-$DATESTAMP-$COUNT"; do
COUNT=$((COUNT + 1))
done
command git checkout -b "${PREFIX}-${DATESTAMP}-${COUNT}"
else
command git checkout -b "${PREFIX}-${DATESTAMP}"
fi
}
function commit-hotfix() {
local DATESTAMP
DATESTAMP=$(date +%Y/%m/%d)
local GIT_ARGS=()
local MESSAGE=""
# Check for the '-n' flag and prepare commit options accordingly
if [[ "$1" == "-n" ]]; then
GIT_ARGS+=("-n") # Add '-n' to the git commit command options
shift # Remove '-n' from the argument list so it's not included in the commit message
fi
# After shifting '-n', all remaining arguments form the commit message
MESSAGE="$*"
# Attempt to stage changes; if the user cancels, abort the commit
if ! __staged_changes; then
echo "Commit aborted due to no changes being staged."
return 1
fi
# Proceed with commit
local CURRENT_BRANCH
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
git commit "${GIT_ARGS[@]}" -m "Hotfix-${DATESTAMP} -- ${MESSAGE}"
# Check if the commit was successful before attempting to push
if git rev-parse --verify "$CURRENT_BRANCH" >/dev/null 2>&1; then
git push --set-upstream origin "$CURRENT_BRANCH"
echo "Changes committed and pushed to $CURRENT_BRANCH."
else
echo "Failed to push changes. Branch $CURRENT_BRANCH does not exist."
fi
}
function checkout-jira() {
JIRA_BRANCH="IF-${1}-${USER}-$(date +%Y-%m-%d)"
# If the JIRA branch already exists, append the current time to the branch name
if command git branch -a | grep -q "remotes/origin/${JIRA_BRANCH}" || command git branch -a | grep -q "${JIRA_BRANCH}"; then
JIRA_BRANCH="${JIRA_BRANCH}-$(date +%H-%M-%S)"
fi
command git checkout -b "${JIRA_BRANCH}"
}
function commit-jira() {
local GIT_ARGS=()
local MESSAGE=""
local BRANCH_PREFIX CURRENT_BRANCH
# Check for the '-n' flag and prepare commit options accordingly
if [[ "$1" == "-n" ]]; then
GIT_ARGS+=("-n") # Add '-n' to the git commit command options
shift # Remove '-n' from the argument list so it's not included in the commit message
fi
# After shifting '-n', all remaining arguments form the commit message
MESSAGE="$*"
# Call the updated function to check and stage all changes
if ! __staged_changes; then
echo "Commit aborted due to no changes being staged."
return 1
fi
# add the branch prefix to the message (e.g. IF-1234 -- message)
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
BRANCH_PREFIX=$(echo "$CURRENT_BRANCH" | cut -d'-' -f1 -f2)
MESSAGE="${BRANCH_PREFIX} -- ${MESSAGE}"
# Proceed with commit
if ! git diff --cached --quiet; then
echo "No changes to commit."
# Check if the branch exists on the remote
if ! git ls-remote --heads origin "$CURRENT_BRANCH" | grep -q "$CURRENT_BRANCH"; then
# Offer to push and track the branch if it doesn't exist on the remote
echo "Current branch '$CURRENT_BRANCH' does not exist on the remote. Would you like to push it? (y/n)"
read -r yn
if [[ "$yn" =~ ^[Yy]$ ]]; then
git push --set-upstream origin "$CURRENT_BRANCH"
echo "Branch pushed and tracked on remote."
else
echo "Push cancelled by the user."
fi
fi
else
# Execute the commit with any options and the message
git commit "${GIT_ARGS[@]}" -m "$MESSAGE"
git push --set-upstream origin "$CURRENT_BRANCH"
echo "Changes committed and pushed to '$CURRENT_BRANCH'."
fi
}
# Outputs the name of the current branch
# Usage example: git pull origin "$(git_current_branch)"
# Using '--quiet' with 'symbolic-ref' will not cause a fatal error (128) if
# it's not a symbolic ref, but in a Git repo.
function git_current_branch() {
local ref
ref=$(command git symbolic-ref --quiet HEAD 2>/dev/null)
local ret=$?
if [[ $ret != 0 ]]; then
[[ $ret == 128 ]] && return # no git repo.
ref=$(command git rev-parse --short HEAD 2>/dev/null) || return
fi
echo "${ref#refs/heads/}"
}
function pr-checkout() {
local jq_template pr_number
jq_template='"''#\(.number) - \(.title)''\t''Author: \(.user.login)\n''Created: \(.created_at)\n''Updated: \(.updated_at)\n\n''\(.body)''"'
pr_number=$(
gh api 'repos/:owner/:repo/pulls' |
jq ".[] | $jq_template" |
sed -e 's/"\(.*\)"/\1/' -e 's/\\t/\t/' |
fzf \
--with-nth=1 \
--delimiter='\t' \
--preview='echo -e {2}' \
--preview-window=top:wrap |
sed 's/^#\([0-9]\+\).*/\1/'
)
if [ -n "$pr_number" ]; then
gh pr checkout "$pr_number"
fi
}
function git_add_global_prepush_hook() {
local repo_path=$1
local branch_name=$2
local hooks_path="$repo_path/.git/hooks"
# Check if the repo_path is a Git repository
if [ ! -d "$repo_path/.git" ]; then
echo "$repo_path is not a Git repository"
return 1
fi
# Create the pre-push hook if it doesn't exist
if [ ! -f "$hooks_path/pre-push" ]; then
touch "$hooks_path/pre-push"
chmod +x "$hooks_path/pre-push"
fi
# Add the code to the pre-push hook
cat <<EOF >>"$hooks_path/pre-push"
#!/usr/bin/env bash
# This script can be run as a pre-push hook locally on repositories to add messages / ensure we're not pushing to the wrong branch etc...
branch_name=$(git symbolic-ref --short HEAD)
if [ "$branch_name" == "main" ] || [ "$branch_name" == "master" ]; then
echo "WARNING: You are pushing to the $branch_name branch!"
read -r -p "Are you sure you want to push to $branch_name? [y/N] " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
echo "$response - Pushing to $branch_name"
else
echo "Aborting push"
exit 1
fi
fi
EOF
echo "Global pre-push hook added to $repo_path"
}
# Gets the number of commits ahead from remote
function git_commits_ahead() {
if command git rev-parse --git-dir &>/dev/null; then
local commits
commits="$(git rev-list --count @{upstream}..HEAD)"
if [[ "$commits" != 0 ]]; then
echo "$ZSH_THEME_GIT_COMMITS_AHEAD_PREFIX$commits$ZSH_THEME_GIT_COMMITS_AHEAD_SUFFIX"
fi
fi
}
# Gets the number of commits behind remote
function git_commits_behind() {
if command git rev-parse --git-dir &>/dev/null; then
local commits
commits="$(git rev-list --count HEAD..@{upstream})"
if [[ "$commits" != 0 ]]; then
echo "$ZSH_THEME_GIT_COMMITS_BEHIND_PREFIX$commits$ZSH_THEME_GIT_COMMITS_BEHIND_SUFFIX"
fi
fi
}
# Outputs if current branch is ahead of remote
function git_prompt_ahead() {
if [[ -n "$(command git rev-list origin/"$(git_current_branch)"..HEAD 2>/dev/null)" ]]; then
echo "$ZSH_THEME_GIT_PROMPT_AHEAD"
fi
}
# Outputs if current branch is behind remote
function git_prompt_behind() {
if [[ -n "$(command git rev-list HEAD..origin/"$(git_current_branch)" 2>/dev/null)" ]]; then
echo "$ZSH_THEME_GIT_PROMPT_BEHIND"
fi
}
# Outputs if current branch exists on remote or not
function git_prompt_remote() {
if [[ -n "$(command git show-ref origin/"$(git_current_branch)" 2>/dev/null)" ]]; then
echo "$ZSH_THEME_GIT_PROMPT_REMOTE_EXISTS"
else
echo "$ZSH_THEME_GIT_PROMPT_REMOTE_MISSING"
fi
}
# Formats prompt string for current git commit short SHA
function git_prompt_short_sha() {
local SHA
SHA=$(command git rev-parse --short HEAD 2>/dev/null) && echo "$ZSH_THEME_GIT_PROMPT_SHA_BEFORE$SHA$ZSH_THEME_GIT_PROMPT_SHA_AFTER"
}
# Formats prompt string for current git commit long SHA
function git_prompt_long_sha() {
local SHA
SHA=$(command git rev-parse HEAD 2>/dev/null) && echo "$ZSH_THEME_GIT_PROMPT_SHA_BEFORE$SHA$ZSH_THEME_GIT_PROMPT_SHA_AFTER"
}
# # Get the status of the working tree
# function git_prompt_status() {
# local INDEX STATUS
# INDEX=$(command git status --porcelain -b 2>/dev/null)
# STATUS=""
# if eval "$(echo "$INDEX" | command grep -E '^\?\? ' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_UNTRACKED$STATUS"
# fi
# if eval "$(echo "$INDEX" | grep '^A ' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_ADDED$STATUS"
# elif eval "$(echo "$INDEX" | grep '^M ' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_ADDED$STATUS"
# fi
# if eval "$(echo "$INDEX" | grep '^ M ' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_MODIFIED$STATUS"
# elif eval "$(echo "$INDEX" | grep '^AM ' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_MODIFIED$STATUS"
# elif eval "$(echo "$INDEX" | grep '^ T ' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_MODIFIED$STATUS"
# fi
# if eval "$(echo "$INDEX" | grep '^R ' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_RENAMED$STATUS"
# fi
# if eval "$(echo "$INDEX" | grep '^ D ' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_DELETED$STATUS"
# elif eval "$(echo "$INDEX" | grep '^D ' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_DELETED$STATUS"
# elif eval "$(echo "$INDEX" | grep '^AD ' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_DELETED$STATUS"
# fi
# if eval "$(command git rev-parse --verify refs/stash >/dev/null 2>&1)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_STASHED$STATUS"
# fi
# if eval "$(echo "$INDEX" | grep '^UU ' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_UNMERGED$STATUS"
# fi
# if eval "$(echo "$INDEX" | grep '^## [^ ]\+ .*ahead' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_AHEAD$STATUS"
# fi
# if eval "$(echo "$INDEX" | grep '^## [^ ]\+ .*behind' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_BEHIND$STATUS"
# fi
# if eval "$(echo "$INDEX" | grep '^## [^ ]\+ .*diverged' &>/dev/null)"; then
# STATUS="$ZSH_THEME_GIT_PROMPT_DIVERGED$STATUS"
# fi
# echo "$STATUS"
# }
# # TODO: replace this with something more standard, this was a temporary workaround for poor performance of the stock oh-my-zsh git plugin
# # Compares the provided version of git to the version installed and on path
# # Outputs -1, 0, or 1 if the installed version is less than, equal to, or
# # greater than the input version, respectively.
# function git_compare_version() {
# local INPUT_GIT_VERSION INSTALLED_GIT_VERSION
# # shellcheck disable=SC2206,SC2207,SC2296
# INPUT_GIT_VERSION=(${(s/./)1})
# # shellcheck disable=SC2206,SC2207,SC2296
# INSTALLED_GIT_VERSION=($(command git --version 2>/dev/null))
# # shellcheck disable=SC2206,SC2207,SC2296
# INSTALLED_GIT_VERSION=(${(s/./)INSTALLED_GIT_VERSION[3]})
# for i in {1..3}; do
# if [[ ${INSTALLED_GIT_VERSION[$i]} -gt ${INPUT_GIT_VERSION[$i]} ]]; then
# echo 1
# return 0
# fi
# if [[ ${INSTALLED_GIT_VERSION[$i]} -lt ${INPUT_GIT_VERSION[$i]} ]]; then
# echo -1
# return 0
# fi
# done
# echo 0
# }
# Outputs the name of the current user
# Usage example: $(git_current_user_name)
function git_current_user_name() {
command git config user.name 2>/dev/null
}
# Outputs the email of the current user
# Usage example: $(git_current_user_email)
function git_current_user_email() {
command git config user.email 2>/dev/null
}
# Clean up the namespace slightly by removing the checker function
# unfunction git_compare_version
#source /usr/local/etc/profile.d/autojump.sh
pdfcompress() {
gs -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -dCompatibilityLevel=1.3 -dPDFSETTINGS=/screen -dEmbedAllFonts=true -dSubsetFonts=true -dColorImageDownsampleType=/Bicubic -dColorImageResolution=144 -dGrayImageDownsampleType=/Bicubic -dGrayImageResolution=144 -dMonoImageDownsampleType=/Bicubic -dMonoImageResolution=144 -sOutputFile="$1".compressed.pdf "$1"
}
# Usage: mv oldfilename
# If you call mv without the second parameter it will prompt you to edit the filename on command line.
# Original mv is called when it's called with more than one argument.
# It's useful when you want to change just a few letters in a long name.
function mv() {
if [ "$#" -ne 1 ]; then
command mv "$@"
return
fi
if [ ! -f "$1" ]; then
command file "$@"
return
fi
read -ei "$1" newfilename
mv -v "$1" "$newfilename"
}
_force_rehash() {
((CURRENT == 1)) && rehash
return 1 # Because we didn't really complete anything
}
# This was causing tab complete errors such as zle-line-init:1: command not found
# edit-command-output() {
# BUFFER=$(eval "$BUFFER")
# CURSOR=0
# }
# zle -N edit-command-output
__mkdir() { if [[ ! -d $1 ]]; then mkdir -p "$1"; fi; }
tch() {
for x in "$@"; do
__mkdir "${x:h}"
done
touch "$@"
}
# Interactive git diff
function git-diff() {
git log --graph --color=always \
--format="%C(auto)%h%d %s %C(black)%C(bold)%cr" "$@" |
fzf --ansi --preview "echo {} \
| grep -o '[a-f0-9]\{7\}' \
| head -1 \
| xargs -I % sh -c 'git show --color=always %'" \
--bind "enter:execute:
(grep -o '[a-f0-9]\{7\}' \
| head -1 \
| xargs -I % sh -c 'git show --color=always % \
| less -R') << 'FZF-EOF'
{}
FZF-EOF"
}
# Github
# Deletes workflow logs from a given repo older than 1 month
# e.g. USER=myuser REPO=myrepo ghac
function ghac() {
DATE=$(date -v "-1m" +"%Y-%m-%d") gh api "repos/${USER}/${REPO}/actions/runs" --paginate -q '.workflow_runs[] | select (.run_started_at <= "env.DATE") | (.id)' |
xargs -n1 -I % gh api "repos/${USER}/${REPO}/actions/runs"/% -X DELETE
}
function github_actions_watcher() {
# https://github.com/nedbat/watchgha
TOKEN_BACKUP=$GITHUB_TOKEN
unset GITHUB_TOKEN
watch_gha_runs "$@" \
"$(git remote get-url origin)" \
"$(git rev-parse --abbrev-ref HEAD)"
GITHUB_TOKEN=$TOKEN_BACKUP
}
# Git checkout new branch, git add, git commit, git push in all subdirectories matching a pattern
function git_add_commit_push() {
if [[ -z $1 ]] || [[ -z "$2" ]] || [[ -z "$3" ]]; then
echo 'You must pass three paramters, branchname, commit message, dir match - e.g. "my-branch" "commit message" ABC*'
fi
BRANCHNAME="$1"
COMMITNAME="$2"
MATCHDIRS="$3"
for dir in $MATCHDIRS; do
(
cd "$dir" &&
git checkout -b "$BRANCHNAME" &&
git add . &&
git commit -n -m "$COMMITNAME" &&
git push
)
done
}
# Interactive cd using fzf
function fcd() {
local dir
while true; do
# exit with ^D
dir="$(ls -a1p | grep '/$' | grep -v '^./$' | fzf --height 40% --reverse --no-multi --preview 'pwd' --preview-window=up,1,border-none --no-info)"
if [[ -z "${dir}" ]]; then
break
else
cd "${dir}" || exit
fi
done
}
# list env variables with fzf
list_env() {
var=$(printenv | cut -d= -f1 | fzf) &&
echo "$var=$(printenv "$var")" &&
unset var
}
# Encryption (using age)
# File with generated password
encrypt_file_pw() {
# Suggest installing age if not installed
if ! command -v age &>/dev/null; then
echo "age could not be found. Install it with 'brew install age'"
return
else
age -p "$1" -o "${1}.age"
fi
}
conda_setup() {
# CONDA - is managed via a function when needed
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/samm/miniconda3/bin/conda' 'shell.zsh' 'hook' 2>/dev/null)"
if [ $? -eq 0 ]; then
eval "$__conda_setup"
else
if [ -f "/Users/samm/miniconda3/etc/profile.d/conda.sh" ]; then
. "/Users/samm/miniconda3/etc/profile.d/conda.sh"
else
export PATH="/Users/samm/miniconda3/bin:$PATH"
fi
fi
unset __conda_setup
# <<< conda initialize <<<
}
function update_asdf() {
asdf update
asdf plugin-update --all
}
# Prompts for a name and a password and stores it in keychain
keychain_password_prompt() {
echo "Enter a name for the password:"
read -r name
echo "Enter the password:"
stty -echo # disable echoing the password
read -r password
security add-generic-password -s "$name" -a "$(whoami)" -w "$password"
stty echo # re-enable echoing
}
# Reads a password from keychain and outputs it
# usage: keychain_password <service name to match on> <account>
keychain_password() {
stty -echo # disable echoing the password
security find-generic-password -s "$1" -a "$(whoami)" -w
stty echo # re-enable echoing
}
### AWS Auth ###
# aws-profile uses s2a-keychain to login to AWS using saml2aws and then exports the AWS_PROFILE variable
# Requires saml2aws, fzf, and keychain_password
alias aad=aws-profile
alias awslogin=aws-profile
alias aws-azure-login=aws-profile
# shellcheck disable=SC2068 disable=SC2046 disable=SC2145
function s2a() {
eval $($(command saml2aws) script --shell=bash --profile=$@)
}
# Logs into AWS using saml2aws and a password stored in keychain
function s2a-keychain() {
local IDPPW INPUT_PROFILE KEYCHAIN_ITEM
KEYCHAIN_ITEM=${KEYCHAIN_ITEM:-"saml2awspw"}
INPUT_PROFILE=${1:-"default"}
CHECK_SCREENRECORDER=${CHECK_SCREENRECORDER:-"false"}
IDPPW=$(keychain_password "$KEYCHAIN_ITEM") # requires mfa and keychain authentication
aws configure list --profile "${INPUT_PROFILE}"
# Login to AWS
# /Users/samm/git/saml2aws-fork/dist/saml2aws_darwin_arm64/saml2aws
saml2aws login -a "$INPUT_PROFILE" \
--skip-prompt \
--password="$IDPPW" \
--profile="$INPUT_PROFILE"
# --skip-verify
export AWS_PROFILE="$INPUT_PROFILE"
export AWSCLIPARAMS="--profile=${INPUT_PROFILE}"
export AWS_DEFAULT_REGION=ap-southeast-2
unset IDPPW
}
# Interactively export AWS_PROFILE
function aws-profile() {
# if provided an argument, use that as the profile
if [[ -n $1 ]]; then
export AWS_PROFILE=$1
export AWSCLIPARAMS="--profile=$1"
else
# otherwise, use fzf to select a profile
AWS_PROFILE=$(grep profile "${HOME}"/.aws/config |
awk '{print $2}' | sed 's,],,g' |
fzf --layout reverse --height=30% --border)
export AWS_PROFILE
export AWSCLIPARAMS="--profile=${AWS_PROFILE}"
fi
s2a-keychain "$AWS_PROFILE"
echo "[You are now using the ${AWS_PROFILE} profile]"
}
### END AWS Auth ###
# A function that checks ssh-add and adds my keys if they're not already added
function ssh-add-keys() {
if ! ssh-add -l | grep -qe 'ED25519\|RSA'; then
ssh-add --apple-use-keychain ~/.ssh/id_*.key
fi
}
function tmux_create() {
SESSION="$1"
echo "Creating tmux session ${SESSION}"
tmux new-session -d -s "$SESSION"
tmux switch-client -t "$SESSION"
}
function tmux_attach() {
# If not provided an argument, use fzf to select a session
if [[ -n $1 ]]; then
SESSION="$1"
# check if there are any sessions
if [[ -z $(tmux ls) ]]; then
echo "No tmux sessions found"
return 1
fi
else
SESSION=$(tmux ls | grep -Eo '^[0-9]+.*' | fzf --layout reverse --height=40% --border | awk '{print $1}')
fi
echo "Attaching to tmux session ${SESSION}"
tmux switch-client -t "$SESSION"
}
clean_string() {
# Escape special characters in a string such as $, ", ', `, \, and newline.
# Usage: escape_string "string to escape"
local string="${1}"
local escaped_string
escaped_string=$(printf '%q' "${string}")
echo "${escaped_string}"
}
docker_login_ghcr() {
# Dependencies: gh
set -e
if [ ! -f ~/.docker/config.json ]; then
echo '{"credsStore": "desktop","credHelpers": {"docker.pkg.github.com": "gh","ghcr.io": "gh"}}' >~/.docker/config.json
fi
cmd="${1}"
if [ "erase" = "${cmd}" ]; then
cat - >/dev/null
exit 0
fi
if [ "store" = "${cmd}" ]; then
cat - >/dev/null
exit 0
fi
if [ "get" != "${cmd}" ]; then
exit 1
fi
host="$(cat -)"
host="${host#https://}"
host="${host%/}"
if [ "${host}" != "ghcr.io" ] && [ "${host}" != "docker.pkg.github.com" ]; then
exit 1
fi
token="$(gh config get -h github.com oauth_token)"
if [ -z "${token}" ]; then
exit 1
fi
printf '{"Username":"%s", "Secret":"%s"}\n' "$(gh config get -h github.com user)" "${token}"
}
docker_inspect_all() {
# Get the IDs of all running containers
local container_ids=("$(docker ps -q)")
# Iterate over each container ID
for container_id in "${container_ids[@]}"; do
# Run docker inspect command and store the output in a variable
local inspect_output=$(docker inspect --format='{{json .}}' "$container_id")
# Extract container name and remove leading '/'
local container_name=$(jq -r '.Name[1:]' <<<"$inspect_output")
# Extract container status, creation timestamp, and IP addresses
local container_status=$(jq -r '.State.Status' <<<"$inspect_output")
local created_timestamp=$(jq -r '.Created' <<<"$inspect_output")
local ip_address=$(jq -r '.NetworkSettings.Networks[].IPAddress' <<<"$inspect_output")
local ipv6_address=$(jq -r '.NetworkSettings.Networks[].GlobalIPv6Address' <<<"$inspect_output")
# Extract forwarded ports
local ports=$(jq -r '.NetworkSettings.Ports | to_entries[] | .key + " -> " + .value[0].HostPort' <<<"$inspect_output")
# Display the extracted information
echo "Container ID: $container_id"
echo "Container Name: $container_name"
echo "Container Status: $container_status"
echo "Created Timestamp: $created_timestamp"
echo "IP Address: $ip_address"
echo "IPv6 Address: $ipv6_address"
echo "Forwarded Ports: $ports"
echo "-----------------------"
done
}
ps-docker() {
# ps -aux but with the container name and nice formatting
echo -e "Processing docker containers, this may take a moment...\n"
{
echo -e "CONTAINER NAME\tUSER\tPID\t%CPU\t%MEM\tRUN TIME\tCOMMAND"
ps -aux | awk '{print $2}' | while read pid; do
container_id=$(grep -Eo "docker-([a-f0-9]{64})\.scope" /proc/"$pid"/cgroup 2>/dev/null | head -n1 | grep -Eo "([a-f0-9]{64})")
if [ ! -z "$container_id" ]; then
container_name=$(docker ps --no-trunc | grep "$container_id" | awk '{print $NF}')
if [ ! -z "$container_name" ]; then
ps -p "$pid" -o user,pid,%cpu,%mem,etime,cmd --no-headers | awk -v cn="$container_name" '{printf "%-20s\t%-8s\t%-8s\t%-5s\t%-5s\t%-10s\t%-40s\n", cn, $1, $2, $3, $4, $5, substr($0, index($0,$6))}'
fi
fi
done
} | awk 'BEGIN {OFS="\t"; prev="none"} NR==1 {print} NR>1 {split($0,a,"\t"); if (a[1]!=prev && NR>2) print "--------------------\t\t\t\t\t\t\t"; print; prev=a[1]}'
}
# 3D Printing
function cura-backup() {
# Zip up the latest cura config from the newest number cura config directory (~/Library/Application\ Support/cura/(number.number) (e.g. 4.8)
# and copy it to the cloud backup folder
local cura_base_dir="${HOME}/Library/Application Support/cura"
local destination="${HOME}/Library/Mobile Documents/com~apple~CloudDocs/Backups/3dprinting/cura"
local latest_version_dir="$(ls -d "${cura_base_dir}"/*/ | tail -n1)"
# zip it up with the date
local date="$(date +%Y-%m-%d)"
local zip_file="${destination}/cura-${date}.zip"
zip -r "${zip_file}" "${latest_version_dir}"
echo "Created ${zip_file}"
}
function ripSearch() {
# 1. Search for text in files using Ripgrep
# 2. Interactively narrow down the list using fzf
# 3. Open the file in vscode
while getopts n OPTION; do
case "${OPTION}" in
n) NEW_WINDOW="--new-window" ;;
*) echo "ERROR: we only support -n" && exit 1 ;;
esac
done
shift $((OPTIND - 1))
: "${NEW_WINDOW:=""}"
# Allow the function to be cancelled with Ctrl-C, but don't exit the shell
trap 'return 1' INT
ARGLIST=""
while IFS=: read -rA SELECTED; do
if [ "${#SELECTED[@]}" -gt 0 ]; then
ARGLIST+="--goto ${SELECTED[0]}:${SELECTED[1]} "
fi
done < <(
rg --color=always --line-number --no-heading --smart-case "${*:-}" |
fzf --ansi \
--color "hl:-1:underline,hl+:-1:underline:reverse" \
--delimiter : \
--multi \
--preview 'bat --color=always {1} --highlight-line {2} --style=header,grid {}' \
--preview-window 'right,60%,border-bottom,+{2}+3/3,~3'
)
if [ -n "${ARGLIST}" ]; then
code "${NEW_WINDOW}" "${ARGLIST}"
fi
}
### CAPTURE AND RETURN OUTPUT OF A COMMAND ###
# Usage:
# $ find . -name 'filename' | cap
# /path/to/filename
# $ ret
# /path/to/filename
# capture the output of a command so it can be retrieved with ret
cap() { tee /tmp/capture.out; }
# return the output of the most recent command that was captured by cap
ret() { cat /tmp/capture.out; }
### END CAPTURE AND RETURN OUTPUT OF A COMMAND ###
# Backup VSCode extensions settings
function backup-vscode() {
local date
date="$(date +%Y-%m-%d)"
local destination="${HOME}/Library/Mobile Documents/com~apple~CloudDocs/Backups/vscode/${date}"
local extensions_file="${destination}/extensions.txt"
local settings_file="${destination}/settings.json"
local keybindings_file="${destination}/keybindings.json"
mkdir -p "${destination}"
# List extensions
code --list-extensions >"${extensions_file}"
echo "Created ${extensions_file}"
# Backup settings
cp "${HOME}/Library/Application Support/Code/User/settings.json" "${settings_file}"
echo "Created:"
echo "$settings_file"
# Backup keybindings
cp "${HOME}/Library/Application Support/Code/User/keybindings.json" "${keybindings_file}"
echo "$keybindings_file"
}
### Github Functions ###
function gh() {
# unset GITHUB_TOKEN for gh cli
GITHUB_TOKEN="" command gh "$@"
}
function gh_pr_list_open() {
local search_param=""
local other_params=()
while [[ $# -gt 0 ]]; do
case "$1" in
--match)
search_param="$2"
shift 2
;;
*)
other_params+=("$1")
shift
;;
esac
done
if [[ -n "$search_param" ]]; then
other_params+=("--search=\"$search_param\"")
fi
gh pr list --state open "${other_params[@]}"
}
function gh_pr_list_open_dir_repos() {
local search_param=""
local other_params=()
while [[ $# -gt 0 ]]; do
case "$1" in
--match)
search_param="$2"
shift 2
;;
*)
other_params+=("$1")
shift
;;
esac
done
for repo in */; do
if [[ -d "$repo" ]]; then