-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path.bashrc
More file actions
1086 lines (942 loc) · 29.1 KB
/
Copy path.bashrc
File metadata and controls
1086 lines (942 loc) · 29.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
# ~/.bashrc
# ============================================================================
# Bash shell configuration
# Copyright (c) Corey Goldberg (https://github.com/cgoldberg)
# ============================================================================
#
# bbbbbbbb
# b::::::b hhhhhhh
# b::::::b h:::::h
# b::::::b h:::::h
# b:::::b h:::::h
# b:::::bbbbbbbbb aaaaaaaaaaaaa ssssssssss h::::h hhhhh
# b::::::::::::::bb a::::::::::::a ss::::::::::s h::::hh:::::hhh
# b::::::::::::::::b aaaaaaaaa:::::ass:::::::::::::s h::::::::::::::hh
# b:::::bbbbb:::::::b a::::as::::::ssss:::::sh:::::::hhh::::::h
# b:::::b b::::::b aaaaaaa:::::a s:::::s ssssss h::::::h h::::::h
# b:::::b b:::::b aa::::::::::::a s::::::s h:::::h h:::::h
# b:::::b b:::::b a::::aaaa::::::a s::::::s h:::::h h:::::h
# b:::::b b:::::ba::::a a:::::assssss s:::::s h:::::h h:::::h
# b:::::bbbbbb::::::ba::::a a:::::as:::::ssss::::::sh:::::h h:::::h
# b::::::::::::::::b a:::::aaaa::::::as::::::::::::::s h:::::h h:::::h
# b:::::::::::::::b a::::::::::aa:::as:::::::::::ss h:::::h h:::::h
# bbbbbbbbbbbbbbbb aaaaaaaaaa aaaa sssssssssss hhhhhhh hhhhhhh
#
# ============================================================================
# if not running interactively, don't do anything
case $- in
*i* )
;;
* )
return
;;
esac
# ANSI color codes
BOLD="\e[1m"
BLUE="\e[34m"
GREEN="\e[32m"
RED="\e[31m"
RESET="\e[0m"
# export environment variables
export LANGUAGE="en_US"
export PAGER="/usr/bin/less"
export LESS="--LONG-PROMPT --RAW-CONTROL-CHARS --no-init --quit-at-eof --quit-if-one-screen --quit-on-intr"
export GITHUB_USERNAME="cgoldberg"
export PIP_DISABLE_PIP_VERSION_CHECK=true
export PIP_REQUIRE_VIRTUALENV=true
export DO_NOT_TRACK=true
export LESSHISTFILE=- # don't leave .lesshst files
if type subl >/dev/null 2>&1; then
export EDITOR="subl --new-window --wait"
elif type nano >/dev/null 2>&1; then
export EDITOR="nano"
else
export EDITOR="vi"
fi
export VISUAL="${EDITOR}"
# set termcap colors for less pager
export LESS_TERMCAP_mb=$(printf '\e[01;31m')
export LESS_TERMCAP_md=$(printf '\e[01;38;5;75m')
export LESS_TERMCAP_me=$(printf '\e[0m')
export LESS_TERMCAP_se=$(printf '\e[0m')
export LESS_TERMCAP_so=$(printf '\e[01;33m')
export LESS_TERMCAP_ue=$(printf '\e[0m')
export LESS_TERMCAP_us=$(printf '\e[04;38;5;200m')
# disable suspend/resume feature in terminal
stty -ixon
# set shell behavior
# ------------------
# change to directory by name without cd command
shopt -s autocd
# check window size after each command and update the values
# of LINES and COLUMNS
shopt -s checkwinsize
# include filenames beginning with a "." in the results of
# filename expansion
shopt -s dotglob
# the pattern "**" used in a pathname expansion context will match
# all files and zero or more directories and subdirectories
shopt -s globstar
# automatically close file descriptors assigned using the
# "{varname}" redirection syntax instead of leaving them
# open when a command completes
shopt -s varredir_close
# better command history handling
# -------------------------------
# append to history file, rather than overwrite it
shopt -s histappend
# edit recalled history line before executing
shopt -s histverify
# save each line of a multi-line command in the same history entry
shopt -s cmdhist
# save multi-line commands with embedded newlines rather than
# semicolon separators where possible
shopt -s lithist
# remove duplicate commands from history
HISTCONTROL=ignoredups:erasedups
# don't add entries to history (sometimes get duplicates of 'x'
# and 'exit' because shell is closed immediately
HISTIGNORE="x:exit"
# number of previous commands stored in memory for current session
HISTSIZE=9999
# number of previous commands stored in history file
HISTFILESIZE=9999
# immediately add commands to history instead of waiting for end of session
PROMPT_COMMAND="history -n; history -w; history -c; history -r"
# add local bin directories to the end of PATH
for d in "${HOME}/bin" "${HOME}/.local/bin"; do
if [[ ":${PATH}:" != *":${d}:"* ]]; then
export PATH="${PATH}:${d}"
fi
done
# ruby gems
if type ruby >/dev/null 2>&1; then
export GEM_HOME="${HOME}/.gems"
export PATH="${PATH}:${HOME}/.gems/bin"
fi
# rust/cargo
if [ -d "${HOME}/.cargo" ]; then
source "${HOME}/.cargo/env"
fi
# deno/js
if [ -d "${HOME}/.deno" ]; then
source "${HOME}/.deno/env"
fi
# golang
if [ -d "/usr/local/go" ]; then
export PATH="${PATH}:/usr/local/go/bin"
fi
# pipx
if type pipx >/dev/null 2>&1; then
eval "$(register-python-argcomplete pipx)"
fi
# ======================================================
#
# 888 d8b
# 888 Y8P
# 888
# 8888b. 888 888 8888b. .d8888b .d88b. .d8888b
# "88b 888 888 "88b 88K d8P Y8b 88K
# d888888 888 888 .d888888 "Y8888b. 88888888 "Y8888b.
# 88 888 888 888 888 888 X88 Y8b. X88
# Y888888 888 888 "Y888888 88888P' "Y8888 88888P'
#
# ======================================================
# navigate up the directory tree
alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."
alias .....="cd ../../../.."
alias ......="cd ../../../../.."
alias .......="cd ../../../../../.."
alias ........="cd ../../../../../../.."
alias .........="cd ../../../../../../../.."
alias cd..="cd .."
alias cd...="cd ../.."
alias cd....="cd ../../.."
alias cd.....="cd ../../../.."
alias cd......="cd ../../../../.."
alias cd.......="cd ../../../../../.."
alias cd........="cd ../../../../../../.."
alias cd.........="cd ../../../../../../../.."
# enable color support for grep
alias grep="grep --color=always"
# version control
alias g="git"
# disk usage (directory sizes)
alias du="du --human-readable --max-depth=1 | sort --human-numeric-sort --reverse"
alias gdu="gdu --no-delete --show-item-count"
# shell script static analysis
alias shellcheck="shellcheck --color=always --shell=bash --exclude=SC1090,SC1091,SC2155"
# extract a tarball
alias untar="tar zxvf"
# clear screen and scrollback buffer
alias cls="clear"
alias c="clear"
# list directory contents
alias ls="LC_ALL=C \ls --almost-all --classify --group-directories-first --color=always"
alias ll="LC_ALL=C \ls -l --almost-all --classify --group-directories-first \
--human-readable --no-group --color=always"
if type eza >/dev/null 2>&1; then
alias l="eza --long --all --git --git-repos-no-status \
--group-directories-first --header --modified --no-quotes \
--classify=always --sort=Name --time-style=long-iso"
alias tree="eza --tree --all --group-directories-first --no-git \
--no-quotes --classify=always --color=always --sort=Name \
--ignore-glob='venv|.git|.tox|*_cache|__pycache__' \
| less"
else
alias l="ll"
fi
# editors (sublime/nano/vim)
if type subl >/dev/null 2>&1; then
alias edit="subl"
alias ed="subl"
alias e="subl --new-window ."
elif type nano >/dev/null 2>&1; then
alias edit="nano"
alias ed="nano"
alias e="nano"
else
alias edit="vi"
alias ed="vi"
alias e="vi"
fi
# open ~/.bashrc for editing
alias ebrc="edit ${HOME}/.bashrc"
# open github website in default browser
alias github="web https://github.com/${GITHUB_USERNAME}"
alias gist="web https://gist.github.com/${GITHUB_USERNAME}"
# python
alias py="python"
# uninstall all python packages in current environment
alias pip-uninstall-all="\
python -m pip freeze |
sed 's/^-e //g' |
PIP_REQUIRE_VIRTUALENV=false \
xargs --no-run-if-empty python -m pip uninstall -y"
# show the zen of python
alias zen="python3 -c 'import this'"
# serve current directory over HTTP on port 8000 (bind all interfaces)
alias webserver="python3 -m http.server"
# =========================================================================================
#
# .o88o. . o8o
# 888 `" .o8 `"'
# o888oo oooo oooo ooo. .oo. .ooooo. .o888oo oooo .ooooo. ooo. .oo. .oooo.o
# 888 `888 `888 `888P"Y88b d88' `"Y8 888 `888 d88' `88b `888P"Y88b d88( "8
# 888 888 888 888 888 888 888 888 888 888 888 888 `"Y88b.
# 888 888 888 888 888 888 .o8 888 . 888 888 888 888 888 o. )88b
# o888o `V88V"V8P' o888o o888o `Y8bod8P' "888" o888o `Y8bod8P' o888o o888o 8""888P'
#
# =========================================================================================
# print bold message to stderr preceded with red ballot x
err() {
printf '%b%b✗%b %b%s%b\n' \
"${BOLD}" "${RED}" "${RESET}" "${BOLD}" "$*" "${RESET}" >&2
}
# print bold message to stderr preceded with green check mark
ok() {
printf '%b%b✓%b %b%s%b\n' \
"${BOLD}" "${GREEN}" "${RESET}" "${BOLD}" "$*" "${RESET}" >&2
}
# list bash functions and aliases
funcs() {
( alias | cut -d= -f1 | sed 's/^alias //' && \
declare -F | sed 's/^.* //g' | grep -v '^_' ) |
sort | less
}
# chop lines at screen width
# - usage: echo $really_long_line | nowrap
nowrap() {
cut -c-"$(tput cols)"
}
# show spinner for indicating progress
spinner() {
local shs=( - \\ \| / ) pnt=0
printf '\e7'
while ! read -rsn1 -t .2 _; do
printf '%b\e8' "${shs[pnt++%${#shs[@]}]}"
done
}
# start spinner background task
start_spinner() {
tput civis
exec {doSpinner}> >(spinner "$@")
}
# stop spinner background task
stop_spinner() {
echo >&"${doSpinner}" && exec {doSpinner}>&-
tput cnorm
echo
}
# extract audio from a YouTube video and save as .mp3
# - usage: yt-mp3 <video url> [quality]
# - examples:
# - encode at highest CBR (320k)
# - yt-mp3 <video url>
# - encode at 256k CBR
# - yt-mp3 <video url> 256k
# - encode at highest quality VBR
# - yt-mp3 <video url> vbr
yt-mp3() {
if [ -z "$1" ]; then
err "please specify a YouTube URL"
return 1
fi
local bitrate="${2:-320k}"
if [ "${bitrate}" = "vbr" ]; then
bitrate="0"
fi
yt-dlp \
--format "bestaudio" \
--extract-audio \
--audio-format mp3 \
--audio-quality "${bitrate}" \
"$1"
}
# download a YouTube video and save as .mp4
yt-video() {
if [ -z "$1" ]; then
err "please specify a YouTube URL"
return 1
fi
yt-dlp \
--format "bestvideo+bestaudio/best" \
--merge-output-format mp4 \
"$1"
}
# colored diffs
dff() {
if [ -z "$1" ] || [ -z "$2" ]; then
err "please enter 2 files to diff"
return 1
fi
\diff --report-identical-files --strip-trailing-cr \
--color=always "$1" "$2" | less
}
alias diff="dff"
# install python packages globally
gpip-install() {
PIP_REQUIRE_VIRTUALENV=false \
python -m pip install --user --upgrade --upgrade-strategy=eager "$@"
}
# uninstall python packages globally
gpip-uninstall() {
PIP_REQUIRE_VIRTUALENV=false \
python -m pip uninstall "$@"
}
# rename all files under the current directory (recursive),
# replacing spaces with underscores. If inside a git repo,
# renames will be tracked by git
replace-whitespace-in-filenames() {
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
find . -path ./.git -prune -o -type f -name "* *" \
-exec bash -c 'git mv "$0" "${0// /_}"' {} \;
else
find . -type f -name "* *" \
-exec bash -c 'mv "$0" "${0// /_}"' {} \;
fi
}
# remove trailing whitespace from lines in given file
# - usage: trim-trailing-whitespace <file>
trim-trailing-whitespace() {
if [ -z "$1" ]; then
err "please specify a file name"
return 1
fi
echo "trimming whitespace..."
perl -pi -e 's/[ \t]+(?=\r?$)//' "$1"
}
# remove trailing whitespace from lines in all files under
# current directory (recursive)
trim-trailing-whitespace-from-files() {
echo "trimming whitespace..."
find . -type f -print0 |
xargs --null --no-run-if-empty sed -i -e 's/[[:blank:]]*$//'
}
# give file(s) a new filesystem identity (inode/file ID) and discard most
# filesystem metadata, while preserving its contents.
# - usage: renew-inode <file_or_glob>
renew-inode() {
if [ -z "$1" ]; then
err "please specify a file or glob pattern with matches"
return 1
fi
for f in "$@"; do
[ -f "${f}" ] || continue
tmp="${f}.tmp.$$"
if cat -- "${f}" >"$tmp"; then
rm -- "${f}" &&
mv -- "${tmp}" "${f}" &&
echo "renewed: ${f}"
else
echo "failed: ${f}"
rm -f -- "${tmp}"
fi
done
}
# remove metadata from an image
# - usage: clean-img-metadata <image_file_or_glob>
clean-img-metadata() {
if [ -z "$1" ]; then
err "please specify an image file or glob pattern with matches"
return 1
fi
if ! type exiftool >/dev/null 2>&1; then
err "exiftool not found"
return 1
fi
echo "removing metadata..."
# keep orientation tag
exiftool -all= -tagsfromfile @ -Orientation -overwrite_original "$@" 2>/dev/null
}
# generate a self-contained html from markdown using pandoc
# - uses modified bootstrap css
# - usage: md2html <markdown_file> [output_html_file]
md2html() {
if [ -z "$1" ]; then
err "please specify a markdown file"
return 1
fi
if ! type pandoc >/dev/null 2>&1; then
err "pandoc not found"
return 1
fi
local input="$1"
local base="${input%.*}"
local output="${2:-${base}.html}"
local title="${base##*/}"
pandoc "${input}" \
--output "${output}" \
--template "${HOME}/.pandoc/template.html" \
--css "${HOME}/.pandoc/template.css" \
--from gfm \
--eol native \
--metadata title="${title}" \
--embed-resources \
--standalone
echo "generated: ${output}"
}
# preview rendered html from a markdown file in web browser
# - generates a temporary self-contained html file
# - launches default browser to view it
# - usage: preview-md2html <markdown_file>
preview-md2html() {
if [ -z "$1" ]; then
err "please specify a markdown file"
return 1
fi
local input="$1"
local filename="${input##*/}"
local basename="${filename%.md}"
local tmpdir="$(mktemp -d)" || return 1
local output="${tmpdir}/${basename}.html"
md2html "${input}" "${output}" || return 1
web "${output}"
}
# print system PATH
path() {
IFS=":"
for d in ${PATH}; do
echo "${d}"
done
unset IFS
}
# use bat for colored help if available
help() {
if type bat >/dev/null 2>&1; then
"$@" --help 2>&1 | bat --plain --language=help
else
builtin help "$@"
fi
}
# search recursively for files or directories matching pattern
# - case-insensitive unless pattern contains an uppercase
# - uses fd if available
# - usage: ff <regex>
ff() {
if type fd >/dev/null 2>&1; then
local command_name="\fd --hidden --no-ignore --color=always "
local exclude_patterns=(
".git/"
".tox/"
".venv/"
"__pycache__/"
"venv/"
)
for pattern in "${exclude_patterns[@]}"; do
command_name+=" --exclude=${pattern}"
done
if [ -n "$1" ]; then
command_name+=" $1"
fi
eval "${command_name}" | less
else
if [ -z "$1" ]; then
err "please enter a search pattern"
return 1
fi
find . \
-xdev \
! -readable \
-prune \
-o \
-iname "*$1*" \
! -path "*/.git/*" \
! -path "*/.tox/*" \
! -path "*/.venv/*" \
! -path "*/__pycache__/*" \
! -path "*/venv/*" \
-print |
\grep --ignore-case --color=always "$1" | less
fi
}
# search recursively in files for pattern (case-insensitive)
# - uses ripgrep if available
# - usage: rg <pattern>
rg() {
if [ -z "$1" ]; then
err "please specify a search pattern"
return 1
fi
if [ -f "${HOME}/.cargo/bin/rg" ]; then
local rg_bin="${HOME}/.cargo/bin/rg"
elif [ -f "${HOME}/Scoop/shims/rg" ]; then # Windows/Scoop/MinGW
local rg_bin="${HOME}/Scoop/shims/rg"
rg_bin="${rg_bin} --path-separator='//'"
fi
if [ -n "${rg_bin+x}" ]; then # using ripgrep
local escaped_pattern=$(sed 's/./\\&/g' <<<"$1")
eval "${rg_bin}" \
--crlf \
--hidden \
--ignore-case \
--ignore-vcs \
--line-number \
--no-ignore \
--no-messages \
--one-file-system \
--with-filename \
--color=always \
--glob='!.git/' \
--glob='!.tox/' \
--glob='!.venv/' \
--glob=!'.*_cache/' \
--glob='!__pycache__/' \
--glob='!venv/' \
"${escaped_pattern}" | less
else
\grep -r \
--ignore-case \
--line-number \
--no-messages \
--with-filename \
--binary-files=without-match \
--color=always \
--devices=skip \
--exclude-dir=.git \
--exclude-dir=.tox \
--exclude-dir=.venv \
--exclude-dir=__pycache__ \
--exclude-dir="venv" \
"$1" | less
fi
}
# search command history by regex (case-insensitive) show last n matches
# - usage: h <pattern>
h() {
local num="50"
history | \grep -v " h " |
\grep --ignore-case --color=always "$1" |
tail -n "${num}"
}
# create directory (make parent directories as needed)
makedir() {
mkdir --parents --verbose "$1"
cd "$1"
}
alias md="makedir"
# reload shell configuration
re-source() {
echo 'sourcing ~/.bashrc...'
unalias -a # remove all aliases
source "${HOME}/.bashrc"
# if a virtual env is active, reactivate it, since the prompt
# prefix gets clobbered
if [ -n "${VIRTUAL_ENV}" ]; then
activate
fi
}
# display weather in boston
weather() {
date
echo
echo -ne "fetching weather...\r"
curl --max-time 10 https://wttr.in/Boston?2F
echo
}
alias w="weather"
# stock watchlist
stocks() {
local tickers="^DJI,^IXIC,^GSPC,^RUI,^RLV,^RLG,^RUT,^RUJ,^RUO,AMZN,COPP,FBTC,FETH,XRPZ"
tickrs \
--show-x-labels \
--summary \
--trunc-pre \
--update-interval 30 \
--symbols "${tickers}"
}
# count all files and symlinks in current directory
# - recursive
# - also shows tracked file if in a git repo
# - ignores .git directories
# - uses fd if available
countfiles() {
if [ -n "$1" ]; then
local path=". $1"
else
local path="."
fi
if type fd >/dev/null 2>&1; then
local num_files=$(\fd --hidden --no-ignore --type=f --type=l --exclude=.git/ "${path}" | wc -l)
else
local num_files="$(find . -type f,l ! -path './.git/*' | wc -l)"
fi
echo "files: ${num_files}"
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
local num_files="$(git ls-files | wc -l)"
echo "tracked files: ${num_files}"
fi
}
# search active processes for pattern (case-insensitive)
# - usage: psgrep <pattern>
psgrep() {
if [ -n "$1" ]; then
ps -ef |
\grep --color=always --extended-regexp --ignore-case "$1" |
\grep --invert-match --word-regexp "grep" | nowrap
else
ps -ef
fi
}
# run pyupgrade against all python files in current directory (recursive)
# and fix recommendations in-place
py-upgrade() {
if ! type pyupgrade >/dev/null 2>&1; then
err "pyupgrade not found"
return 1
fi
local count=0
while IFS= read -r -d '' file; do
pyupgrade --py310-plus "${file}"
count=$((count + 1))
done < <(
find . \
-name "*.py" \
! -path "*/.git/*" \
! -path "*/.tox/*" \
! -path "*/venv/*" \
! -path "*/"*"_cache/*" \
-print0
)
# on Windows, pyupgrade rewrites files with LF line endings,
# so we convert them back
if [[ "${OSTYPE}" == "msys" || "${OSTYPE}" == "cygwin" ]]; then
find . \
-name "*.py" \
! -path "*/.git/*" \
! -path "*/.tox/*" \
! -path "*/venv/*" \
! -path "*/"*"_cache/*" \
-print0 |
xargs --null --no-run-if-empty unix2dos 2>/dev/null
fi
echo
ok "Processed ${count} files"
}
# run refurb against all python files in current directory (recursive)
# and display recommendations
py-refurb() {
if ! type refurb >/dev/null 2>&1; then
err "refurb not found"
return 1
fi
local count=0
while IFS= read -r -d '' file; do
refurb \
--enable-all \
--python-version 3.10 \
--disable FURB107 \
--disable FURB173 \
--disable FURB183 \
--disable FURB184 \
"${file}"
count=$((count + 1))
done < <(
find . \
-name "*.py" \
! -path "*/.git/*" \
! -path "*/.tox/*" \
! -path "*/venv/*" \
! -path "*/"*"_cache/*" \
-print0
)
echo
ok "Processed ${count} files"
}
# clean pip/pipx cache
clean-pip() {
echo "cleaning pip/pipx cache..."
pip cache purge
local dirs=(
"${HOME}/.cache/pip/"
"${HOME}/.cache/pip-tools/"
"${HOME}/.cache/pipx/"
"${HOME}/.local/pipx/.cache/"
"${HOME}/.local/pipx/logs/"
"${HOME}/pipx/.cache/"
"${HOME}/pipx/logs/"
"${HOME}/AppData/Local/pip/cache/"
)
for d in ${dirs[@]}; do
if [ -d ${d} ]; then
echo "deleting ${d}"
rm -rf ${d}
fi
done
}
# clean python dev/temp files from current directory and subdirectories
clean-py() {
if [[ "${PWD}" == "${HOME}" || "${PWD}" != "${HOME}"/* ]]; then
err "can't run from this directory"
return 1
fi
if ! type fd >/dev/null 2>&1; then
err "fd not found"
return 1
fi
local dirs=(
build
dist
)
local recurse_dirs=(
__pycache__
.tox
.venv
.*_cache
*.egg-info
htmlcov
venv
)
local recurse_files=(
*.coverage
*.spec
*.pyc
)
if [ -n "${VIRTUAL_ENV}" ]; then
echo "deactivating venv"
deactivate
fi
echo "cleaning python dev/temp files..."
echo
for d in "${dirs[@]}"; do
if [ -d ${d} ]; then
echo "deleting ${d}/"
rm -rf "${d}/"
fi
done
for rd in "${recurse_dirs[@]}"; do
echo "recursively deleting ${rd}/"
\fd --hidden --no-ignore --glob --exclude=".git/" --type=d "${rd}" \
--exec rm -r
done
for rf in "${recurse_files[@]}"; do
echo "recursively deleting ${rf}"
\fd --hidden --no-ignore --glob --exclude=".git/" --type=f "${rf}" \
--exec rm -r
done
echo
ok "done"
}
# run pytest with coverage and open html report in browser
pytest-with-cov() {
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
err "not a git repository"
return 1
fi
cd "$(git rev-parse --show-toplevel)"
if [ ! -f "pyproject.toml" ]; then
err "not a python project"
return 1
fi
local tmp_dir="$(mktemp -d)"
local html_dir="${tmp_dir}/html"
local cov_cfg="${tmp_dir}/coveragerc"
cat > "${cov_cfg}" <<'EOF'
[run]
branch = True
omit =
*/tests/*
*/test_*
*/venv/*
*/.venv/*
*/site-packages/*
*/dist-packages/*
*/build/*
*/dist/*
EOF
trap 'rm -f "${cov_cfg}"' EXIT
echo "installing packages..."
venv
pip install --group test --upgrade --editable . || pip install --upgrade --editable .
pip install --upgrade pytest-cov
COVERAGE_FILE="${tmp_dir}/.coverage" pytest \
--cov=. \
--cov-context=test \
--cov-config="${cov_cfg}" \
--cov-report=html:"${html_dir}"
web "${html_dir}/index.html"
}
# install a python application in an isoloated environment with the
# current global interpreter
# - usage: pipx-install <package>
pipx-install() {
if [ -z "$1" ]; then
err "please specify a package"
return 1
fi
if ! type pipx >/dev/null 2>&1; then
err "pipx not found"
return 1
fi
if [ -n "${VIRTUAL_ENV}" ]; then
echo "deactivating venv"
deactivate
fi
if [ -d "${HOME}/.pyenv" ]; then
pipx install "$1" --backend=pip --python "$(pyenv which python)"
else
pipx install "$1" --backend=pip
fi
}
# upgrade all pipx applications
# - reinstalls apps if they don't match the current python interpreter version
pipx-upgrade-all() {
if ! type pipx >/dev/null 2>&1; then
err "pipx not found"
return 1
fi
if [ -n "${VIRTUAL_ENV}" ]; then
echo "deactivating venv"
deactivate
fi
echo "upgrading pip..."
PIP_REQUIRE_VIRTUALENV=false python -m pip install --upgrade \
--upgrade-strategy=eager pip
echo "upgrading pipx..."
PIP_REQUIRE_VIRTUALENV=false pip install --user --upgrade \
--upgrade-strategy=eager pipx
local py_version=$(python3 --version)
local pipx_list_output=$(pipx list)
echo "upgrading pipx apps..."
if [[ "${pipx_list_output}" == *"${py_version}"* ]]; then
pipx upgrade-all --backend=pip --pip-args=--upgrade-strategy=eager
else
echo "app versions don't match interpreter. reinstalling packages..."
echo
if [ -d "${HOME}/.pyenv" ]; then
pipx reinstall-all --backend=pip --python "$(pyenv which python)"
else
pipx reinstall-all --backend=pip
fi
fi
echo
local pipx_list_output=$(pipx list)
echo "${pipx_list_output}"
echo
ok "$(grep -c '\- ' <<< ${pipx_list_output}) apps from"\
"$(grep -c 'package ' <<< ${pipx_list_output}) packages installed"
}
# preview markdown file in browser
# - requires GitHub CLI (gh) and gh-markdown-preview extension
# - install extension with: `gh extension install yusukebe/gh-markdown-preview`
preview-md() {