-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path.functions
782 lines (629 loc) · 21.9 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
tmux-kill-detached-sessions() {
sleep 10
# TODO add `all` param and remove the digit grep to kill all unattached sessions
# `grep -v attached | grep -E '^\d{1,3}'` will only grab non-vs-code sessions
tmux list-sessions | grep -v attached | awk -F: '{print $1}' | xargs -I {} tmux kill-session -t {}
}
# delete all unused, update all plugins, reset completions
zinit-update() {
zinit self-update
zinit delete --clean
zinit update --all --parallel
zinit cclear
}
# destroy your entire zinit setup, helpful when something seems off but you aren't sure why...
zinit-nuke() {
rm -f ~/.zcompdump*
rm -rf ~/.zsh/cache
rm -rf ~zinit
echo "Open up a new terminal window to reload zinit"
}
# TODO this does not work as cleanly as you'd expect... needs some work.
# TODO export ZSH_XTRACEFD=5 isn't a thing yet :/ https://www.zsh.org/mla/workers//2020/msg01177.html
zsh-trace() {
exec 2>> /tmp/zsh-debug.log
set -x
echo "Tracing enabled. Log file: /tmp/zsh-debug.log"
}
# https://yazi-rs.github.io/docs/quick-start
function y() {
local tmp="$(mktemp -t "yazi-cwd.XXXXXX")" cwd
yazi "$@" --cwd-file="$tmp"
if cwd="$(command cat -- "$tmp")" && [ -n "$cwd" ] && [ "$cwd" != "$PWD" ]; then
builtin cd -- "$cwd"
fi
rm -f -- "$tmp"
}
# pass path to image to copy it to clipboard
pbcopy-image() {
if [ -z "$1" ]; then
set -- "$(pbpaste)"
fi
if [ ! -f "$1" ]; then
echo "Error: File $1 does not exist."
return 1
fi
osascript -e "set the clipboard to (read (POSIX file \"$1\") as JPEG picture)"
}
###########################
# Mise Utilities
###########################
# use plugin name as only parameter
mise-current-version() {
if [ $# -gt 1 ]; then
echo "Error: Only one plugin name is allowed"
return 1
fi
mise list --current --json | jq -r ".$1[0].version // empty"
}
# Loop through all arguments (assumed to be mise plugins)
mise-generate-tool-versions() {
for plugin in "$@"; do
version=$(mise-current-version "$plugin")
if [ -n "$version" ]; then
echo "$plugin $version" >> .tool-versions
else
echo "Error: Version for $plugin not found."
fi
done
}
# use plugin name as initial parameter
mise-reinstall() {
if [ $# -gt 1 ]; then
echo "Error: Only one plugin name is allowed"
return 1
fi
version=$(mise-current-version $1)
if [ -z "$version" ]; then
echo "Error: Version not found for $1"
return 1
fi
mise uninstall $1@$version
mise install $1@$version
}
###########################
# Python Utilities
###########################
# create a file to automatically import pretty-traceback on startup
python-inject-startup() {
local site_packages=$(python -c "import site; print(site.getsitepackages()[0])")
local pth_file=$site_packages/mbianco_injection.pth
local py_file=$site_packages/_mbianco_injection.py
if [[ -f "$pth_file" ]]; then
echo "python startup already exists: $target_file"
return 1
fi
cat << 'EOF' > "$py_file"
def run_startup_script():
try:
import pretty_traceback
pretty_traceback.install()
except ImportError:
pass
run_startup_script()
EOF
# the pth file must have a single line, so it's easier to import another file
echo "import _mbianco_injection" > "$pth_file"
echo "Python startup injection created: $pth_file"
}
pyd() {
local executable=$1
if ! [ -f "$executable" ]; then
executable=$(which "$executable")
fi
echo "$executable ${@:2}"
eval "ipdb3 -c continue -- $executable ${@:2}"
}
# when hacking on a package with `pip-show` this will properly wipe + reinstall the package
# also allows installing a package from a git repo
pip-pristine() {
if [[ $1 == http* ]]; then
# Fetch pyproject.toml from GitHub using Python's requests library
package_name=$(python -c "
import requests
import toml
from io import StringIO
try:
response = requests.get('$1/raw/main/pyproject.toml')
response.raise_for_status()
except requests.exceptions.HTTPError:
# If fetching from the 'main' branch fails, try the 'master' branch
response = requests.get('$1/raw/master/pyproject.toml')
data = StringIO(response.text)
config = toml.load(data)
print(config['tool']['poetry']['name'])
")
pip uninstall -y $package_name
pip cache remove $package_name
else
pip uninstall -y $1
pip cache remove $1
fi
pip install $1
}
# find the location of a pip package
pip-show() {
# convert - => _
package_name=${1//-/_}
package_path=$(pip show $package_name | grep "Location:" | awk '{print $2}' | tr -d "\n")/$package_name
echo $package_path
cd $package_path
code $package_path
}
###########################
# Network Sniffing
###########################
start_network_proxy() {
SERVICE="Ethernet"
PROXY_ADDRESS="localhost"
PROXY_PORT="8084"
disable_proxy() {
echo "Disabling proxies for $SERVICE..."
sudo networksetup -setsocksfirewallproxystate "$SERVICE" off
echo "Proxies disabled for $SERVICE"
}
# Check if the mitmproxy certificate is in the keychain
if [[ -z $(security find-certificate -a -c "mitmproxy" -p) ]]; then
echo "mitmproxy certificate not found in the system keychain. Adding it now..."
sudo security add-trusted-cert -d -p ssl -p basic -k /Library/Keychains/System.keychain ~/.mitmproxy/mitmproxy-ca-cert.pem
else
echo "mitmproxy certificate is already in the system keychain."
fi
echo "Starting mitmproxy on port $PROXY_PORT..."
# Set SOCKS5 proxy
sudo networksetup -setsocksfirewallproxy "$SERVICE" "$PROXY_ADDRESS" "$PROXY_PORT"
sudo networksetup -setsocksfirewallproxystate "$SERVICE" on
echo "SOCKS5 proxy set for $SERVICE"
# Start mitmproxy in SOCKS5 mode with TLS version adjustment
mitmproxy --mode socks5 --listen-port $PROXY_PORT --set tls_version_client_min=SSL3
# Clean up proxy settings after mitmproxy exits
disable_proxy
}
###########################
# Docker Utilities
###########################
set_docker_config() {
# set default `ps` format to be much shorter
touch ~/.docker/config.json
yq -i '.psFormat = "table {{.ID}}\t{{.Image}}\t{{.Names}}"' ~/.docker/config.json
# set default log size to be a reasonable, but not unbounded, size
touch ~/.docker/daemon.json
yq -i '.log-driver = "json-file" | .log-opts.max-size = "10m" | .log-opts.max-file = "3"' ~/.docker/daemon.json
}
# Usage: docker-shell container_name user
# - container name (can be partial) as first arg
# - [optional] user as second arg
#
# Description: shell inside of existing container
docker-shell() {
local container_ids=($(docker ps -aqf "name=$1"))
local user_option=""
if [ ${#container_ids[@]} -gt 1 ]; then
echo "Error: Multiple containers match the name '$1'."
return 1
elif [ ${#container_ids[@]} -eq 0 ]; then
echo "Error: No containers found matching the name '$1'."
return 1
fi
local container_id=${container_ids[0]}
if [ -n "${2-}" ]; then
user_option="-u $2"
fi
eval "docker exec -it $user_option $container_id bash"
}
# get files that would be included in a Dockerfile, with size in megabytes
dockerignore-test() {
rsync --dry-run -av --exclude-from='.dockerignore' --out-format="%l %n" ./ /tmp/ | \
awk '{size_mb = $1 / (1024 * 1024); printf "%.2f MB %s\n", size_mb, $2}' | \
sort -k1,1nr -k2,2 | \
less
}
# TODO docker-new-bash, run instead of exec
# add key to remove server
# ssh-add-key <server>
ssh-add-key() {
ssh-copy-id -i ~/.ssh/id_rsa.pub $1
ssh $1
}
# useful for cleaning up text from tmux
# trims whitespace and removes quotes (single and double) if they are trailing + leading
trim-and-unquote() {
sed -E 's/^[ \t]+//;s/[ \t]+$//;s/^['\''"](.*)['\''"]$/\1/'
}
# a touch command which creates folders too
function touchp() {
mkdir -p $(dirname $1) && touch "$1"
}
# all the dig info
function diga() {
dig +nocmd "$1" any +multiline +noall +answer
}
# for quick gpt prompt generation
files-to-markdown() {
for file in "$@"; do
if [[ -f "$file" ]]; then
echo "### File: $file"
echo '```'
cat "$file"
echo '```'
echo ''
else
echo "File $file does not exist." >&2
fi
done
}
ask_llm() {
local files=()
local message=""
local system_prompt="Be very concise. I am an expert programmer."
for arg in "$@"; do
if [[ -f "$arg" ]]; then
files+=("--context-file" "$arg")
else
message="$arg"
fi
done
# if no message, exit
if [[ -z "$message" ]]; then
echo "No message provided."
return 1
fi
cody chat --stdin "${files[@]}" --message "$system_prompt\n$message"
}
# can't use a `?` in a function name, only an alias
alias "llm?"="ask_llm"
# TODO add to remote-logout repo
# https://github.com/iloveitaly/remote-logout
# https://serverfault.com/questions/10404/log-out-graphical-user-from-command-line
macos-logout() {
if [ -z "$1" ]; then
echo "Error: No user specified."
return 1
fi
if ! id -u "$1" > /dev/null 2>&1; then
echo "Error: User $1 does not exist."
return 1
fi
sudo launchctl bootout user/$(id -u "$1")
sudo pkill -u "$1"
# may need to kill WindowManager here too, looks like that is the one that gets tripped up
}
copy_with_context() {
local file=$1
local line=$2
if [[ -z "$file" ]]; then
echo "Usage: copy_with_context <file> <line> | <file-with-line>"
return 1
fi
# if line DNE, then it must be embedded in the first argument
if [[ -z "$line" ]]; then
IFS=':' read file line _other <<< "$file"
fi
# check if $line is a number
if ! [[ $line =~ ^[0-9]+$ ]]; then
echo "Error: Line number must be a number (extracted line: $line)."
return 1
fi
local context=10
local start=$((line - context > 0 ? line - context : 1))
local end=$((line + context))
sed -n "${start},${end}p" "$file" | pbcopy
}
##################################
# Local Written-by-me Code Search
# https://mikebian.co/fast-local-written-by-you-code-search/
##################################
# create a local index of all git repos
index_local_repositories() {
fd --hidden --type=directory "\.git$" ~/Projects -x sh -c '
repo=$(dirname "$0")
origin=$(git -C "$repo" remote get-url origin 2>/dev/null)
if [[ -z "$origin" ]] || [[ "$origin" == *"github.com/iloveitaly/"* ]]; then
if [[ -z "$origin" ]] || ! git -C "$repo" remote get-url upstream &>/dev/null; then
echo "$repo"
fi
fi
' {} \; > ~/.local-git-repos
}
# ripgrep code search
rgc() {
if [[ ! -f ~/.local-git-repos ]]; then
index_local_repositories
fi
if [[ $(/usr/bin/find ~/.local-git-repos -mtime +7) ]]; then
# reindex async if it hasn't been done in awhile
index_local_repositories &
fi
# an alternative to `cut` is using -r rg option to mutate the content output
# https://github.com/BurntSushi/ripgrep/issues/2860
rg --hidden --glob '!**/.git/**' "$@" $(cat ~/.local-git-repos) | \
# we don't want column, just file and line
cut -d: -f1-2 | \
# now that we only have file + line, we can remove duplicates
uniq | \
# nth will still display `:`, which is annoying
fzf --ansi --delimiter : --with-nth '1' \
--keep-right \
--preview 'height=$(tput lines); start={2}; context=$((height / 2)); bat --color=always --paging=never --highlight-line {2} --line-range $((start > context ? start - context : 1)):$((start + context)) {1}'
}
###########################
# Local Filesystem Searches
###########################
# determine if we are in a node_modules folder or if a valid node_modules path was passed via any argument
function _is_node_modules() {
local node_modules_path=$1
if [[ -z "$node_modules_path" ]]; then
node_modules_path=$(pwd)
fi
[[ "$node_modules_path" =~ node_modules$ ]]
}
function _is_venv() {
local venv_path=$1
if [[ -z "$venv_path" ]]; then
venv_path=$(pwd)
fi
[[ "$venv_path" =~ \.venv$ ]]
}
alias ff="fzf --preview='bat --color=always {}'"
# TODO this should use the `cd` thing and just overload there instead
# fd + fzf, cd into the selected directory
fdd() {
local additional_args=""
if _is_node_modules "$@" || _is_venv "$@"; then
additional_args="--no-ignore-vcs --hidden"
fi
local file_or_directory=$(fd ${=additional_args} "$@" | fzf --preview 'if [ -d {} ]; then exa -1 --color=always {}; elif [ -f {} ]; then cat {}; fi')
# cd into dir or view the file
if [[ -n "$file_or_directory" ]]; then
if [[ -d "$file_or_directory" ]]; then
cd "$file_or_directory"
elif [[ -f "$file_or_directory" ]]; then
cat "$file_or_directory"
fi
fi
}
RIPGREP_LIVEGREP_EXCLUSIONS=("--glob=!.git/**" "--glob=!.venv" "--glob=!.pnpm" "--glob=!node_modules" "--glob=!.tox" "--glob=!cdk.out")
# TODO add fzf support
# search all files in the current directory
rgu() {
# TODO use glob list from find-replace
rg -uu "${RIPGREP_LIVEGREP_EXCLUSIONS[@]}" "$@"
}
# livegrep-like local search
# related: https://github.com/seletskiy/zsh-fuzzy-search-and-edit/blob/master/plugin.zsh
rgg() {
local additional_args=""
# TODO should check search page in $@ as well
if [[ $(pwd) =~ node_modules$ ]] || [[ $(pwd) == *"/.venv/"* ]]; then
# in this case, we want to search the contents of the node_modules directory
# this is a common case for me, trying to debug various package bugs in a project I'm working on
additional_args="--no-ignore-vcs --hidden"
fi
# TODO --bind=\"ctrl-y:execute-silent(echo {} | cut -d: -f1 | tr -d '[:space:]' | pbcopy)\" \
local file_and_location=$(rg --color always --hidden "$@" ${=additional_args} | fzf --ansi --delimiter : --with-nth '1,4' --preview 'height=$(tput lines); start={2}; context=$((height / 2)); bat --color=always --paging=never --highlight-line {2} --line-range $((start > context ? start - context : 1)):$((start + context)) {1}')
# Extracting the file name from the selected line
local file=$(echo "$file_and_location" | awk -F: '{print $1}')
if [[ ! -z "$file" ]]; then
open "$file"
fi
}
# combine all matching files into a single string and copy to clipboard, helpful for AI stuff
find_and_bundle() {
# $1 is the first argument to the function: the specific string to search for
# Ensure the search string is provided
if [[ -z "$1" ]]; then
echo "Usage: find_and_bundle <string>"
return 1
fi
# Use ripgrep to find files containing the specific string
local files_with_string=($(rg --files-with-matches --no-messages --fixed-strings "$1"))
# Check if any files were found
if [[ ${#files_with_string[@]} -eq 0 ]]; then
echo "No files found with string: $1"
return 1
fi
# Combine contents of the files, separated by "---"
for file in $files_with_string; do
cat "$file"
echo "\n---\n"
done | pbcopy # Copy the combined content to the clipboard
}
# convert a pdf to a jpeg for usage in gpt-v
# ChatGPT cannot handle 3p documents
# TODO try to group content into two-page pairs in the future: https://stackoverflow.com/questions/17025515/converting-a-multi-page-pdf-to-multiple-pages-using-a-single-command
convert-pdf-to-jpeg() {
local filepath=$1
local outputpath="${filepath:r}"
# the position of `filepath` matters! Put this before the operators
magick -density 300 "${filepath}" -alpha remove -resize 1024x -quality 100 "${outputpath%.*}-%d.jpeg"
# select the first output
open -R "$outputpath-0.jpeg"
}
# make a gif out of the last recorded video
function makegif() {
# make sure to include trailing slash
# TODO we should be able to determine the default SS directly automatically
screenshot_dir=~/Desktop/
latest_movie=$screenshot_dir`/bin/ls -tp "$screenshot_dir" | grep '.*\.mov' | head -n 1`
gif_destination=`echo "$latest_movie" | sed 's/.mov/.gif/'`
# `brew install ffmpeg gifsicle`
ffmpeg -i "$latest_movie" -r 10 -f gif - | gifsicle > "$gif_destination"
echo $gif_destination
open -a "Google Chrome" "$gif_destination"
}
# httpie funneled through a pager
function httpless {
http --pretty=all --print=hb "$@" | ov
}
# Explore a JSON file using Node.
#
# Usage:
#
# nq <node expression> <file>
# nq <file>
#
# Examples:
#
# # Evaluate a JavaScript expression with `$` substituted for the parsed
# # `data.json`
# nq '$.filter(d => !!d).map(d => d.length)' data.json
#
# # Launch an interactive node REPL with the `$` variable assigned to the
# # parsed `data.json`
# nq 'data.json'
#
nq() {
if [ $# -gt 1 ]; then
node -e "const $ = JSON.parse(require('fs').readFileSync('$2')); console.log($1)"
else
node -i -e "const $ = JSON.parse(require('fs').readFileSync('$1'))"
fi
}
# ripgrep "only": only display the matching text in the first capture group
# this is helpful for selecting and transforming
rgo() {
params=()
# check if the user is passing in `-r`, if not, then default to a basic option
if ((${@[(I)*-r*]} == 0)); then
params+=("-r \$1")
fi
rg $@ $params --no-filename --no-column --no-line-number --color never --only-matching
}
# TODO extract to `.widgets`
# https://github.com/fearphage/dotfiles-1/blob/9fe03f0fe891ab5e38423fb4b9e185526407fb02/.zsh/config/widgets.zsh#L16
# function custom-fzf-execute-widget() {
# if (! hash fzf &>/dev/null) {
# return 1
# }
# local selected=$(
# zle -al \
# # | command grep --extended-regexp --invert-match '(^orig|^\.|^_)' \
# | fzf \
# --tac \
# --nth='2..,..' \
# --tiebreak='index' \
# --prompt=':'
# )
# local stat=$?
# if [[ "$selected" != '' ]] {
# echo $selected
# zle $selected
# }
# return $stat
# }
# password protected pdfs are such a pain, this removes the password protection
decryptpdf() {
echo "Enter password followed by <enter> followed by <ctrl-D>"
qpdf --decrypt --password-file=- --replace-input "${1}"
}
# take a list of images and output a PDF
images_to_pdf() {
# TODO determine best name for the PDF via AI?
magick $@ output.pdf
}
# even with a massive drive, these LLM models + git history can take up a lot of space
inspect-space() {
(cd / && sudo ncdu --exclude '/Volumes/Backups of BiancoBook' --exclude /Library/Developer --exclude /System/ --exclude /Applications --exclude "/Library/Application Support/ArqAgentAPFS.noindex" --confirm-quit)
}
# find and replace across files in the current directory
function find-replace() {
if [ $# -lt 2 ]; then
echo "Usage: find-replace <find_string> <replace_string>"
return 1
fi
local find_string=$1
local replace_string=$2
local files=( $(rg -uu --glob '!.git/**' --glob '!.venv' --glob '!.pnpm' --glob '!node_modules' --glob '!.tox' --glob '!cdk.out' -l --fixed-strings "$find_string") )
echo "${#files[@]} files found."
for file in "${files[@]}"; do
# sd is modern replacement for sed
sd --preview --fixed-strings "$find_string" "$replace_string" "$file"
read "confirmation?Confirm replace in '$file'. [y/n]:"
if [[ $confirmation =~ ^[Yy]$ ]]; then
sd --fixed-strings "$find_string" "$replace_string" "$file"
fi
done
}
###########################
# SSH tunneling
###########################
# usage: find_random_open_port [start_port]
function find_random_open_port() {
local start_port=${1:-1024}
local max_attempts=100
local attempt=0
local port=$start_port
while (( attempt < max_attempts )); do
if ! nc -z localhost $port 2>/dev/null; then
echo $port
return
fi
port=$((port + 1))
attempt=$((attempt + 1))
done
echo "No open port found after $max_attempts attempts, starting from $start_port." > /dev/stderr
return 1
}
# quickly create a tunnel into another host
function ssh-tunnel() {
if [ $# -lt 2 ]; then
echo "Usage: ssh-tunnel remote_host remote_port [local_port]"
echo "This function sets up SSH port forwarding."
return 1
fi
local remote_host=$1
local remote_port=$2
local local_port=${3:-$(find-random-open-port $remote_port)}
if [[ -z $local_port ]]; then
echo "Failed to find an open local port."
return 1
fi
echo "Forwarding local port $local_port to remote port $remote_port on $remote_host..."
set -x
ssh $remote_host -L ${local_port}:localhost:${remote_port}
}
# an entire website to a folder
# https://superuser.com/questions/55040/save-a-single-web-page-with-background-images-with-wget/136335#136335
scrape-website() {
wget -E -H -k -K -p -e robots=off $@
}
###########################
# File opening functions
###########################
# open "yank.tmux:56:109:" at the right line in your terminal
open_in_nano() {
# Read the input string into variables, splitting by ':'
IFS=':' read file line column _other <<< "$1"
# Open the file at the specified line. Nano doesn't support specific column.
nano +$line "$file" < /dev/tty
}
open_in_vscode() {
# git-fuzzy will pass a string that looks like `M bin/run.js` or ` M bin/run.js`
# write a ripgrep command which:
# * ` M bin/run.js` => `bin/run.js`
# * `test/scraper.test.js:25:40` => `test/scraper.test.js:25:40`
# * `test/scraper.test.js` => `test/scraper.test.js`
# * `test/scraper.test.js:25:40: something` => `test/scraper.test.js:25
# assume each of inputs are passed on a single line and are only passed one at a time
local file=$(pcregrep -o2 "(^\s?M\s)?(.*)" <<< "$1")
IFS=':' read file line column _other <<< "$file"
# remove multiple slashes that could have been passed from `file:///` references
file=$(echo "$file" | sed 's|^/{2,}|/|')
code --goto "$file:$line:$column"
}
open_in_cat() {
# TODO jump to specific line number via less
# wrapping doesn't work the way you would think:
# bat Makefile --highlight-line 136 --paging=never --wrap=character --terminal-width=150
# TODO https://github.com/sharkdp/bat/issues/2527
IFS=':' read file line column _other <<< "$1"
# output command executed via local shopt
# setopt local_options xtrace
local height=$(tput lines)
local start=$line
local context=$((height / 2))
bat --color=always $file --highlight-line "$line" --line-range $((start > context ? start - context : 1)):$((start + context))
}
source ~/.node-functions
source ~/.python-functions
source ~/.git-functions