-
Notifications
You must be signed in to change notification settings - Fork 0
/
dot_bash_aliases
1708 lines (1398 loc) · 40.3 KB
/
dot_bash_aliases
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
# vim: set filetype=sh -- .bash_aliases is known, this isn't
# if possible, this file should remain under 1000 LOC.
# autostart {{{
# TODO: sudo clean journal log
open_file() {
f=$1
if
[[ -f $f ]] && [[ -s $f ]] &&
# file not opened
# [[ ! -f "$HOME/.vim/swap/${f//\//%}.swp" ]] # breaks treesitter
[[ ! -f "$HOME/.vim/swap/$(echo "$f" | tr / %).swp" ]]
then
# note: nvim generally always spawns with --embed
# https://neovim.io/doc/user/starting.html#--embed
exec nvim + "$f"
fi
}
# open_file /tmp/hr-loona
if
[[ -f /tmp/verse.json ]] && [[ -s /tmp/verse.json ]]
then
{
jq -r '.votd | .reference, .content' < /tmp/verse.json |
sed -e 's/<[^>]*>//g' |
fold -w 65 -s
# echo
} >&2
fi
# }}}
# aliases {{{
# alias ws=wallset
alias dr=discogs_rate
alias ex=extract
alias gm=getmail
alias lc=leetcode.py # shadows lc binary (who?)
alias mb=musicbrainz
alias met=metronome
alias ns=notify-send
alias trk=trackratings.py
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 rat="exec yazi \"\$HDD/torrent\" \"\$HDD/movies\""
# alias drag="dragon-drop --all --and-exit"
# alias pq="cd ~/plaque/ ; go build ; ./plaque"
alias ..="cd .."
alias au="audacious -H"
alias bh="vb -b"
alias cam="ls /dev/video* && mpv --fs av://v4l2:/dev/video0 --profile=low-latency --untimed && exit" # TODO: handle >1 video device (just increment n until file not exist)
alias ci="chromium --incognito"
alias con="convert_files && fix_genres --auto && fix_tags -a && fix_tags && fix_genres && move_files" # && notify-send ok"
alias csv="python -c 'import sys; import pandas; print(pandas.read_csv(sys.argv[1]))'"
alias ctz="sudo timedatectl set-timezone \$(timedatectl list-timezones | grep / | fzf)" # TODO: geolocate
alias da="dc artist:"
alias dc="discogs_collection filter"
alias dt="discogs_collection top"
alias feh="feh --draw-filename --fullscreen --auto-zoom --sort name --version-sort"
alias h="htop -u \$USER"
alias li="chromium --incognito 'https://www.linkedin.com/notifications/?midToken=AQECUGJ6GKhRSg' & exit"
alias lock="[[ -d /sys/class/power_supply/BAT0 ]] && systemctl suspend && slock"
alias md="\$EDITOR -c 'set ft=markdown'"
alias mem="top -b -n1 -o %MEM | grep -m10 \$USER"
alias n="NO_COLOR=1 node --import=tsx"
alias pq="~/plaque/plaque"
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 tx="tectonic -X"
alias tz=trizen
alias vf="\$EDITOR \$(fzf)"
alias y="bash ~/gripts/disq/ytm.sh"
# }}}
# git {{{
# shellcheck disable=SC2120
gls() {
git ls-files "${1:-.}"
}
gmaster() {
git symbolic-ref refs/remotes/origin/HEAD 2> /dev/null | cut -d/ -f4
}
gb() {
# no remote branches
default_local_branch=$(gmaster) || :
current_local_branch=$(git branch --show-current)
if [[ $# -eq 0 ]]; then
if [[ $default_local_branch == "$current_local_branch" ]]; then
echo "Already on $default_local_branch"
else
git checkout "$default_local_branch" || echo "need commit"
git pull
fi
else
# generally, new branches are based on master. however, this
# may not always be the case, so an optional 2nd arg is needed
if ! git checkout "${2:-$default_local_branch}"; then
echo "need commit"
return
fi
git pull || return
# existing remote branch > create local branch > existing local branch
if
git branch -r | grep "origin/$1"
then
# TODO: should probably ask for confirmation
git switch "$1" 2> /dev/null
elif git switch --create "$1" 2> /dev/null; then
# git switch --create does not produce output, for some
# reason (but git switch does)
echo "Switched to new branch $1"
else
git switch "$1" || echo "need commit"
fi
fi
}
gB() {
# https://stackoverflow.com/a/1441062
# --pretty=format:'%h%x09%an%x09%ad%x09%s' # no color
# TODO: include date/author, but preserve color
# TODO: handle master..master
prv_cmd="echo {} | sed -r 's/^[ *]+//; s/^/master../' | xargs git log --oneline --color=always"
branch=$(git branch |
fzf --preview="$prv_cmd" --preview-window='right,80%,border' --ansi |
sed -r 's/^[ *]+//')
[[ -z $branch ]] && return
gb "$branch"
}
gbd() {
: prune local branches that no longer exist on remote -- unstaged changes will be lost!
# https://stackoverflow.com/a/46192689
git branch -vv |
grep ': gone]' |
grep -v "\*" |
awk '{ print $1; }' |
xargs -r git branch -D
}
gba() {
: show all branches with author
# https://stackoverflow.com/a/19135644
git for-each-ref --format='%(committerdate:iso)%09%(authorname)%09%(refname)' |
grep remotes |
sort |
column -t -s ' '
}
_() {
# https://nitaym.github.io/ourstheirs/
# # merge: attempt to apply (bring in) changes from feature, then master
# git checkout master
# git merge $feature_branch
# git checkout --ours $conflict_file # to select the changes done in master
# git checkout --theirs $conflict_file # to select the changes done in $feature_branch
# git add $conflict_file
# git merge --continue
# # rebase: attempt to apply changes from master, then from feature
# git checkout $feature_branch
# git rebase master
# git checkout --ours $conflict_file # to select the changes done in master
# git checkout --theirs $conflict_file # to select the changes done in $feature_branch
# git add $conflict_file
# git rebase --continue
:
}
gld() {
: browse git log, showing each commit\'s diff in fzf preview
prv_cmd="echo {} | cut -d' ' -f1 | xargs git show --color=always"
{
if [[ -f $1 ]] || [[ -d $1 ]]; then
git log --oneline "$1"
else
git log --oneline
fi
} |
fzf --preview="$prv_cmd" --preview-window='right,60%,border' --ansi |
awk '{print $1}' |
xargs git show
# TODO: open in browser?
}
gS() {
: like gs+gld, for files to stage/commit
files=$(git status --porcelain)
prv_cmd="echo {} | awk '{print \$2}' | xargs git diff --color=always"
sel=$(<<< "$files" fzf --multi --reverse --preview="$prv_cmd" --preview-window='right,60%,border' --ansi)
echo "$sel" | awk '{print $2}' | xargs git commit -v
}
gac() {
: append ALL changes to most recent unpushed commit
git add "$@"
git commit --amend --no-edit
}
gapc() {
git add --patch "$@"
git commit --amend --no-edit
}
# delete and ignore file, without untracking. warning: the only way to recover
# is to re-download from repo!
# https://stackoverflow.com/a/45149731
# git update-index --assume-unchanged <file>
gL() {
: show commits \(hash+msg\) made in the last week
# TODO: allow file/dir $1
d=$(date --date="1 week ago")
git logline --since="$d" --no-merges | tac
# gl --since="$d" --no-merges | tac
}
gcf() {
# https://stackoverflow.com/a/44750379
# https://jordanelver.co.uk/blog/2020/06/04/fixing-commits-with-git-commit-fixup-and-git-rebase-autosquash/
# default_branch=$(git symbolic-ref refs/remotes/origin/HEAD | sed 's|^refs/remotes/origin/||')
default_branch=$(gmaster)
sha=$(git log --oneline | fzf | cut -d' ' -f1)
git commit --fixup "$sha"
git rebase -i --autosquash "$default_branch"
}
gA() {
: un-add, unstage
git restore --staged "$@" \
2> /dev/null || # committed; without --staged, changes are discarded!
git reset "$@" # not committed yet
}
gc() {
# TODO: if work repo, master branch, return
pcrc
if [[ $# -gt 0 ]]; then
# use glob to automatically exclude untracked files
arr=()
for f in "$@"; do
[[ ! -f $f ]] && continue
git ls-files | grep -q "$(basename "$f")" && arr+=("$f")
done
# TODO: this loop commits renamed files, but does not commit
# their old names
git commit -v "${arr[@]}"
elif
# file(s) have been renamed
git status --porcelain | grep -Pq '^R \S+? -> \S+$'
then
git commit -v "${arr[@]}"
elif
staged=$(git diff --name-only --cached --diff-filter=AMD) &&
[[ -n $staged ]]
then
# commit all staged changes
git commit -v
else
# commit all files that have changed
git diff --name-only | xargs git commit -v
fi
}
gs() {
# 1. changed files (twice: porcelain, then diff stat)
# 2. untracked files
# 3. current number of staged commits
# (1)
# M discogs.go
# M discogs_test.go
# M main.go
#
# discogs.go | 2 +-
# main.go | 2 +-
# discogs_test.go | 6 +++---
#
# (2)
# util_test.go
#
# (3)
# No commits staged.
if
# not repo
! git status > /dev/null
then
return
elif
# new repo
git status | grep -q 'No commits yet'
then
git status
return
fi
# shellcheck disable=SC2164
[[ $# -eq 1 ]] && [[ -d $1 ]] && pushd "$1" > /dev/null
# 1
# note: colors are lost when piping, but sort is more useful than color
if
diffs=$(
git diff --stat ./ | # generally, i only want to see the diff stat for current dir
grep -F '|' | # ignore summary line
sort -n -k3 # most changes last (more useful in short terminals)
)
[[ -n $diffs ]]
then
{ git status --porcelain | grep -Fv '??'; } 2> /dev/null
echo
echo "$diffs"
elif
# newly staged files are -not- included in git diff
files=$(git status --porcelain |
grep '^A' |
awk '{print $NF}' |
# make paths absolute (default: relative to root)
prepend "$(get_repo_root)/" |
# then relativise to cwd
largs realpath --relative-to=. 2> /dev/null) &&
[[ -z $files ]]
then
: no files added
else
echo "$files" | column -t | while read -r f; do
lines=$(< "$f" wc -l)
echo "./$f | $lines +"
done <<< "$files" | column -t
fi
echo
# 2
if
untracked=$(git ls-files --others --exclude-standard) &&
[[ -n $untracked ]]
then
echo "$untracked"
echo
fi
# 3
git status | grep -P '\d+ commits?' || echo 'No commits staged.'
popd > /dev/null 2> /dev/null || :
}
gp() {
: push current branch
# shellcheck disable=SC2164
[[ $# -eq 1 ]] && [[ -d $1 ]] && pushd "$1"
if ! git config --get remote.origin.url > /dev/null; then
echo 'no remote; try gnew'
return
fi
if ! git log > /dev/null; then
echo 'no commits yet; try gc'
return
fi
gpl
# --set-upstream[-to]: sets the default remote branch for the current
# local branch
git push --set-upstream origin "$(git rev-parse --abbrev-ref HEAD)"
[[ $# -eq 1 ]] && { popd || :; }
}
gpl() {
: pull
# [[ $# -eq 1 ]] && cd "$1"
# TODO: pull/update?
# https://devconnected.com/how-to-add-and-update-git-submodules/#Pull_a_Git_Submodule
# git submodule update --init --recursive
# git submodule update --remote --merge
if git branch -r | grep -q 'upstream/'; then
# pull from upstream
# git remote add upstream "$UP"
echo "Pulling from upstream"
git fetch upstream
git rebase upstream/main # or whatever
# merge as usual...
else
# git pull
git fetch
# set -x
if
# this is the closest builtin that comes close
# git diff --name-status master origin/master
pullresult=$(git merge 2>&1) # fail = exit 2
[[ $? -eq 2 ]] &&
conflicts=$(sed <<< "$pullresult" -rn 's|^\s+||p') &&
[[ -n $conflicts ]]
then
while read -r -u9 conflict; do
notify-send "Conflict" "$conflict"
git commit -v "$conflict"
done 9<<< "$conflicts"
git pull
else
echo "$pullresult"
fi
# set +x
fi
# git submodule foreach git pull origin master
# assumes all submodules at repo root
for sub in $(git submodule | cut -d' ' -f2-); do
cd "$sub" || continue
echo -e "\nUpdating submodule: $sub"
gpl
cd ..
done
}
gplm() {
: pull latest master
git checkout master
git fetch
if ! git merge; then
# discard all local changes
git merge 2>&1 | grep '^\s' | xargs git checkout --
git merge
fi
}
gmm() {
: merge master into dev branch
# https://stackoverflow.com/a/20103414
git fetch origin # gets you up to date with origin
git merge origin/master
}
gh() {
: open remote url
if ! repo=$(git config --get remote.origin.url); then
echo "Current repo has no remote"
return
fi
repo=${repo%*.git}
if [[ -f $1 ]] && git ls-files --error-unmatch "$1" &> /dev/null; then
# TODO: path must be relativised to repo root
# i.e. realpath - repo_root
# view file at its most recent commit
hash=$(git log -n 1 --pretty=format:%h -- "$1")
URL="$repo/blob/$hash/$1"
elif [[ -n $1 ]]; then # view repo at specific commit
# TODO: git log oneline -> fzf
h=$(git rev-parse --short --verify HEAD)
URL="$repo/commit/$h"
# URL="$repo/tree/$1"
else
URL="$repo"
fi
# URL=$(sed -r 's/[^/]+@//' <<< "$URL")
[[ $URL != http* ]] && URL=$(tr <<< "$URL" : / | sed -r 's|git@|https://|')
echo "$URL"
# ubuntu is a pita:
# gio: ...: Failed to find default application for content type ‘text/html’
xdg-open "$URL" ||
firefox "$URL"
}
gnew() {
: push to newly created remote
# TODO: when starting a new work repo (local or remote), do:
# git config --local user.name ...
# git config --local user.email ...
if [[ -f files_to_add ]]; then
if [[ -d .git ]] && [[ -d .git_old ]]; then
echo 'new and old git histories found, remove new one first: rm -rf ./.git'
return
fi
mv .git .git_old
fi
# echo $GIT_EMAIL
# return
# https://kbroman.org/github_tutorial/pages/init.html
# set -euo pipefail
if [[ ! -d .git ]]; then
echo "Creating local tree..."
if
[[ ! -f .gitignore ]] && find . | grep -Pq '\.py$'
then
echo "__pycache__" > .gitignore
fi
git init # idempotent
if [[ -f files_to_add ]]; then
# private repo goes public
< files_to_add xargs git add
less files_to_add
else
# git add .
find . -maxdepth 1 -type f |
grep -v pdf | # TODO: better to remove binary (how?)
largs git add
fi
# git add tests/* 2> /dev/null
fi
if ! git log > /dev/null 2> /dev/null; then
git commit -m "initial commit"
fi
if ! remote=$(git config --get remote.origin.url); then
git branch -M master
xdg-open https://github.com/new &
read -rp 'Repo name (not URL!): ' repo
git remote add origin "https://github.com/hejops/$repo"
git push -u origin master
git status
elif [[ $remote != *"hejops"* ]]; then
# make a private clone of a repo, preserving history
# don't remember the use case for this tbh
xdg-open https://github.com/new &
read -rp 'Repo name: ' repo
git remote set-url origin "https://github.com/hejops/$repo"
git push -u origin master
git status
else
# own remote already present
return
fi
}
gssh() {
# init github ssh key
# https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent#generating-a-new-ssh-key
# https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account#adding-a-new-ssh-key-to-your-account
# password not strictly necessary
ssh-keygen -t ed25519 -C [email protected] -f "$HOME/.ssh/github_$(date -I)"
ssh -T [email protected] 2>&1 | grep -q success && echo ok
# to actually use the key on startup, add to .xinitrc (or similar);
# if [[ -z $SSH_AUTH_SOCK ]]; then
# {
# pkill ssh-agent
# eval "$(ssh-agent -s)"
# ssh-add "$HOME/.ssh/github_2024-06-17"
# } > /dev/null 2> /dev/null
# fi
}
gd() {
if [[ $# -eq 0 ]]; then
git diff
return
fi
# no local changes, check against last commit
if git diff --exit-code "$1" > /dev/null; then
git diff HEAD^^ "$1"
else
git diff "$1"
fi
}
grescon() {
: merge all resolved conflicts
if rg '^[<=>]{7}'; then
echo "Unresolved conflicts remaining"
return
fi
git status --porcelain | grep UU | cut -d' ' -f2 | xargs git add
git commit -v
}
gapat() {
: stage hunks matching some pattern
# # https://choly.ca/post/git-programmatic-staging/
# git diff |
# # TODO: grepdiff seems to match entire context surrounding the
# # matches, instead of just the surrounding lines
# # might be useful: --only-match=rem|removals|add|additions|mod|modifications|all
# grepdiff --output-matching=hunk "$1" |
# git apply --cached
# # https://old.reddit.com/r/git/comments/p1vltk
# git diff -U0 |
# grepdiff --output-matching=hunk "$1" |
# # "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
# https://stackoverflow.com/a/52394658
git diff --unified=1 --pickaxe-regex -G "$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
}
ggiturl() {
: replace http url with git
echo "$url" | sed 's#http://#git@#; s#/#:#; s/$/.git/'
}
# }}}
# pre-commit {{{
alias pcu="pre-commit autoupdate"
pci() {
if ! command -v pre-commit > /dev/null; then
echo "pre-commit not installed"
return
fi
# init
local f
repo_root=$(get_repo_root)
f="$repo_root/.pre-commit-config.yaml"
[[ -f $f ]] && return
# https://pre-commit.com/#command-line-interface
# https://pre-commit.com/#quick-start
# https://pre-commit.com/hooks.html
git init
cat << EOF > "$f"
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/Yelp/detect-secrets
rev: v1.4.0
hooks:
- id: detect-secrets
# args: ["--baseline", ".secrets.baseline"]
exclude: package.lock.json
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-added-large-files
- id: check-executables-have-shebangs
- id: check-shebang-scripts-are-executable
- id: check-yaml
- id: detect-private-key
- id: end-of-file-fixer
exclude: \.sql$
- id: trailing-whitespace
EOF
if find . -name '*.py' | grep -q .; then
# https://github.com/MarcoGorelli/auto-walrus#usage-as-a-pre-commit-hook
# https://github.com/PyCQA/docformatter/blob/master/.pre-commit-config.yaml#L23C1-L28C57
# https://github.com/dannysepler/rm_unneeded_f_str#usage
# https://github.com/hadialqattan/pycln/blob/master/.pre-commit-config.yaml#L4
# https://github.com/hhatto/autopep8#usage-with-pre-commit
# https://github.com/pre-commit/mirrors-mypy#using-mypy-with-pre-commit
cat << EOF >> "$f"
- id: name-tests-test
args: ["--pytest-test-first"]
- id: requirements-txt-fixer
# reorder-python-imports is no longer compatible with black
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
name: isort
args: [--force-single-line, --profile=black]
- repo: https://github.com/asottile/pyupgrade
rev: v3.15.0
hooks:
- id: pyupgrade
args: ["--py36-plus"]
# % format -> f-string
- repo: https://github.com/ikamensh/flynt/
rev: 1.0.1
hooks:
- id: flynt
- repo: https://github.com/psf/black
rev: 24.1.1
hooks:
- id: black
args: ["--preview"]
EOF
fi
# TODO: https://github.com/TekWizely/pre-commit-golang/blob/master/sample-config.yaml#L85
pcu
}
pcr() {
pci && pre-commit run --all-files
}
pcrc() {
# only files which have changed since latest remote commit
# check if remote repo exists
git config --get remote.origin.url > /dev/null || return
pci && pre-commit run --all-files --from-ref "origin/$(gmaster)" --to-ref HEAD
}
# }}}
# python {{{
# i haven't worked in python in a while, so this may be cleaned up
# ve() {
# return
#
# # important reading:
# # https://www.b-list.org/weblog/2022/may/13/boring-python-dependencies/
# # https://github.com/jazzband/pip-tools
#
# # "always work in, and deploy in, a virtual environment"; this is how
# # cargo works.
#
# # venv comes before pip install (etc), not the other way round, and
# # python -m pip (in venv) should always be used over bare pip.
#
# python -m venv .venv
# . .venv/bin/activate
#
# # do work, manually add deps to requirements.in (no cargo add, too bad)
#
# python -m pip install --upgrade pip-tools
# python -m pip-tools compile --generate-hashes requirements/app.in --output-file requirements/app.txt
# # python -m pip-tools compile --generate-hashes requirements/tests.in --output-file requirements/tests.txt
# # if some package doesn't provide wheel, omit --only-binary
# python -m pip install --only-binary :all: -r requirements/app.txt
#
# # for monitoring dep updates of a "finished" project, use dependabot
#
# }
alias cx=coac
get_repo_root() {
git rev-parse --show-toplevel 2> /dev/null
}
eval_conda() {
# subshell only generates the code, which must then be executed
# note: this command alone does not re-source .bashrc, so don't expect
# PS1 to change
eval "$("$HOME/anaconda3/bin/conda" 'shell.bash' 'hook' 2> /dev/null)"
}
coac() {
# set -x
# local _env
local DEFAULT_ENV=foo
if
[[ -n $CONDA_PREFIX ]] #&& [[ $CONDA_PREFIX == *${_env} ]]
then
# echo "Already activated"
return
elif [[ ! -d $HOME/anaconda3/envs/$DEFAULT_ENV ]]; then
echo "\"$DEFAULT_ENV\" environment not found!"
return
fi
if ! command -v conda > /dev/null; then
echo >&2 'Activating conda...'
eval_conda
fi
echo "Activating $DEFAULT_ENV..."
conda activate "$DEFAULT_ENV"
# note: conda activate causes PS1 to be overridden
# generally always better to set
# conda config --set changeps1 false
# because you never really know what conda does to PS1
}
# python venvs should now be managed from nvim itself:
# pyright: function get_python_path
# pylint: require("lint").linters.pylint.cmd
sl() {
# set -x
[[ $# -eq 0 ]] && return
arr=("$@")
f="$(realpath "${arr[0]}")"
arr[0]=$f
# [[ -f $f ]] &&
# check_env "$f"
streamlit run "${arr[@]}"
cd
}
pta() {
: run all tests
# TODO: gls: allow arg that calls from proj root
gls | grep 'test.*py' | xargs pytest -xvv
}
pget() {
if [[ -f $1 ]]; then
pip3 install -r "$1"
elif [[ -n $CONDA_PREFIX ]]; then
pip3 install "$@"
else
pip3 install --break-system-packages "$@"
fi
}
pup() {
if [[ -f $(get_repo_root)/pyproject.toml ]]; then
poetry add "$1@latest"
else
pip install --upgrade "$1"
fi
}
p() {
# set -x
if [[ $# -eq 0 ]]; then
python3
return
fi
arr=("$@")
f="$(realpath "${arr[0]}")"
repo_root="$(get_repo_root)"
mod=$(sed <<< "$f" -r "s#$repo_root/##; s#.py##" | tr / .)
arr[0]=$mod
# check_env "$f" # go to file's project root, activate env
# python3 "${arr[@]}" || :
python3 -m "${arr[@]}"
# command -v deactivate > /dev/null && deactivate
# cd || return
}
pentmd() {
: render entry points as markdown
# - [`poetry run XXX`](./path/to/script.py)
grep < pyproject.toml :main |
sed -r 's|^([^ ]+) = "([^:]+):main"|- [`poetry run \1`](./\2.py)|g' |
tr . / |
sed -r 's#/(/|py)#.\1#g'
}
# }}}
# django {{{
alias djnew='django-admin startproject'
alias djs='./manage.py runserver'
djrmdb() {
# nuke db and rebuild
# https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html
# https://stackoverflow.com/questions/29253399/how-to-reset-migrations-in-django-1-7#comment67199335_29266821
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -delete
rm ./db.sqlite3
./manage.py makemigrations "$1"
./manage.py migrate
}
djapp() {
[[ -d $1 ]] && return
app=$1
./manage.py startapp "$app"
# startapp doesn't create urls.py
cat << EOF > "$app"/urls.py
from django.urls import path
from . import views
app_name = "$app"
urlpatterns = [
# https://docs.djangoproject.com/en/5.0/ref/urls/#django.urls.path
path(
route="",
view=views.IndexView.as_view(),
name="index",
),
]
EOF
mkdir -p "$app/templates/$app"
touch "$app/templates/$app/index.html"
cat << EOF >> "$app"/views.py
from django.views import generic
from django.shortcuts import get_object_or_404
from django.db.models import F
from $app.models import *
class IndexView(generic.ListView):
template_name = "$app/index.html" # default: <app name>/foo_list.html
context_object_name = "foo"
def get_queryset(self):
return Foo.objects.filter().order_by("pk")
EOF