-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
.functions
3554 lines (3138 loc) · 96.3 KB
/
.functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
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
#!/usr/bin/env bash
# shellcheck disable=SC2001
# shellcheck disable=SC2120
# shellcheck disable=SC2155
# set -x
# Bin aliases
alias manssh='docker run -t --rm -v ~/.ssh/config:/root/.ssh/config "jtz-reg/jtz/manssh"'
# === Docs / Reusable Selection Lists ===
docs() {
if [[ -d "$DOCS_DIR" ]]; then
(
cd "$DOCS_DIR" || return
"$EDITOR" .
)
else
open "https://docs.joshuatz.com/"
fi
}
fuzzy_preview() {
local search_dir="$1"
local search_pattern="$2"
if ! [[ -d "$search_dir" ]]; then
return 1
fi
local RG_ARGS=(
"$search_dir"
"--glob"
'!**/node_modules/'
)
results=$(rg --files-with-matches -e "$search_pattern" "${RG_ARGS[@]}")
if [[ -z "$ONLY_CONTENT" ]]; then
# Check filenames too
local filename_results=$(rg --files --glob "$search_pattern" "${RG_ARGS[@]}")
if [[ -z "$results" ]]; then
results="$filename_results"
elif [[ -n "$filename_results" ]]; then
results="$results\n$filename_results"
fi
fi
if [[ -z "$results" ]]; then
return 1
fi
# Display results with FZF, with a fancy preview pane
echo "$results" | fzf --reverse --preview-window=wrap --preview "rg --with-filename --line-number --context=10 --no-heading --column --color=always --smart-case -e $search_pattern {}"
}
docs_fuzzy() {
if ! [[ -d "$DOCS_DIR" ]]; then
echo "DOCS_DIR is unset!"
return 1
fi
fuzzy_preview "$DOCS_DIR" "$@"
}
SIGNALS_PICK_LIST=$(cat << "EOF"
9 KILL (non-catchable, non-ignorable kill)
--- --- ---
1 HUP (hang up)
2 INT (interrupt)
3 QUIT (quit)
6 ABRT (abort)
9 KILL (non-catchable, non-ignorable kill)
14 ALRM (alarm clock)
15 TERM (software termination signal)
EOF
)
docs_signals() {
echo "$SIGNALS_PICK_LIST"
}
# === Styling ===
# For ANSI, this is a helpful guide - https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797
# However, `tput` seems to be generally preferred over ANSI escape sequences now
if (which tput >/dev/null) && [[ -n $TERM ]]; then
STYLE_RESET="$(tput sgr0)"
fi
# === /Styling ===
get_shell_type() {
# Make sure bash check comes first, to reduce issues when using subshells
if [[ -n "$BASH_VERSION" ]] || echo $SHELL | grep --silent -E "\/bash$"; then
echo "BASH"
elif [[ -n "$ZSH_VERSION" ]] || echo $SHELL | grep --silent -E "\/zsh$"; then
echo "ZSH"
return
fi
}
SHELL_TYPE=$(get_shell_type)
# You can use this to parse version strings and then use the resulting number for comparison
# Example:
# if [[ $(parse_version_string $(git --version | grep -E -o "\d+\.\d+.\d+$")) -ge $(parse_version_string "2.39.0") ]]
# https://stackoverflow.com/a/37939589/11447682
function parse_version_string { echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }'; }
parse_version_string_extra() {
parse_version_string "$(echo $1 | sed -E 's/^([0-9]+(\.[0-9]+)*)[^0-9]*.*/\1/')"
}
ARRAY_INDEX_START=0
if [[ "$SHELL_TYPE" == "ZSH" ]]; then
# cmon y'all, can't we just agree on things for once?
ARRAY_INDEX_START=1
ZSH_VERSION_NUM=$ZSH_VERSION
elif [[ "$SHELL_TYPE" == "BASH" ]]; then
BASH_VERSION_NUM=$(parse_version_string "$BASH_VERSION")
fi
# Useful for splitting with non-printable char, etc.
UNIT_SEPARATOR_CHAR=$'\x1F'
IS_MAC=0
if [[ "$OSTYPE" == "darwin"* ]]; then
IS_MAC=1
fi
IS_WAYLAND=0
if [[ $IS_MAC -ne 1 ]] && (loginctl show-session "$(loginctl | grep $(whoami) | awk '{print $1}')" -p Type | grep -q wayland); then
IS_WAYLAND=1
fi
# Expand ~
expand_path() {
local INPUT_PATH=$1
if [[ -z "$INPUT_PATH" ]]; then
echo "ERROR: No path provided"
return 1
fi
INPUT_PATH="${INPUT_PATH/#\~/$HOME}"
echo "$INPUT_PATH"
}
symlink_resolve() {
if [[ $IS_MAC -eq 1 ]]; then
greadlink -f "$1"
return
fi
readlink -f "$1"
}
alias_resolve() {
local ALIAS="$1"
shift
if (check_args_for_value "--all" "$*"); then
type -a "$ALIAS"
return 0
fi
# The last line should be something like `${final_entry_name} is ${bin_path}`
local final_alias_path=$(type -a "$ALIAS" | tail -n 1 | sed -rn 's#^.+ is (.+)$#\1#p')
# The final entry could still be a symlink (which is actually very likely with applications,
# like on mac, `/usr/local/bin/code` is a symlink to the VS Code installed bin,
# under the normal applications folder
if (check_args_for_value "--no-follow" "$*"); then
echo "$final_alias_path"
return 0
fi
symlink_resolve "$final_alias_path"
}
# Not perfect across all OSes, but a "good enough" approach for most
get_computer_name() {
if (which scutil > /dev/null); then
scutil --get ComputerName
return 0
fi
uname -n | sed -e 's/\.local$//'
}
pretty_path() {
echo "$PATH" | tr ':' '\n'
}
augment_path() {
local extra_path=$1
shift
local cmd=$*
(
PATH="$extra_path:$PATH"
$SHELL -c "$cmd"
)
}
# Make sure that you call with "$@", not "$*"
check_args_for_value() {
local search_value="$1"
shift
for arg in "$@"; do
# Note: -x is to force exact whole-line match
if (echo "$arg" | grep -qx -- "$search_value"); then
return 0
fi
done
return 1
}
# TODO / WARNING: Both `get_var_value` and `set_var_value` are
# portable in their inner implementation, but overall
# non-portable because the syntax is checked before
# actual execution.
# If you try to source this file right now in bash, it
# will throw an expansion error on the zsh-specific lines
#
# I think an optimal solution here might be to make `.functions` agnostic
# and then have separate `.functions__zsh` and `.functions__bash`
# (or some naming schema along those lines) for shell-specific
# implementations)
# A way to get the value from a dynamic variable name
# I.e., dereference from pointer to variable held as string name
# https://mywiki.wooledge.org/BashFAQ/006#Indirection
# https://stackoverflow.com/q/16553089/11447682
get_var_value() {
local VAR_NAME="$1"
if [[ "$SHELL_TYPE" == "ZSH" ]]; then
# shellcheck disable=SC2296
echo "${(P)VAR_NAME}"
elif [[ "$SHELL_TYPE" == "BASH" ]]; then
echo "${!VAR_NAME}"
else
echo "Not sure how to handle $SHELL_TYPE"
exit 1
fi
}
# https://mywiki.wooledge.org/BashFAQ/006#Indirection
# https://stackoverflow.com/q/16553089/11447682
set_var_value() {
local VAR_NAME="$1"
local VAR_VALUE=$2
if [[ "$SHELL_TYPE" == "ZSH" ]]; then
# shellcheck disable=SC2296
# shellcheck disable=SC2086
: ${(P)VAR_NAME::=VAR_VALUE}
elif [[ "$SHELL_TYPE" == "BASH" ]]; then
if [[ $BASH_VERSION_NUM -gt $(parse_version_string "4.2") ]]; then
declare -g "${VAR_NAME}=$VAR_VALUE"
elif [[ $BASH_VERSION_NUM -gt $(parse_version_string "3.1") ]]; then
printf -v "$VAR_NAME" %s "$VAR_VALUE"
else
declare -- "${VAR_NAME}=$VAR_VALUE"
fi
else
echo "Not sure how to handle $SHELL_TYPE"
exit 1
fi
}
debug_separator_ifs() {
IFS_CHARS=$(printf '%s' "$IFS" | cat -e | head -n 1)
echo "$IFS_CHARS"
}
trim_whitespace() {
echo "$1" | awk 'NF{$1=$1;print}'
}
# RegEx replacer, using Node's RegExp implementation
# Example:
# regex_replace $'Item A\nItem B 2\nItem C' "/Item A\n.*\d/gim" "Items A & B"
# > Items A & B
# Item C
regex_replace() {
ORIGINAL_STRING="$1" PATTERN="$2" REPLACEMENT="$3" node <<-"EOF"
function strToRegExp(strPattern){
// Test for "/{pattern}/{flags}" input
const regLikePatt = /^\/(.*)\/([igmuy]{0,5})$/;
if (regLikePatt.test(strPattern)){
const pattern = regLikePatt.exec(strPattern)[1];
const flags = regLikePatt.exec(strPattern)[2];
return new RegExp(pattern,flags);
}
else {
return new RegExp(strPattern);
}
}
const originalStr = process.env.ORIGINAL_STRING;
const pattern = process.env.PATTERN;
const replacement = process.env.REPLACEMENT || '';
console.log(originalStr.replace(strToRegExp(pattern), replacement));
EOF
}
remove_first_line() {
echo "$1" | sed -r '1d;'
}
remove_last_line() {
echo "$1" | sed -r '$d'
}
remove_first_and_last_line() {
echo "$1" | sed -r '1d;$d'
}
reload() {
if [[ $SHELL_TYPE == "ZSH" ]]; then
# Note: Don't use source ~/.zshrc
# See: https://github.com/ohmyzsh/ohmyzsh/wiki/FAQ#how-do-i-reload-the-zshrc-file
exec zsh
elif [[ $SHELL_TYPE == "BASH" ]]; then
source ~/.bash_profile
else
echo "Not sure how to reload this shell"
fi
}
alert() {
msg="$1"
# Hello? Is anyone home? It's me, your terminal.
echo -e "\a"
if [[ -n "$msg" ]]; then
if (is_in_tmux); then
tmux display-message "$1"
return 0
fi
# TODO: Add styling
echo "$1"
fi
}
get_clipboard_contents() {
if (which pbpaste > /dev/null); then
pbpaste
elif (which xclip > /dev/null); then
xclip -selection clipboard -o
elif (which wl-paste > /dev/null); then
wl-paste
else
echo "ERROR: Could not find a clipboard utility"
fi
}
get_clipboard_html() {
if [[ $IS_MAC -ne 1 ]]; then
# TODO: Linux support
return 1
fi
# https://stackoverflow.com/a/24132171/11447682
# The Perl part of this is to convert the hex string to a readable string
osascript -e 'the clipboard as «class HTML»' | perl -ne 'print chr foreach unpack("C*",pack("H*",substr($_,11,-3)))'
}
_copy_to_clipboard() {
if (which pbcopy > /dev/null); then
pbcopy
elif (which xclip > /dev/null); then
xclip -selection clipboard
elif (which wl-copy > /dev/null); then
wl-copy
else
echo "ERROR: Could not find a clipboard utility"
fi
}
# shellcheck disable=SC2120
copy_to_clipboard() {
if [[ -n "$1" ]]; then
# Suppress trailing line break while piping
echo -n "$1" | _copy_to_clipboard
else
_copy_to_clipboard
fi
}
# This only overwrites clipboard content if the selection is NOT empty
# It always return 0, so that it can be conveniently used with places
# that expect a copy command to always work
copy_to_clipboard_if_not_empty() {
text="$1"
# make sure to remove both space AND trailing line breaks
if [[ -z $(trim_whitespace "$1") ]]; then
alert "Empty Selection"
return 0
fi
echo "$text" | copy_to_clipboard
alert "Copied to clipboard"
}
copy_html_to_clipboard() {
html="$1"
plaintext="$2"
# Fallback to HTML as plaintext if not set
if [[ -z "$plaintext" ]]; then
plaintext="$html"
fi
if [[ $IS_MAC -eq 1 ]]; then
# If HTML is not prefixed with meta charset tag, add it
if [[ -z "$NO_WRAP" ]] && (! echo "$html" | grep -q -E "^<meta charset"); then
html="<meta charset=\"utf-8\">${html}"
fi
# https://stackoverflow.com/a/11089226/11447682
# https://aaron.cc/copying-the-current-safari-tab-as-a-to-the-clipboard-as-a-clickable-link/
html_hex=$(echo -n "$html" | hexdump -ve '1/1 "%.2x"')
if [[ -n "$NO_PLAIN" ]]; then
osascript <<- EOF
set the clipboard to «data HTML${html_hex}»
EOF
return
fi
# Need to escape any inner double-quotes inside `plaintext` string, since
# we are using`string:"${plaintext}"` as wrapper, or else this will error out.
# E.g.: 6216:6226: syntax error: Expected “,” or “}” but found identifier. (-2741)
local plaintext_escaped=$(echo "$plaintext" | sed 's/"/\\"/g')
if ! (osascript <<- EOF
set the clipboard to {«class HTML»:«data HTML${html_hex}», string:"${plaintext_escaped}"}
EOF
); then
echo "AppleScript failed to set HTML"
return 1
fi
else
echo "$html" | xclip -selection clipboard -t text/html
fi
}
copy_tab_to_clipboard() {
printf "\t" | copy_to_clipboard
}
copy_last_command_to_clipboard() {
last_command=$(fc -ln -1)
echo "$last_command" | copy_to_clipboard
}
markdown_to_html() {
local md="$1"
if (which pandoc > /dev/null); then
echo "$md" | pandoc -f gfm -t html
return
else
npx marked --gfm -s "$md"
return
fi
}
markdown_to_html_clipboard() {
local md="$1"
# If no arg, grab from clipboard
if [[ -z "$md" ]]; then
md="$(get_clipboard_contents)"
fi
html=$(markdown_to_html "$md")
copy_html_to_clipboard "$html" "$md"
echo "✅ HTML copied to clipboard"
}
convert_clipboard_md_to_html() {
markdown_to_html_clipboard "$(get_clipboard_contents)"
}
convert_clipboard_to_plaintext() {
# Takes the clipboard contents and converts it to plaintext, in-place
text=$(get_clipboard_contents)
echo "$text" | copy_to_clipboard
}
convert_clipboard_html_to_md() {
html=$(get_clipboard_html)
echo "$html" | pandoc --from html --to gfm | copy_to_clipboard
}
spreadsheet_to_markdown() {
local filepath="$1"
filepath=$filepath python << "EOF"
import os
import sys
import csv
filepath = os.environ.get("filepath")
if not filepath:
print("❌ No filepath provided")
sys.exit(1)
delimiter = '\t' if filepath.endswith('.tsv') else ','
try:
with open(filepath, 'r') as file:
reader = csv.reader(file, delimiter=delimiter)
rows = list(reader)
except Exception as e:
print(f"❌ Error reading file: {e}")
sys.exit(1)
if not rows:
print("❌ No content to convert")
sys.exit(1)
headers = rows[0]
markdown_table = [
f"| {' | '.join(headers)} |",
f"| {' | '.join(['---'] * len(headers))} |",
*[f"| {' | '.join(row)} |" for row in rows[1:]]
]
markdown_table_str = '\n'.join(markdown_table)
print(markdown_table_str)
EOF
}
firefox() {
if [[ "IS_MAC" -eq 1 ]]; then
/Applications/Firefox.app/Contents/MacOS/firefox "$@"
return 0
fi
return 1
}
firefox_get_profile_dir() {
if [[ $IS_MAC -ne 1 ]]; then
# TODO: Linux support
return 1
fi
local firefox_db_location=$(rg \
--files \
--no-ignore \
--glob "**/Profiles/*.default-release/places.sqlite" \
~/Library/Application\ Support/Firefox 2>/dev/null)
# Error out on no matches, or greater than 1 match
if [[ -z "$firefox_db_location" ]]; then
echo "ERROR: Could not find Firefox DB location"
return 1
fi
if [[ $(echo "$firefox_db_location" | wc -l) -gt 1 ]]; then
# TODO: Support multiple profiles?
echo "ERROR: Found more than one Firefox DB location"
return 1
fi
dirname "$firefox_db_location"
}
# Convert Mozilla's non-standard LZ4 files (jsonlz4 or mozlz4) to JSON
# The special things about moz's lz4 implementation are:
# - Non-standard header - first 8 bytes, magic `mozLz40\0`
# - Uses blocks instead of frame (making it incompatible, as-is, with the
# lz4 CLI)
moz_lz4json_to_json() {
local mozlz4_file="$1"
if ! [[ -f $mozlz4_file ]]; then
echo "File $mozlz4_file does not exist"
return 1
fi
# Check for magic header bytes
if ! [[ $(head -c 7 "$mozlz4_file") == "mozLz40" ]]; then
echo "Not a Mozilla LZ4 JSON file"
return 1
fi
# Make sure mozlz4_file is full path
mozlz4_file=$(realpath "$mozlz4_file")
# Check for required python package
ensure_pkg_in_dotfiles_venv "lz4"
python_script=$(cat <<- EOF
import lz4.block
import json
with open("$mozlz4_file", "rb") as f:
f.seek(8)
decompressed = lz4.block.decompress(f.read())
decoded = decompressed.decode("utf-8")
parsed_json = json.loads(decoded)
print(json.dumps(parsed_json, indent=2))
EOF
)
mozlz4_file="$mozlz4_file" run_raw_python_in_dotfiles_venv "$python_script"
}
# WARNING: This produces a *huge* (multi-MB) JSON file
firefox_dump_restore_file() {
if ! local firefox_profile_dir="$(firefox_get_profile_dir)"; then
return 1
fi
local firefox_recovery_file_path="${firefox_profile_dir}/sessionstore-backups/recovery.jsonlz4"
local temp_dir="$(mktemp -d)"
cp "$firefox_recovery_file_path" "$temp_dir/"
moz_lz4json_to_json "$temp_dir/recovery.jsonlz4"
}
firefox_get_tabs() {
:
# TODO
}
# Copies the Firefox DB (`places.sqlite`) to a temp dir,
# to avoid lock issues / concurrency / corruption
firefox_get_temp_db_copy() {
local VERBOSE=0
if [[ $* == *--verbose* ]]; then
VERBOSE=1
fi
local firefox_profile_dir=$(firefox_get_profile_dir)
if ! [[ $? -eq 0 ]]; then
return 1
fi
local firefox_db_location="$firefox_profile_dir/places.sqlite"
[[ $VERBOSE -eq 1 ]] && echo "Firefox DB location(s) = $firefox_db_location"
# Copy database to a temp directory to avoid lock issues / concurrency / corruption
local temp_dir=$(mktemp -d)
local temp_db_copy="$temp_dir/places.sqlite"
[[ $VERBOSE -eq 1 ]] && echo "💾 Creating temporary copy of FF DB"
cp "$firefox_db_location" "$temp_db_copy"
echo "$temp_db_copy"
}
firefox_db_interact() {
local VERBOSE=0
if [[ $* == *--verbose* ]]; then
VERBOSE=1
fi
local callback=$1
if [[ -z "$callback" ]]; then
echo "ERROR: No callback provided"
return 1
fi
shift
local temp_db_copy=$(firefox_get_temp_db_copy)
# Call our callback with the temporary db, to let it do whatever it wants
$callback "$temp_db_copy"
# Cleanup!
[[ $VERBOSE -eq 1 ]] && echo "🗑️ Cleaning up temp DB copy"
rm -f "$temp_db_copy"
[[ $VERBOSE -eq 1 ]] && echo "✅ Firefox DB interaction complete"
}
# Get members of a firefox bookmarks group by group ID or name
# Returns joined rows as JSON
firefox_get_bookmark_group_members() {
if ! (which sqlite3 > /dev/null); then
echo "ERROR: sqlite3 not found"
return 1
fi
local temp_db_copy=$(firefox_get_temp_db_copy)
bookmark_group_name_or_id=$1
GROUP_ID=$1
IS_ID=$(echo "$bookmark_group_name_or_id" | grep -E -q "^[0-9]+$" && echo "true" || echo "false")
if [[ "$IS_ID" == "false" ]]; then
GROUP_ID=$(sqlite3 "$temp_db_copy" "SELECT id FROM moz_bookmarks WHERE title = '$bookmark_group_name_or_id';")
if [[ -z "$GROUP_ID" ]]; then
echo "ERROR: Could not find bookmark group '$bookmark_group_name_or_id'"
return 1
fi
fi
sqlite3 \
"$temp_db_copy" \
".mode json" \
"SELECT * FROM moz_bookmarks JOIN moz_places ON moz_bookmarks.fk = moz_places.id WHERE moz_bookmarks.parent = '$GROUP_ID';"
rm -f "$temp_db_copy"
}
chrome() {
if [[ "IS_MAC" -eq 1 ]]; then
: "${CHROME_BIN:="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"}"
"$CHROME_BIN" "$@"
return 0
fi
return 1
}
# Opens firefox, with each URL passed at the end, as a new tab
# Currently, with tree style tabs, the first URL becomes the root tab
# and any subsequent new tabs are loaded as children
# (TODO: Make this more flexible)
# See: http://kb.mozillazine.org/Command_line_arguments
firefox_with_tabs() {
args=("-new-window")
for arg in "$@"; do
args+=("-new-tab" "-url" "$arg")
done
firefox "${args[@]}"
}
# Opens Chrome, with each URL passed at the end, as a new tab
# See: https://peter.sh/experiments/chromium-command-line-switches/
chrome_with_tabs() {
args=("--new-window")
for arg in "$@"; do
args+=("$arg")
done
chrome "${args[@]}"
}
# This opens a new browser with a preset group of tabs, based on stdin JSON
# that matches the `browser-group.json` schema.
# See [browser-groups.json](./schemas/browser-groups.json).
# It defaults to Firefox - use `--chrome` to launch with Chrome instead.
open_browser_group_url() {
local JSON=$1
shift
local BROWSER="firefox"
if (check_args_for_value "--chrome" "$*"); then
BROWSER="chrome"
fi
local OPEN_ALL=0
if (check_args_for_value "--all" "$*"); then
OPEN_ALL=1
fi
# Pass the list of tabs (URLS) to the browser
local TAB_URLS=($(echo "$JSON" | jq -r ".tabs[].url"))
# Check for empty array
if [[ ${#TAB_URLS[@]} -eq 0 ]]; then
echo "ERROR: No tabs found"
return 1
fi
if [[ $OPEN_ALL -eq 1 ]]; then
if [[ "$BROWSER" == "firefox" ]]; then
firefox_with_tabs "${TAB_URLS[@]}"
elif [[ "$BROWSER" == "chrome" ]]; then
chrome_with_tabs "${TAB_URLS[@]}"
fi
return 0
fi
local SELECTED_TAB_URL=$(echo "$JSON" | jq -r '.tabs[] | "\(.notes) || \(.url)"' | fzf | awk -F '\\|\\|' '{print $2}')
if [[ -n "$SELECTED_TAB_URL" ]]; then
if [[ "$BROWSER" == "firefox" ]]; then
firefox "$SELECTED_TAB_URL"
elif [[ "$BROWSER" == "chrome" ]]; then
chrome "$SELECTED_TAB_URL"
fi
return 0
fi
return 1
}
# Get nested workspace JSON by name, or with TUI selector
get_workspace_json() {
local WORKSPACE_NAME=$1
local CONSIDER_ONLY_ACTIVE_WORKSPACES=$(
{ [[ -n "$ALL_WORKSPACES" ]] || [[ $* == *--all* ]]; } && echo "y" || echo "n"
)
local workspaces_file=~/.workspaces.json
if ! [[ -f "$workspaces_file" ]]; then
echo "ERROR: Could not find workspaces file at $workspaces_file"
return 1
fi
local JSON=$(cat "$workspaces_file")
local NAME_KEYS=()
local NAME_KEYS_STR=$(echo "$JSON" | jq -r 'del(."$schema") | keys[]' 2>/dev/null)
while IFS='' read -r line; do NAME_KEYS+=("$line"); done < <(echo "$NAME_KEYS_STR")
# Check if WORKSPACE_NAME is valid (in list of keys)
local FOUND_KEY=0
for key in "${NAME_KEYS[@]}"; do
if [[ "$key" == "$WORKSPACE_NAME" ]]; then
FOUND_KEY=1
break
fi
done
# If key was not found, offer a selector TUI (preview is group config)
if [[ $FOUND_KEY -eq 0 ]]; then
if [[ "$CONSIDER_ONLY_ACTIVE_WORKSPACES" == "n" ]]; then
NAME_KEYS_STR=$(echo "$JSON" | jq -r 'del(."$schema") | with_entries(select(.value.active == true)) | keys[]' 2>/dev/null)
fi
WORKSPACE_NAME=$(echo "$NAME_KEYS_STR" | fzf --preview "jq '.\"{}\"' $workspaces_file")
fi
if [[ -z "$WORKSPACE_NAME" ]]; then
return 1
fi
echo "$JSON" | jq -r "$(printf '."%s"' "$WORKSPACE_NAME")"
}
open_workspace() {
local WORKSPACE_NAME=$1
local WORKSPACE_JSON=$(get_workspace_json "$WORKSPACE_NAME")
if [[ -z "$WORKSPACE_JSON" ]]; then
return 1
fi
# Don't open slack by default - require `--with-slack`
if (check_args_for_value "--with-slack"); then
local first_slack_channel=$(echo "$WORKSPACE_JSON" | jq -r ".slackChannels[0]")
if [[ "$first_slack_channel" != "null" ]]; then
local TEAM_ID=$(echo "$first_slack_channel" | jq -r '.teamId')
local CHANNEL_ID=$(echo "$first_slack_channel" | jq -r '.channelId')
open "slack://channel?team=${TEAM_ID}&id=${CHANNEL_ID}"
fi
fi
local first_ide_project_root=$(echo "$WORKSPACE_JSON" | jq -r ".ideProjectRoots[0]")
if [[ "$first_ide_project_root" != "null" ]]; then
code "$(expand_path "$first_ide_project_root")"
fi
local first_browser_group_json=$(echo "$WORKSPACE_JSON" | jq -r ".browserGroups[0]")
if [[ "$first_browser_group_json" != "null" ]]; then
open_browser_group_url "$first_browser_group_json" "--$BROWSER" --all
fi
local tmux_session_name=$(echo "$WORKSPACE_JSON" | jq -r ".preferredTmuxSessionName")
if [[ "$tmux_session_name" != "null" ]]; then
# Note: tmux_auto_open already gracefully handles if session is already open
tmux_auto_open "$tmux_session_name"
fi
}
open_workspace_url() {
local WORKSPACE_NAME=""
local PASS_THROUGH_ARGS=()
while [[ ! $# -eq 0 ]]
do
case "$1" in
-w|--workspace)
WORKSPACE_NAME=$2
shift
shift
;;
*)
PASS_THROUGH_ARGS+=("$1")
shift
;;
esac
done
local WORKSPACE_JSON=$(get_workspace_json "$WORKSPACE_NAME")
local first_browser_group_json=$(echo "$WORKSPACE_JSON" | jq -r ".browserGroups[0]" 2>/dev/null)
if [[ $? -eq 0 ]] && [[ "$first_browser_group_json" != "null" ]]; then
open_browser_group_url "$first_browser_group_json" "${PASS_THROUGH_ARGS[@]}"
else
echo "Could not fetch browserGroups. Is it configured in the JSON config?"
return 1
fi
}
date_iso() {
# 2020-11-28T12:11:28Z
date -u +"%Y-%m-%dT%H:%M:%SZ"
}
date_ms() {
if which gdate > /dev/null; then
gdate +%s%3N
else
date +%s000
# echo "WARNING: gdate not found; faking millseconds from seconds"
fi
}
# Like `touch` + `mkdir -p`: creates intermediate directories if they don't exist yet
make_file() {
file_path=$1
if [[ -e $file_path ]]; then
echo "File already exists"
else
mkdir -p "$(dirname "$file_path")"
touch "$file_path"
fi
}
get_cpu_throttle_info() {
if [[ $* == *--watch* ]]; then
pmset -g thermlog
return
fi
pmset -g therm
}
make_venv() {
VENV_PATH=./.venv
echo "Where should the virtual environment be created? (press enter to default to .venv)"
read -r INPUT
if [[ $INPUT != "" ]]; then
VENV_PATH=$INPUT
fi
if [[ -d $VENV_PATH ]]; then
echo "${VENV_PATH} already exists"
else
echo "Preparing virtual environment in ${VENV_PATH}"
python3 -m venv $VENV_PATH
source $VENV_PATH/bin/activate
fi
}
check_venv() {
which python | grep "$PWD"
}
# Generates the poetry named environment string
# Although this _can_ be used to check that the correct virtual environment is
# activated, it is generally much easier to just use a regular venv and point
# poetry to it (because then you can just do something like `which python | grep $PWD`)
# For implementation reference see
# https://github.com/python-poetry/poetry/blob/7c86992909257caa4f51a50c001f5894bfe5065e/src/poetry/utils/env.py#L635
# https://github.com/python-poetry/poetry/blob/7c86992909257caa4f51a50c001f5894bfe5065e/src/poetry/utils/env.py#L1212-L1220
generate_poetry_env_name_str() {
PROJECT_NAME=$(basename "$PWD")
if [[ -f pyproject.toml ]]; then
PROJECT_NAME=$(poetry version | sed -E -n 's/(.+) [.0-9]+$/\1/p')
fi
PROJECT_NAME=$PROJECT_NAME python << "EOF"
import base64
import os
import re
import hashlib
# shim - re-implement poetry encode method
def encode(string: str):
if isinstance(string, bytes):
return string
return string.encode("utf-8")
def generate_env_name(package_name: str, cwd: str) -> str:
package_name = package_name.lower()
sanitized_name = re.sub(r'[ $`!*@"\\\r\n\t]', "_", package_name)[:42]
normalized_cwd = os.path.normcase(os.path.realpath(cwd))
h_bytes = hashlib.sha256(encode(normalized_cwd)).digest()
h_str = base64.urlsafe_b64encode(h_bytes).decode()[:8]
return f"{sanitized_name}-{h_str}"
cwd = os.getcwd()
print(generate_env_name(os.environ["PROJECT_NAME"], cwd))
# Should print something like `project-name-ABCD1a-Z`
EOF
}
# Search for, and activate, a local python virtual environment
# @TODO - if python env is *already* activated, check if path matches, and if not
# deactivate and then activate
# @TODO - handle Poetry
activate() {
fail=1
possible_envs=(./venv ./.venv ./env ./.env)
for env_dir in "${possible_envs[@]}"; do
if [[ -e "$env_dir/bin/activate" ]]; then
source "$env_dir/bin/activate"
fail=0
break
fi
done
return $fail
}
# TODO set up auto-activate on every shell start
pip_upgrade() {
python3 -m pip install --upgrade pip
}
# Like clear, but extra space to pad the start
wipe() {
for run in {1..10}; do
echo $'\n'
done
clear
}
render_image() {
IMAGE_PATH=$1
# Wezterm
if (which wezterm > /dev/null) && (is_in_wezterm); then
wezterm imgcat "$IMAGE_PATH"
return
fi
# ImageMagick
if (which display > /dev/null); then
# Sometimes can be installed, but misconfigured. Can use a simple` --version`
# check to verify
if (display --version > /dev/null 2>&1); then
display "$IMAGE_PATH"
return
else
echo "WARNING: ImageMagick installed, but not configured correctly"
fi
fi
if (which chafa > /dev/null); then
chafa "$IMAGE_PATH"
return
fi
echo "ERROR: Could not find a suitable image viewer"
return 1
}
render_table() {
local horizontal_scroll="true"
if [[ $* == *--no-h-scroll* ]]; then
horizontal_scroll="false"
fi