-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdot_bash_aliases
More file actions
3447 lines (2905 loc) · 90.1 KB
/
Copy pathdot_bash_aliases
File metadata and controls
3447 lines (2905 loc) · 90.1 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
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 shell=bash
# vim:ft=sh
# if possible, this file should remain under 1000 LOC. interactive shell
# startup time should remain under 0.02 s
# completion {{{
_base_completer() {
# https://mill-build.org/blog/14-bash-zsh-completion.html#_conclusion
# https://www.gnu.org/software/bash/manual/html_node/A-Programmable-Completion-Example.html
# fallback to default file completion after 1st completion
# https://stackoverflow.com/a/22827323
if ((COMP_CWORD > 1)); then
COMPREPLY=()
return
fi
local f=$1 # func(string) string
_gen() {
local idx=$1
shift
local words=("$@")
local curr_fragment=${words[idx]}
# for a func with 1 arg, only this func needs to change
f "$curr_fragment"
}
# COMP_CWORD: number of "completely typed" words (e.g. `$ foo b|` == 1 word, but `$ foo b |` == 2 words)
# COMP_WORDS: all words currently typed
# local raw
# mapfile -t raw < <(_gen "$COMP_CWORD" "${COMP_WORDS[@]}") # SC2207
# local matches=("${raw[@]}")
# if ((${#raw[@]} == 1)); then # 1 match, autocomplete
# # matches+=("${raw[0]%%:*}") # strip from : onwards (could use \t, for example)
# matches+=("${raw[0]}")
# fi
local IFS=$'\n'
local matches
mapfile -t matches < <(_gen "$COMP_CWORD" "${COMP_WORDS[@]}")
if
# if COMPREPLY is an array with only one unique element, the
# completion is accepted immediately (with trailing space)
((${#matches[@]} == 1))
then
COMPREPLY=("${matches[0]}")
else
# otherwise, the maximally left-matching prefix is
# autocompleted (if any), and all elements in the array are
# displayed (with the prefix highlighted)
COMPREPLY=("${matches[@]}")
fi
}
_complete_make() {
# TODO: -C awareness is nice to have, but probably difficult to impl
[[ ! -f ./Makefile ]] && return
f() { < ./Makefile grep -Po "^${1:-[a-z]}[a-z-]*:" | tr -d :; }
_base_completer f
}
complete -o bashdefault -o default -F _complete_make make # not sure if option order is significant
_complete_pnpm() {
# pnpm -h is too slow (0.2s)
f() { < package.json jq -r '.scripts|keys[]' | grep "^${1:-.}"; }
_base_completer f
}
complete -o bashdefault -o default -F _complete_pnpm pnpm
_complete_git() {
git rev-parse --is-inside-work-tree > /dev/null 2> /dev/null || return
f() { git help -a | grep '^ ' | awk '{print $1}' | grep "^${1:-.}" | sort -u; }
_base_completer f
}
complete -o bashdefault -o default -F _complete_git git
# complete -o bashdefault -o default -F 'f() { < package.json jq -r ".scripts|keys[]" | grep "${1:-.}"; }; _base_completer f' pnpm
# }}}
# startup {{{
# https://silverrainz.me/blog/2025-09-systemd-fzf-aliases.html
# https://wiki.archlinux.org/title/Systemd#Boot_time_increasing_over_time
# systemd-analyze blame | grep -P '\ds'
# systemd-analyze critical-chain
#
# sudo systemctl disable NetworkManager-wait-online.service # https://askubuntu.com/a/1018731
# TODO: SystemMaxUse only affects system.journal? does not prevent
# /var/log/journal from filling up
# docker is disabled for now, because i literally never use it
# sudo systemctl disable docker.service
if
[[ -f /tmp/updates ]] && ! pgrep pacman > /dev/null
then
cat /tmp/updates
if
< /tmp/updates grep -q '^python ' &&
! < /tmp/updates grep -Pq 'python (3\.\d+)\S+ -> \1'
then
echo -e "WARNING: major Python update\n"
# TODO: reinstall aur scrobbler, python-lfm
fi
if
< /tmp/updates grep -q '^postgresql ' &&
! < /tmp/updates grep -Pq 'postgresql (\d+)\S+ -> \1'
then
echo -e "WARNING: major postgresql update\n"
fi
if
sudo pacman -Syu
then
rm /tmp/updates
# may get unset after update? not sure what causes it
setxkbmap -layout us -option -option compose:rctrl #,caps:menu
elif [[ -f /var/lib/pacman/db.lck ]]; then
echo "try rm /var/lib/pacman/db.lck"
elif
# if pacman hasn't been run in a long time, keys in keyring
# will expire. pacman -Syyu OR updating archlinux-keyring
# should fix this
command -v expac > /dev/null &&
last_update=$(expac --timefmt '%s' "%l" | sort -n | tail -n1) &&
# https://stackoverflow.com/a/6948865
[[ $(((last_update - $(date +%s)) / (60 * 60 * 24))) -gt 14 ]]
then
sudo pacman -Sy archlinux-keyring
fi
fi
ps --pid "$PPID" | grep -Fq wezterm &&
[[ -s /tmp/verse ]] &&
cat /tmp/verse
[[ -d $SLSK ]] &&
# i like the idea of BASH_REMATCH, but it is unfortunate that
# \S (et al) is not supported. there is no noticeable performance
# difference
# https://www.bashsupport.com/bash/variables/bash_rematch/
[[ $(du -csh "$SLSK/complete" | tail -n1) =~ ^([0-9]+).*G ]] &&
# [0] = full line (like awk)
# [@] = full line + all matches
((BASH_REMATCH[1] >= 3)) &&
echo -e "\n${BASH_REMATCH[0]}"
# SSH_AUTH_SOCK=/home/joseph/.ssh/agent/s.CAJYxPkRy2.agent.QOE8rEUDrL
# SSH_AGENT_PID=5221
if
# note: ls foo bar fails if any arg does not exit
x=$(! ls /tmp/ssh-XXXXXX*/agent.* 2> /dev/null &&
# openssh v10.1
# https://www.openssh.org/txt/release-10.1
! ls ~/.ssh/agent/s.*.agent.* 2> /dev/null)
then
# pkill ssh-agent # deletes all existing sockets
eval "$(ssh-agent -s)" > /dev/null
fi
if [[ -z $SSH_AUTH_SOCK ]]; then
SSH_AUTH_SOCK=$(<<< "$x" head -n1)
export SSH_AUTH_SOCK
fi
unset x
if
ssh-add -l | grep -Fq 'no identities'
then
find ~/.ssh -name 'gitlab*' | grep -v .pub | \xargs ssh-add -q
fi
[[ -f ~/jira.txt ]] && < ~/jira.txt cut -f1,3
# }}}
# aliases {{{
# alias dr=discogs_rate
# alias lc=leetcode.py # shadows lc binary (who?)
# alias mb=musicbrainz
# alias trk=trackratings.py
# alias wd=waitdie
alias ex=extract
alias gm=getmail
alias met=metronome
alias ns=notify-send
alias sk=slock
alias tt=taptempo
alias xo=xdg-open
alias rab='exec yazi "$HDD/books"'
alias rad='exec yazi "$SLSK/complete"' # TODO: investigate `ya pub`
alias rag='exec yazi "$HDD/guitar"'
alias ram='exec yazi "$MU"'
alias rat='exec yazi "$HDD/movies"' # "$HDD/torrent"
# alias dA="dc artist:"
# alias dc="discogs_collection filter"
# alias dt="discogs_collection top"
# alias lock="[[ -d /sys/class/power_supply/BAT0 ]] && systemctl suspend && slock"
# alias mem='top -b -n1 -o %MEM | grep -m10 $USER'
# alias mem='top -bn1 | sed -rn "/PID/,$p" | sort -k10 -n | tail'
# alias pq="~/plaque/plaque"
# alias tx="tectonic -X"
# top -bn1 | sed -rn '/PID/,$p' | sed 1d | awk '{print $10}' | sum
alias au="audacious -H"
alias bh="vb -b"
alias cam="ls /dev/video* && exec mpv --fs av://v4l2:/dev/video0 --profile=low-latency --untimed" # TODO: handle >1 video device (just increment n until file not exist)
alias cdnp='cd "$(files mpv | grep mp3 | largs dirname)"'
alias ci="chromium --incognito"
alias colt="column -t -s$'\t'" # align tab-containing output -- https://unix.stackexchange.com/a/57235
alias cpu='top -b -n1 -o %CPU | grep -m10 $USER'
alias ctz='sudo timedatectl set-timezone $(timedatectl list-timezones | grep / | fzf)' # TODO: geolocate
alias cv='exec $EDITOR ~/cv/cv.typ'
alias datez='date -u +%FT%TZ' # utc (i.e. ignore current timezone)
alias eb="exec bash"
alias fzh="fzf --reverse --height=~33%" # height=~X% means min(input rows, window height * X%);
alias fzr="fzf --reverse --preview='bat --color=always --style=auto {}' --preview-window='right,60%,border'"
alias inw="inotifywait --monitor --recursive"
alias keep="tee /dev/stderr" # copy stdout to stderr, but still direct stdout to pipe
alias li="exec firefox --private-window 'https://www.linkedin.com/notifications/?midToken=AQECUGJ6GKhRSg'"
alias or="bash ~/gripts/oar/run.sh && nico ~/oar.txt" # TODO: why new term spawned in gui window?
alias ports="netstat -tunlp | grep -Pw '^(udp|tcp)' | sort -k4 -V" # https://linuxize.com/post/check-listening-ports-linux/#check-listening-ports-with-netstat
alias pss="ps -e --format=lstart,pid,cmd --sort=start_time | grep -Fv -e '[' -e '('"
alias synctime="sudo ntpd --quit --panicgate"
alias tf="waitdie con; fix_tags"
alias trizen="trizen --aur-results-sort-by=votes --aur-results-sort-order=ascending"
alias tz=trizen # if gpg fail, gpg --recv-keys <key>
alias wr='< ~/.fehbg tail -n1 | cut -d"'"'"'" -f2 | largs -o rm -i' # insane quoting
mem() {
# https://unix.stackexchange.com/a/261252
: calc free memory in kb
low=$(< /proc/zoneinfo grep low |
awk '{print $NF}' |
sum)
a=$(
# TODO: why 12?
cat <<- EOF
{a[\$1]=\$2} END { print a["MemFree:"]+a["Active(file):"]+a["Inactive(file):"]+a["SReclaimable:"]-(12*$low); }
EOF
)
< /proc/meminfo awk "$a" |
awk '{print $0/1000000}' # bc does not handle floats
}
# alias y="bash ~/gripts/disq/ytm.sh"
y() {
vol 30
bash ~/gripts/disq/ytm.sh
}
EXA_ARGS=(
# https://github.com/search?type=code&q=path:dot_config/eza
# xdg dir is only for theme...?
# --dereference # this actually undoes symlink `-> ...`
--all # show dot files
--color=always
--git # status porcelain
--group-directories-first # debatable
--links # inode count
--long # note: long names will not be wrapped
--no-permissions
--no-user
--octal-permissions
--time-style=iso
--level=2
--tree # will be slow in large (wide) dirs
# --sort=modified
)
alias ls='exa ${EXA_ARGS[*]}'
alias lsl="ls --sort=modified"
vv() {
# # shellcheck disable=SC2329
# f() {
# line=$1
# f=$(<<< "$line" cut -d: -f1)
# line=$(<<< "$line" cut -d: -f2)
# ((start = line - 10))
# ((start < 0)) && ((start = 0))
#
# echo "$f"
# echo
# bat --color always --style=auto --line-range "$start:" "$f"
# }
# export -f f
# line=$(rgl --line-number . | fzf --preview='f {}' --preview-window='right,60%,border')
# unset f
# TODO: exclude pnpm lock, etc
line=$(rg --hidden --line-number --no-heading . |
# https://news.ycombinator.com/item?id=45677142
fzf -d: -n 2.. --preview-window "right:50%:+{2}" --preview "bat --color=always --highlight-line {2} {1}")
[[ -z $line ]] && return
f=$(<<< "$line" cut -d: -f1)
line=$(<<< "$line" cut -d: -f2)
nvim +"$line" +"norm zt" "$f"
}
# }}}
# frequent {{{
yc() {
# copy cmd to clipboard
history |
fzf --tac |
awk '{$1=""; print $0}' |
xclip -sel c
vim +gg ~/foo.sh
}
# # show contents of most recent self-sent msg
# notmuch show --limit=1 from:hejops1 |
# grep -Po 'id:\S+' |
# xargs notmuch show --part=2
# < ~/.config/mpv/library fzf |
# prepend "$MU/" |
# largs mpv
m() {
find "$HDD/movies" -type f |
fzf --preview= |
largs mpv
}
da() {
local args=()
[[ $# -eq 1 ]] && args+=(-artist "$1")
~/disq/disq "${args[@]}"
}
cm() {
if [[ $# -eq 0 ]]; then
# note: files added to cm via `add -f <symlink>` are not
# automatically updated when the src file (target of the
# symlink) is modified. the symlink targets must always be
# re-added. this will no longer be necessary when the scripts
# repo is deprecated.
chezmoi status |
grep -Po '\.local/bin/.+' |
largs chezmoi add -f 2> /dev/null
# TODO: when updating ~/scripts/foo (and having run `links`),
# the symlink at ~/.local/bin/foo is always updated. however,
# cm apply will replace the symlink with an actual file?
#
# chezmoi source-path .local/bin/mail | xargs chezmoi
# target-path | xargs realpath
chezmoi cd
else
chezmoi "$@"
fi
}
bx() { [[ $# -gt 0 ]] && bash -x "$@"; }
replace() {
_in_git_repo || return
# check correct rep binary (not the lisp thing)
if ! command -v rep | grep -Fq .cargo; then
cargo install rep-grep
return
fi
search=$1
replace=$2
_rg() {
# --hidden will cause .git to be included!
rg --hidden --glob='!.git/**' "$@"
}
if ! _rg -q -- "$search"; then
echo "Pattern not found"
return
fi
# note: backreferences use $1, not \1
_rg --line-number -- "$search" | rep -- "$search" "$replace"
read -r -p 'OK?' || return
_rg --line-number -- "$search" | rep --write -- "$search" "$replace"
# git diff
# use gap in vim instead?
gapat() { # {{{
: stage hunks matching some pattern
# TODO: error: No valid patches in input (allow with "--allow-empty")
for patt in "$@"; do
# grepdiff is more reliable than git diff -S/-G
# https://choly.ca/post/git-programmatic-staging/
# https://blog.paddlefish.net/git-tip-stage-lines-matching-a-regular-expression/
# https://old.reddit.com/r/git/comments/p1vltk
git diff -U0 |
grepdiff --output-matching=hunk -E "$patt" |
# "By default, git apply expects that the patch being applied
# is a unified diff with at least one line of context."
git apply --cached --unidiff-zero
done
# # https://stackoverflow.com/a/52394658
# git diff --unified=1 --pickaxe-regex -S "$1" |
# grepdiff --output-matching=hunk --extended-regexp "$1" |
# git apply --cached
# see also:
# http://www.philandstuff.com/2014/02/09/git-pickaxe.html
# https://git-scm.com/docs/gitdiffcore#_diffcore_pickaxe_for_detecting_additiondeletion_of_specified_string
git commit -v
# # unstage hunks that were unnecessarily added
# git reset -p
} # }}}
gapat "$replace"
}
rge() {
: edit files matching pattern
staged=$(rg --hidden --files-with-matches "$@" | sort -u)
if [[ $(<<< "$staged" wc -l) -gt 10 ]]; then
echo "More than 10 files found"
fi
pat="${@: -1}" # last arg of array https://unix.stackexchange.com/a/503475
if
(($# > 1)) && [[ -f $pat || -d $pat ]]
then
x=("$@")
pat="${x[-2]}" # pat is 2nd last arg
fi
echo "$staged" |
head |
xargs nvim -p +"/\v${pat//\//\\\/}"
}
sd() {
: shutdown
# uptime | grep hour || return/reboot
waitdie mpv pacman curl #python
if [[ -n $HDD ]]; then
if
files firefox | grep "$HDD"
then
inotifywait -e moved_to "$HDD/movies"
fi
killall firefox
while
f=$(files python | grep "$SLSK")
do
echo "$f" | largs -n1 inotifywait -e move_self
done
killall nicotine
fi
echo "Shutting down..."
sleep 3
shutdown now
}
rt() {
: pass an array of relative paths to tagfix
# note: dead symlinks are still displayed as if they exist
< ~/.config/mpv/library sort -u |
fzf --multi --reverse --preview="ls \"$MU\"/{}" |
prepend "$MU/" |
while read -r d; do
files mpv | grep -Fq "$d" && waitdie mpv >&2
echo "$d"
done |
# to preserve the old behaviour (>1 args), remove -n1
largs -o fix_tags
}
ytm() {
f=$(mktemp)
"$EDITOR" +startinsert "$f"
while
yt-dlp 'ytsearch1:foo' --get-id 2>&1 | grep -q "Sign in to confirm you’re not a bot."
do
"$EDITOR" "$f"
done
waitdie mpv
all_ids=
while read -r query; do
echo "$query"
curl -sL 'https://music.youtube.com/youtubei/v1/search' \
-H 'Content-Type: application/json' \
--data-raw '{"context":{"client":{"clientName":"WEB_REMIX","clientVersion":"1.20240904.01.01"}},"query":"'"$query"'","params":"EgWKAQIIAWoSEAMQBBAJEA4QChAFEBEQEBAV"}' |
gron |
grep videoId |
cut -d'"' -f2 |
uniq |
while read -r id; do # deduplicate across queries; somewhat useful i guess?
<<< "$all_ids" grep -Fqw -- "$id" && continue
all_ids+=" $id"
echo "$id"
done |
prepend 'https://youtube.com/watch?v=' |
xargs mpv --video=no
done < "$f"
exit
}
# }}}
# git
# alias e=v
# alias ga=_git_commit
# alias i=b
alias b=_git_branch_fzf # existing branch
alias bv="b && v"
alias cr=git_root
alias gb=_git_branch # new branch
alias gl=git_log
alias s=_git_commit # should increasingly be done in vim
# discouraged due to double index keypresses: gt gf gb
# alias ga="git add"
# alias gdnw="git diff --color-words --no-index"
# alias gm,='_git_branch && gmm'
alias g..="git push --force-with-lease origin \$(_git_current_branch)"
alias gC="git show HEAD | cat; git reset --soft HEAD~1" # un-commit, but keep changes staged
alias gCH="git show --oneline HEAD | cat; echo; read -r -p 'confirm?'; git reset --hard HEAD~1" # un-commit, and discard changes
alias gdn="git diff --no-index" # https://stackoverflow.com/a/17433969 -- TODO: handle symlinks
alias gdnc="git diff --color-words=. --no-index" # diff by char; may be replaced with delta
alias gig='$EDITOR $(_get_repo_root)/.gitignore'
alias gx='git log --author=$(git config --get user.email) --branches --format="%h%x09%S%x09%s" --pickaxe-regex -S' # TODO: colt would be nice, but then it can't be an alias anymore
# TODO: dos2unix
gdns() { gdn -U0 <(sort -u "$1") <(sort -u "$2"); } # sort lines and diff
# git info {{{
# functions that only report info
gls() { git ls-files "${1:-.}"; }
glsat() { git ls-tree -r --name-only "${1:-HEAD}"; } # https://superuser.com/a/429694
_get_remote() { git config --get remote.origin.url; }
_git_current_branch() { git branch --show-current; }
_in_git_repo() { git rev-parse --is-inside-work-tree > /dev/null 2> /dev/null; }
_get_repo_root() {
if [[ $(basename "$PWD") == .git ]]; then
realpath ..
else
git rev-parse --show-toplevel 2> /dev/null
fi
}
_gmaster() {
: get default branch, e.g. master
# https://stackoverflow.com/a/44750379
# default_branch=$(git symbolic-ref refs/remotes/origin/HEAD | sed 's|^refs/remotes/origin/||')
git symbolic-ref refs/remotes/origin/HEAD 2> /dev/null | cut -d/ -f4
}
git_root() {
if _in_git_repo; then
cd "$(_get_repo_root)" || :
elif [[ -n $REPO ]]; then
cd "$REPO" || :
fi
}
# gh() {
# # TODO: better handled in vim
#
# _git_http() {
# url=$1
# if [[ $url == http* ]]; then
# echo "$url"
# else
# tr <<< "$url" : / | sed -r 's|git@|https://|; s|.git$||'
# fi
# }
#
# : open remote url
#
# if ! repo=$(_get_remote); then
# echo "Current repo has no remote"
# return
# fi
#
# url=${repo%*.git}
# url=$(_git_http "$url")
# echo "$url"
# xdg-open "$url"
# }
# }}}
# git history {{{
gpar() { git log -n1 --format=%H "$1^@"; } # get parent hash
_git_log_fzf() { # {{{
_in_git_repo || return
# TODO: heads may be 'cleared'
# https://stackoverflow.com/a/30143136
if ! ls "$(_get_repo_root)"/.git/refs/heads/* > /dev/null 2> /dev/null; then
echo "no commits yet" >&2
return 1
fi
# stat always suppresses the diff, so --patch must be specified again.
# i generally prefer --numstat, if only because --stat uses a weird ---
# separator
#
# i don't mind always showing a stat in git show, but there seems to be
# no config option for this
prv_cmd="echo {} | cut -d' ' -f1 | xargs git show --numstat --patch --color=always"
log_args=()
fzf_args=(
--accept-nth=1 # we always only want the git hash
--ansi
--preview-window='right,60%,border'
--preview="$prv_cmd"
-m
)
if
# only logs of file/dir
[[ -f $1 || -d $1 ]]
then
log_args+=("$@")
prv_cmd="echo {} | cut -d' ' -f1 | xargs -I{} git show --color=always {} $1" # restrict diff to selected file/dir
elif
# range from...to
<<< "$1" grep -Fq ...
then
log_args+=("$@")
elif
[[ $# -gt 1 ]] # probably arbitrary options to git log
then
# TODO: also allow arbitrary options to fzf (this is a can of worms)
log_args+=("$@")
elif
[[ $# -eq 1 ]] &&
[[ $1 == $(_gmaster) ]]
then
log_args+=("$1")
# git does not allow flag overrides (i.e. --merges will not
# work), and merge commits are always after. thus, we just show
# child commit in preview
# https://stackoverflow.com/a/9870218
prv_cmd="
echo {} | cut -d' ' -f1 | xargs -I{} git log --reverse --ancestry-path {}..$(_gmaster) --oneline 2>/dev/null | head -n1 | cut -d' ' -f1 | xargs git show | grep -FC1 !;
echo {} | cut -d' ' -f1 | xargs git show
"
fzf_args+=(
# TODO: prefer word match
--no-sort
--preview="$prv_cmd"
)
elif
m=$(_gmaster) && [[ $(_git_current_branch) == "$m" ]]
then
: on master
# TODO: should just match above
# elif
# # remote dev branch (rare)
# [[ $# -eq 1 ]] &&
# git branch --remote | grep -Fqx " origin/$1"
# then
# git pull > /dev/null 2> /dev/null
# log_args+=("origin/$1")
elif
[[ -z $m ]]
then
: no remote yet - rare
else # dev branch
# note: use origin/master, because i tend to not actually
# update my local master
# note: .. and ... are NOT synonymous!
#
# A..B = raw diff between A and B
#
# A...B = diff between B and "last shared ancestor of A and B"
# (almost always master); this is usually what we want
#
# https://i.sstatic.net/PboEt.png
# https://stackoverflow.com/a/24186641
log_args+=(
# --first-parent # discards commits introduced by a merge commit (not good)
"origin/$m...HEAD"
)
fi
# there is literally nothing to see in merge commits (Merge branch 'x'
# into 'master'), so --no-merges is generally a good idea.
#
# however, commits that are the -result- of a merge are still included.
# these merges can be further ignored with --first-parent, although
# ignoring them may not always be desirable.
#
# alternatively, it may be good to indicate whether the commit was
# committed in this branch, or simply pulled from remote.
git log --decorate --oneline --no-merges "${log_args[@]}" |
fzf "${fzf_args[@]}"
} # }}}
v() { # {{{
: open recently modified files
_in_git_repo || return
# on ubuntu:
# ln -s /usr/bin/batcat ~/.local/bin/bat
prv_cmd="bat --color always --style=auto {} 2>/dev/null || cat {}"
# readarray avoids 'xargs nvim' wezterm bug
# https://github.com/wezterm/wezterm/issues/4287#issuecomment-3289326309
readarray -t f < <(git log --max-count=50 --no-merges --first-parent --name-only --pretty= |
# TODO: filter deleted
grep -Fv -e .sql.go |
prepend "$(_get_repo_root)"/ |
largs realpath --relative-to=. 2> /dev/null |
seen |
# height=~X% is not suitable because preview is usually longer
# than input rows, and preview must always be shown to a reasonable
# extent
#
# --no-sort should only be used when fuzzy matching is strict
# enough to remove most rows
fzf --no-sort -m --prompt="$(_git_current_branch): " \
--height=50% --reverse --preview-window='right,50%,border' \
--preview="$prv_cmd")
((${#f} > 0)) && nvim -p "${f[@]}"
} # }}}
gdm() { # {{{
: diff against master, like in a PR
# caveat: due to git internals, it is not trivial to produce a diff
# that is both 'cumulative' and completely excludes merges.
#
# https://stackoverflow.com/q/25403705
#
# this gets reasonably close, but if a file was changed in the current
# branch as well as in a merge, both changes will be shown. for the
# purpose of fast diffing (i.e. without network), this is usually fine.
span="origin/$(_gmaster)...HEAD" # origin/ is important
root=$(_get_repo_root)
git log --diff-filter=d --no-merges --first-parent --name-only --oneline --pretty= "$span" |
sort -u |
# HACK: --diff-filter excludes files deleted by us, but does
# not exclude files deleted during a merge
while read -r f; do
[[ -f "$root/$f" ]] && echo "$root/$f"
done |
# TODO: xargs: git: terminated by signal 13
xargs git diff "$span" 2> /dev/null
# https://gitlab.com/gitlab-org/cli/-/issues/7704
} # }}}
gbe() {
: match pattern in current branch, like rge
# does not include uncommitted changes
# TODO: generally requires gmm
pat=$1
git log --name-only --pretty= origin/"$(_gmaster)"...HEAD --pickaxe-regex -S "$pat" |
seen |
xargs nvim -p +'/\v'"${pat//\//\/\/}"
}
git_log() {
: browse git log, showing each commit\'s diff in fzf preview
_git_log_fzf "$@" | xargs git show
}
gxx() {
# -S only shows changes where the number of occurrences of <pat> did not change (modify only)
# -G shows all changes <pat> was changed (modify+add+delete)
: show commits whose changes contain a pattern
# TODO: git show --color=always breaks grepdiff?
# TODO: optional 2nd arg (file)
prv_cmd="echo {} | cut -f1 | xargs git show -U1 | grepdiff \"$1\" --output-matching=hunk"
git log --branches --format="%h%x09%S%x09%s" --pickaxe-regex -S "$1" | # WARN: slow with large histories
fzf -m --preview="$prv_cmd" --preview-window='right,60%,border'
}
gcoup() {
: for a given file, show which files changed together
# https://adamtornhill.com/articles/crimescene/codeascrimescene.htm
git log --pretty=%h "$1" |
xargs git show --name-only --pretty= |
count
}
clocd() {
: diff current repo state against a date in the past
git log --until="$(date -I --date="$1")" -n1 --oneline |
awk '{print $1}' |
xargs -I{} cloc --diff {} HEAD
}
gsdel() {
: show last state of a deleted file
f=$1
git show "$(git rev-list --max-count=1 --all -- "$f")^:$f" # https://stackoverflow.com/a/19727752
}
gy() {
: yesterday\'s log
n=1
until
d=$(date --date="$n days ago" -I)
git -C "${REPO:-.}" log --all --format="%S|%cI|%h|%s" \
--since="${d}T07:00:00" \
--until="${d}T23:00:00" \
--author="$(
# not reliable yet:
# git config get --local user.email
# git config get --local user.name
<<< "$USER" sed -r 's/^\w/\U&/'
)" --no-merges |
sed 's|refs[^ ]*/||' |
sort |
tr '|' '\t' |
colt |
grep -v -e ^master -e ^HEAD
do
((++n))
done
}
# git diff blame
# inherently, this means git diff must operate on a time range that spans more
# than commits, typically a (big) diff of a PR. by extension, this means that
# git diff blame is only useful when multiple authors have worked on the same
# PR, which tends to not happen very often IME.
# https://gist.github.com/maxrothman/d27bbc36f7c150924de6c6e54965de4d py
# https://github.com/eantoranz/difflame py
# https://github.com/dmnd/git-diff-blame pl
# GitBlameOpenFileURL
# $url/-/blob/$branch/$path
# }}}
# git staging -- functions that modify files or the index {{{
#
# TODO: most of these would be more convenient if done in vim
_commit_or_discard() {
: returns 0 if committed
committed=1
while read -r f; do
f=$(_get_repo_root)/$f
[[ -f $f ]] || continue
if
git commit -v --untracked-files=no "$f"
then
committed=0
else
# TODO: checkout fails if f is staged; must gA
git checkout -- "$f"
fi
done < /dev/stdin
# xargs git commit is not useful, because we need to know the result of
# each git checkout
return "$committed"
}
gc() {
: commit
local cmd=(git commit -v --untracked-files=no)
if [[ $# -gt 0 ]]; then
# 1. specified files, but excluding untracked files
# note: this loop commits renamed files, but does not commit
# their old names
# arr=()
# for f in "$@"; do
# [[ ! -f $f ]] && continue
# realpath "$f" | xargs git ls-files | grep -q . && arr+=("$f")
# done
# git commit -v "${arr[@]}"
for f in "$@"; do
[[ ! -f $f ]] && continue
realpath "$f" |
xargs git ls-files |
grep -q . && echo "$f"
done |
largs "${cmd[@]}"
# note: git commit -av stages -all- changes in the entire repo. this is
# almost never what i want
elif
rd=$(git diff --diff-filter=RD --name-only --staged | grep .)
then
"${cmd[@]}"
elif
# 2. file(s) that have been renamed/deleted
# this behaviour may not be desirable when modified files
# should also be included in the commit
# TODO: also check --staged
rd=$(git diff --diff-filter=RD --name-only | grep .)
then
echo "$rd" |
prepend "$(_get_repo_root)/" |
xargs "${cmd[@]}"
elif
# 3. all staged changes
# [git diff] "exits with 1 if there were differences"
! git diff --staged --diff-filter=AMD --quiet
then
: committing staged changes
"${cmd[@]}"
else
# 4. all files that have changed in the current dir
git diff --name-only . |
prepend "$(_get_repo_root)/" |
grep -v .gitignore |
xargs "${cmd[@]}"
fi
}
_git_commit() {
: like gl, for files to stage/commit
# should be replaced by gs in vim, but i still find myself doing this
# often