-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path.functions
More file actions
4850 lines (4262 loc) · 131 KB
/
.functions
File metadata and controls
4850 lines (4262 loc) · 131 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
#!/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
}
search_fuzzy() {
local search_dir=""
local search_pattern=""
local RG_ARGS=(
'--follow'
'--glob'
'!**/node_modules/'
'--glob'
'!**/.venv/'
'--glob'
'!**/venv/'
'--glob'
'!package-lock.json'
'--glob'
'!yarn.lock'
'--glob'
'!poetry.lock'
'--glob'
'!**/.git/'
)
while [[ ! $# -eq 0 ]]
do
case "$1" in
-d|--dir)
search_dir=$2
shift 2
;;
-p|--pattern)
search_pattern=$2
shift 2
;;
--all)
RG_ARGS+=("--no-ignore" "--hidden")
shift
;;
# Assume that all other args passed in are for rg
# If adding new args for this function specifically,
# they should be popped off before passing to rg
*)
RG_ARGS+=("$1")
shift
;;
esac
done
# The search path should always come LAST
RG_ARGS+=("$search_dir")
if [[ -z "$search_dir" ]] || ! [[ -d "$search_dir" ]]; then
echo "No search directory specified" 1>&2
return 1
fi
if [[ -z "$search_pattern" ]]; then
echo "No search pattern specified" 1>&2
return 1
fi
selected_options=$(echo -e "File Paths\nFile Contents" | fzf \
--multi \
--bind load:select-all+clear-query \
--header="What would you like to search?" \
--preview 'case {} in
"File Paths") echo "Search File Paths" ;;
"File Contents") echo "Search File Contents" ;;
esac')
SEARCH_FILE_PATHS_ENABLED=0
SEARCH_FILE_CONTENTS_ENABLED=0
# Parse the selected options and set corresponding variables
if echo "$selected_options" | grep -q "File Paths"; then
SEARCH_FILE_PATHS_ENABLED=1
fi
if echo "$selected_options" | grep -q "File Contents"; then
SEARCH_FILE_CONTENTS_ENABLED=1
fi
echo "Searching in $search_dir"
local results=""
if [[ $SEARCH_FILE_CONTENTS_ENABLED -eq 1 ]]; then
local RG_ARGS__CONTENT=("--files-with-matches" "-e" "$search_pattern" "${RG_ARGS[@]}")
echo "RG Args: ${RG_ARGS__CONTENT[*]}"
results=$(rg "${RG_ARGS__CONTENT[@]}" 2>/dev/null)
fi
if [[ $SEARCH_FILE_PATHS_ENABLED -eq 1 ]]; then
# Check filenames too
# WARNING: The use of `--glob SEARCH --glob *SEARCH*` is an ugly workaround for the fact that rg does NOT
# currently support regex-style (or even just partial) filename matching.
# See: https://github.com/BurntSushi/ripgrep/issues/193 and https://github.com/BurntSushi/ripgrep/issues/2314
# ALSO, `**/*SEARCH*/**` is to work around that this partial search issue extends to the middle of the search too,
# in case you are looking to search for directory matches. I feel like there *has* to be a better way to do this.
local RG_ARGS__FILENAMES=("--files" "--glob" "$search_pattern" --glob "*$search_pattern*" --glob "**/*$search_pattern*/**" "${RG_ARGS[@]}")
echo "RG Args: ${RG_ARGS__FILENAMES[*]}"
local filename_results=$(rg "${RG_ARGS__FILENAMES[@]}")
if [[ -z "$results" ]]; then
results="$filename_results"
elif [[ -n "$filename_results" ]]; then
results="$results\n$filename_results"
fi
fi
if [[ -z "$results" ]]; then
echo "No results!"
return 1
fi
# Display results with FZF, with a fancy preview pane
echo "$results" | fzf --multi --reverse --preview-window=wrap --preview "rg --with-filename --line-number --context=10 --no-heading --column --color=always --smart-case -e $search_pattern {}"
# TODO: Copy selected file path to clipboard and/or offer options menu (open in $EDITOR, etc.)
}
search_docs_fuzzy() {
if ! [[ -d "$DOCS_DIR" ]]; then
echo "DOCS_DIR is unset!"
return 1
fi
search_fuzzy --dir "$DOCS_DIR" "$@"
}
search_dev_fuzzy() {
search_fuzzy --dir "$HOME/jtzdev" "$@"
}
search_home_fuzzy() {
search_fuzzy --dir "$HOME" "$@"
}
search_vscode_backups_fuzzy() {
local possible_backup_paths=(
# macOS
"$HOME/Library/Application Support/Code/Backups"
# Linux
"$HOME/.config/Code/Backups"
)
local search_path=""
for possible_path in "${possible_backup_paths[@]}"; do
if [[ -d "$possible_path" ]]; then
search_path="$possible_path"
break
fi
done
if [[ -z "$search_path" ]]; then
echo "Could not locate VS Code backup dir!"
return 1
fi
search_fuzzy --dir "$search_path" "$@"
}
search_fuzzy_all() {
# TODO
:
}
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. Or https://github.com/paoloricciuti/learn-ansi
# However, `tput` seems to be generally preferred over ANSI escape sequences now
# A style reset can take many different forms:
# \033[0m = reset _all_ attributes
# \e[0m = Reset all attributes
# \e[39m = Reset text color
# \e[49m = Reset background color
if (which tput >/dev/null) && [[ -n $TERM ]]; then
TERM_STYLE_RESET="$(tput sgr0)"
fi
# Example invocation (red text):
# > colorize_text colorize_text 196 'ERROR! Oh no!'
colorize_text() {
local color_code=$1
local text=$2
echo -e "\e[38;2;${color_code}m${text}\e[0m"
}
# === /Styling ===
get_shell_type() {
# Make sure bash check comes first, to reduce issues when using subshells
if echo $SHELL | grep --silent -E "\/bash$"; then
echo "BASH"
return
elif echo $SHELL | grep --silent -E "\/zsh$"; then
echo "ZSH"
return
fi
echo "Unknown shell"
return 1
}
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'
USER_CONFIG_DIR=$HOME/.config
OS_NAME="linux"
IS_MAC=0
IS_MAC_SILICON=0
IS_MAC_ROSETTA_ACTIVE=0
ARCH_NAME="$(uname -p)"
ARCH_NAME_PRETTY="$ARCH_NAME"
# E.g. `darwin25.0`
if [[ "$OSTYPE" == "darwin"* ]]; then
USER_CONFIG_DIR=$HOME/Library/Application\ Support
OS_NAME="mac"
IS_MAC=1
# Rather than check `arch` or `uname -p`, better to use full string in case
# this is running under rosetta
if (uname -a | grep -q ARM64_); then
IS_MAC_SILICON=1
ARCH_NAME_PRETTY="arm64 (Apple)"
if [[ "$ARCH_NAME" == "i386" ]]; then
IS_MAC_ROSETTA_ACTIVE=1
ARCH_NAME_PRETTY="i386 (Apple, Rosetta)"
fi
fi
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"
}
resolve_symlink() {
if [[ $IS_MAC -eq 1 ]]; then
greadlink -f "$1"
return
fi
readlink -f "$1"
}
alias symlink_resolve="resolve_symlink"
add_bin_entry() {
local BIN_PATH="$1"
if ! [[ -f $BIN_PATH ]] || ! [[ -x $BIN_PATH ]]; then
echo "$BIN_PATH is not a valid executable"
fi
# Get the absolute path
BIN_PATH=$(realpath "$BIN_PATH")
# symlink into custom bin overrides / PATH
ln -s "$BIN_PATH" "${USER_BIN_OVERRIDES_DIR}/"
}
mac_quarantine_remove() {
local file_path="$1"
if [[ $IS_MAC -ne 1 ]]; then
echo "This is a mac-only command"
return 1
fi
if ! [[ -f "$file_path" ]]; then
echo "Could not find file at $file_path"
return 1
fi
xattr -d com.apple.quarantine "$file_path"
}
apple_ipa_meta_extract() {
local ipa_file_path="$1"
if [[ -z "$ipa_file_path" ]]; then
echo "Error: IPA file path was not provided." >&2
echo "Usage: apple_ipa_meta_extract <path_to_ipa>" >&2
return 1
fi
if [[ ! -f "$ipa_file_path" ]]; then
echo "Error: File not found at '$ipa_file_path'" >&2
return 1
fi
# Extract the entire IPA into a temporary directory (persists after exit).
local extract_dir
extract_dir=$(mktemp -d "${TMPDIR:-/tmp}/ipa_extract.XXXXXX")
unzip -q "$ipa_file_path" -d "$extract_dir"
# Locate Info.plist inside the extracted Payload.
local plist_path
plist_path=$(find "$extract_dir/Payload" -maxdepth 2 -name 'Info.plist' -path '*.app/*' | head -n 1)
if [[ -z "$plist_path" ]]; then
echo "Error: Could not find Info.plist in '$ipa_file_path'" >&2
return 1
fi
# Print Info.plist as readable XML (or raw if plutil is unavailable).
echo "--- Info.plist ---"
if which plutil > /dev/null 2>&1; then
plutil -convert xml1 -o - "$plist_path"
else
echo "plutil is not available; falling back to direct contents of plist" >&2
cat "$plist_path"
fi
# Detect a React Native JS bundle.
echo ""
echo "--- React Native ---"
local jsbundle_path
jsbundle_path=$(find "$extract_dir/Payload" -maxdepth 2 -name '*.jsbundle' -path '*.app/*' | head -n 1)
if [[ -n "$jsbundle_path" ]]; then
echo "RN Bundle: $jsbundle_path"
else
echo "RN Bundle: Not Detected"
fi
# Print the persistent extraction directory.
echo ""
echo "--- Extracted IPA ---"
echo "Extracted to: $extract_dir"
}
# TODO: auto-resolve asdf shims
resolve_alias() {
local ALIAS="$1"
shift
# Each line should be something like:
# `${final_entry_name} is ${bin_path}`
local all_aliases=$(type -a "$ALIAS" | sed -rn 's#^.+ is (.+)$#\1#p')
if (check_args_for_value "--all" "$*"); then
echo $all_aliases
return 0
fi
local final_alias_path=$(echo "$all_aliases" | head -n 1)
# 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"
}
alias alias_resolve="resolve_alias"
alias which_all="resolve_alias --all"
# TODO
bin_info() {
local bin="$1"
local is_file=$([[ -e "$bin" ]] && echo 1 || echo 0)
local is_homebrew=0
local has_homebrew=0
local is_asdf=0
local has_asdf=0
local is_python=0
local has_python=0
local is_node=0
local has_node=0
if [[ $is_file -ne 1 ]]; then
:
else
:
fi
local INFO_TEXT=$(cat <<- EOF
Hello World
EOF
)
render_text_overlay "BIN Info" "$INFO_TEXT"
}
# 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'
}
remove_all_line_breaks() {
echo "$1" | tr -d '\n\r'
}
replace_all_line_breaks() {
echo "$1" | tr '\n\r' ' '
}
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
}
toast() {
local message="$1"
local title="From Your Shell"
while [[ ! $# -eq 0 ]]
do
case "$1" in
-t|--title)
title=$2
shift
;;
-m|--message)
message=$2
shift
;;
esac
shift
done
if [[ $IS_MAC -eq 1 ]]; then
# https://apple.stackexchange.com/a/115373/428959
osascript -e "display notification \"$message\" with title \"$title\""
return 0
fi
# TODO: Linux
alert "$message"
return 0
}
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 "$text") ]]; then
if [[ $FAIL_LOUDLY -eq 1 ]]; then
toast "❌ Empty Selection"
return 1
fi
return 0
fi
echo "$text" | copy_to_clipboard
toast "✅ 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 [[ -f "$md" ]]; then
md=$(cat "$md")
fi
if (which pandoc > /dev/null); then
echo "$md" | pandoc -f gfm -t html
return
else
npx marked --gfm -s "$md"
return
fi
}
markdown_to_pdf() {
local pdf_out_filename="converted.pdf"
local md="$1"
if [[ -f "$md" ]]; then
pdf_out_filename="$md.pdf"
md=$(cat "$md")
fi
echo "$md" | pandoc -f gfm -t pdf --output "$pdf_out_filename"
}
html_to_markdown() {
local html="$1"
echo "$html" | pandoc --from html --to gfm
}
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"
}
clipboard_md_to_html() {
markdown_to_html_clipboard "$(get_clipboard_contents)"
}
alias convert_clipboard_md_to_html="clipboard_md_to_html"
clipboard_to_plaintext() {
# Takes the clipboard contents and converts it to plaintext, in-place
local text=$(get_clipboard_contents)
echo "$text" | copy_to_clipboard
}
alias convert_clipboard_to_plaintext="clipboard_to_plaintext"
clipboard_html_to_md() {
local html=$(get_clipboard_html)
echo "$html" | pandoc --from html --to gfm | copy_to_clipboard
}
alias convert_clipboard_html_to_md="clipboard_html_to_md"
clipboard_html_to_md_reduced() {
local html=$(get_clipboard_html)
echo "$html" | pandoc --from html --to markdown_github-raw_html | copy_to_clipboard
}
clipboard_strip_newlines() {
local text=$(get_clipboard_contents)
remove_all_line_breaks "$text" | copy_to_clipboard
}
clipboard_replace_newlines() {
local text=$(get_clipboard_contents)
replace_all_line_breaks "$text" | 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
}
spreadsheet_to_json() {
SPREADSHEET_FILE_PATH="$1" python << "EOF"
import json
import os
import string
import sys
import csv
filepath = os.environ.get("SPREADSHEET_FILE_PATH")
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 = [v.strip() for v in rows[0]]
# Strip non-printable
headers = list(map(lambda v: ''.join(filter(lambda x: x in string.printable, v)), headers))
only_keys = list(headers)
only_keys_str = os.environ.get("ONLY_KEYS")
if only_keys_str:
only_keys = only_keys_str.split(',')
output_list = []
for row in rows[1:]:
row_dict = {}
for c_index, val in enumerate(row):
if headers[c_index] not in only_keys:
continue
row_dict[headers[c_index]] = val.strip()
output_list.append(row_dict)
indent_spaces_str = os.environ.get("INDENT_SPACES", "2")
indent_spaces = int(indent_spaces_str)
print(json.dumps(output_list, indent=indent_spaces))
EOF
}
spreadsheet_to_html() {
local md=$(spreadsheet_to_markdown "$1")
markdown_to_html "$md"
}
spreadsheet_to_html_clipboard() {
local md=$(spreadsheet_to_markdown "$1")
markdown_to_html_clipboard "$md"
}
firefox() {
if [[ "IS_MAC" -eq 1 ]]; then
/Applications/Firefox.app/Contents/MacOS/firefox "$@"
return 0
fi
return 1
}
firefox_get_profile_dir() {
local firefox_db_location=""
if [[ $IS_MAC -eq 1 ]]; then
firefox_db_location=$(rg \
--files \
--no-ignore \
--glob "**/Profiles/*.default-release/places.sqlite" \
~/Library/Application\ Support/Firefox 2>/dev/null)
else
firefox_db_location=$(find ~/snap/firefox -iname "places.sqlite" -type f 2>/dev/null)
fi
# 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"
}
firefox_find_audio_procs() {
local ff_proc_list=$(lsof -c firefox -a -d txt,mem,fd | grep 'CoreAudio')
if [[ $? -ne 0 ]] || [[ -z $ff_proc_list ]]; then
return 1
fi
echo "$ff_proc_list"
}
# 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() {
local BACKUP_DIR=~/backups/ff
mkdir -p "$BACKUP_DIR"
local OUT_DIR="$(pwd)"