-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions
545 lines (462 loc) · 13.7 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
# vim: set filetype=sh :
# Set the terminal emulator's title
title() {
echo -ne "\033]0;"$*"\007"
}
# Simpler ssh tunnels
# tunnel some.host:8080 :9090
# tunnel another.host:5000 local.dev.host:8080
tunnel() {
local remoteHost=${1/:*/}
local remotePort=${1/*:/}
local localHost=${2/:*/}
local localPort=${2/*:/}
localHost=${localHost:-localhost}
echo "Mapping $remoteHost:$remotePort to $localHost:$localPort"
ssh -N -L $localPort:${localHost}:$remotePort $remoteHost
}
current_date() {
date +${1:-%Y-%m-%d}
}
current_time() {
date +${1:-%H:%M:%S}
}
notify() {
local SCRIPT_NAME=$FUNCNAME
local HELP=
read -rd '' HELP << HELP
$SCRIPT_NAME
Put a notification in the notification center
(requires terminal-notifier)
Usage:
$SCRIPT_NAME
-m | --message msg - The message to display in the notification
[-i | --icon name] - The name of the icon to display
(default: Terminal)
[-t | --title title] - The title to display for the notification
(default: Terminal)
[...notifier-args] - Additional arguments for terminal-notifier
HELP
local notifier_args=
local icon=
local title=
local message=
while [ "${1+defined}" ]; do
case $1 in
-h|--help) echo "$HELP" && return 0;;
-i|--icon) icon="$2"; shift;;
-m|--message) message="$2"; shift;;
-t|--title) title="$2"; shift;;
*) notifier_args+="$1 ";;
esac
shift
done
if [ -n "$icon" ]; then
[[ ! "$icon" =~ ^(~|/) ]] && icon=~/Pictures/icons/$icon
[[ ! "$icon" =~ \.png$ ]] && icon=${icon}.png
fi
echo $notifier_args
terminal-notifier -message "$message" ${title:+-title "$title"} ${icon:+-appIcon "$icon"} $notifier_args
}
notify-complete() {
( "${@}" )
local status=$?
if [ $status -eq 0 ]; then
notify --message "Ran ${*}"
else
notify --message "Failed to run ${*}" --title "Exit status: $status"
fi
}
toggle-wifi() {
local SCRIPT_NAME=$FUNCNAME
local HELP=
read -rd '' HELP << HELP
$SCRIPT_NAME
Restart wireless for when things are acting weird
Usage:
$SCRIPT_NAME
[-d | --device device-name:en0] - Device Airport is listening on
[-t | --timeout wait-time:1s] - Time to wait before sending power-on signal again
HELP
local timeout=1s;
local device=en0;
while [ "${1+defined}" ]; do
case $1 in
-h|--help) echo "$HELP" && return 0;;
-t|--timeout) timeout="$2"; shift;;
-d|--device) device="$2"; shift;;
esac
shift
done
networksetup -setairportpower "$device" off;
echo "Waiting for shutdown to complete ...";
sleep $timeout;
echo "Restarting ...";
networksetup -setairportpower "$device" on;
}
# assign variableName command --string here
# echo $variableName
# Via https://stackoverflow.com/a/21636953/135978
assign() {
local var=$1; shift;
local channel=/tmp/assignfifo-${BASH_PID}-${BASH_SUBSHELL}
mkfifo $channel
exec 3<> $channel
"$@" 1>&3
local result=$?
if [[ $result -eq 0 ]];
then read -u3 ${var}
fi
exec 3>&-
rm $channel
return $result
}
# Use clipboard in shell pipelines
# clip | xargs echo # uses pbpaste
# ps -A | grep search | clip # uses pbcopy
clip() {
[ -t 0 ] && pbpaste || pbcopy
}
# Get the absolute path of a file or directory
# Via: https://stackoverflow.com/a/23002317/135978
abspath() {
# $1 : relative filename
if [ -d "$1" ]; then
# dir
(cd "$1"; pwd)
elif [ -f "$1" ]; then
# file
if [[ $1 = /* ]]; then
echo "$1"
elif [[ $1 == */* ]]; then
echo "$(cd "${1%/*}"; pwd)/${1##*/}"
else
echo "$(pwd)/$1"
fi
fi
}
# Bookmark a directory so you can `cd {bookmark-name}` to it from anywhere
bmd() {
local directory=`abspath ${1:-.}`
local bookmark_name=${2:-${directory##*/}}
echo ln -si $directory ${BOOKMARK_DIR:-$CDPATH}/$bookmark_name
ln -si $directory ${BOOKMARK_DIR:-$CDPATH}/$bookmark_name
}
# For those times when you need to wrap `set -e` around just *one* command.
try-or-fail() {
eval "$@"
local status=$?
[ $status -ne 0 ] && echo "Failed to execute $@" && exit $status
}
confirm() {
local msg=${1:-Are you sure}
local choice=
read -r -n 1 -p "$msg [y/N]? " choice
echo
case "$choice" in
y*|Y* ) return 0;;
* ) return 1;;
esac
}
pause() {
local ignored
read -s -r -p "Press any key to continue..." -n 1 ignored
}
quiet() {
&>/dev/null "${@}"
}
error() {
echo >&2 "$@"
}
fail() {
error "$@"
exit 1
}
# `tre` is a shorthand for `tree` with hidden files and color enabled, ignoring
# the `.git` directory, listing directories first. The output gets piped into
# `less` with options to preserve color and line numbers, unless the output is
# small enough for one screen.
# VIA: https://github.com/mathiasbynens/dotfiles/blob/287f38e2196d8367cf2cb33b6f75860dbf17492a/.functions#L240-246
tre() {
tree -aC -I '.git|node_modules|bower_components' --dirsfirst "$@" | less -FRNX;
}
# history with grep
#
# history list
# history <filter> greped history
# Taken from humanism.sh
history() {
if [ $# -eq 0 ]; then
builtin history
# Pass -args to the underlying command
elif [[ "$1" == "-"* ]]; then
builtin history $@
else
builtin history | grep $@
fi
}
# cd without path echo when CDPATH is set
# Taken from https://superuser.com/a/729207
cd() {
if [ -z "$*" ]; then
destination=~
else
destination="$*"
fi
builtin cd -P "${destination}" >/dev/null
}
determine-python-version() {
local venv="$1"
local exec_name=python
local exec_version=
if [[ -L "$venv"/bin/python3 ]]; then
exec_version=3;
elif [[ -L "$venv"/bin/pypy ]]; then
exec_name=pypy
if [[ -L "$venv"/bin/pypy3 ]]; then
exec_version=3;
fi
fi
if [[ $exec_name != pypy && $exec_version != 3 ]]; then
exec_version=2
fi
echo "${exec_name}${exec_version}"
}
virtualenv-restore() {
[[ "$1" = "/" ]] && error "Cannot restore at root" && return 1;
local venv="$1"
local python_version=`determine-python-version "$1"`
gfind "$venv" -type l -xtype l -delete;
virtualenv --python=${python_version} "$venv";
}
# Usage:
# on_exit rm -f /tmp/foo
# on_exit echo "I am exiting"
# tempfile=$(mktemp)
# on_exit rm -f "$tempfile"
# From https://stackoverflow.com/documentation/bash/363/using-trap/2398/accumulate-a-list-of-trap-work-to-run-at-exit
# Based on https://www.linuxjournal.com/content/use-bash-trap-statement-cleanup-temporary-files
_on_exit() {
for cmd in "${on_exit_items[@]}"; do
( eval "$cmd" )
done
}
on_exit() {
[[ "$#" -lt 1 ]] && error "Must provide command to on_exit" && return 1;
local n=${#on_exit_items[*]}
on_exit_items[$n]="$*"
if [[ $n -eq 0 ]]; then
trap _on_exit EXIT
fi
}
# Lazily load NMV when a node binary is invoked (node / npm / globally installed dependencies
# Via https://www.reddit.com/r/node/comments/4tg5jg/lazy_load_nvm_for_faster_shell_start/d5ib9fs
load_nvm() {
. $PACKAGE_MANAGER_PREFIX/opt/nvm/nvm.sh
}
node() {
unset -f node
[ -z "$NVM_BIN" ] && load_nvm
node $@
}
npm() {
unset -f npm
[ -z "$NVM_BIN" ] && load_nvm
npm $@
}
npx() {
unset -f npx
[ -z "$NVM_BIN" ] && load_nvm
npx $@
}
yarn() {
unset -f yarn
[ -z "$NVM_BIN" ] && load_nvm
yarn $@
}
nvm() {
unset -f nvm
[ -z "$NVM_BIN" ] && load_nvm
nvm $@
}
# Turn a URL into a host suitable for ssh / scp
function url-to-host-name {
local SCRIPT_NAME=$FUNCNAME
local HELP=
read -rd '' HELP << HELP
$SCRIPT_NAME
Change anything url-ish into a usable host name
Usage:
$SCRIPT_NAME
url-like - the url of the site,
with or without the protocol, port, or path
Or something vaguely in the form of an IPv4 address
HELP
while [ "${1+defined}" ]; do
case $1 in
-h|--help) echo "$HELP" && return 0;;
*) echo "$1" | sed -E 's#^(.*:https://)?(([^:/]+)|([0-9.]+)).*$#\2#g';;
esac
shift
done
return;
}
update() {
if command -v update_start; then update_start; fi
brew update && brew upgrade
pipx upgrade-all
if [[ "$1" == "--all" ]]; then
sudo softwareupdate --list
fi
if command -v update_local; then update_local; fi
}
cleanup() {
brew cleanup
# Restore python for pipsi
# TODO: Maybe do the same for virtualenvwrapper-managed stuff too.
virtualenv --version >&2 > /dev/null
# Handle cases where python itself upgrades, clearing out virtualenv completely
[[ $? != 0 ]] && pip3 install --force-reinstall virtualenvwrapper
pipx reinstall-all
if command -v cleanup_local; then cleanup_local; fi
}
join-array() {
# Via https://stackoverflow.com/a/23673883
# $1 is return variable name
# $2 is sep
# $3... are the elements to join
local retname=$1 sep=$2 ret=$3
shift 3 || shift $(($#))
printf -v "$retname" "%s" "$ret${@/#/$sep}"
}
# Via https://stackoverflow.com/a/13038235
set_union () {
sort $1 $2 | uniq
}
set_intersection () {
sort $1 $2 | uniq -d
}
set_difference () {
sort $1 $2 $2 | uniq -u
}
set_symmetric_difference() {
sort $1 $2 | uniq -u
}
new-password() {
local SCRIPT_NAME=$FUNCNAME
local HELP=
local size=24
local characters=
local default_punctuation='~!@#$%^&*_+=.|:;,[=-=]'
local default_characters='[:alnum:]'$default_punctuation
local clipboard_cmd=
read -rd '' HELP << HELP
$SCRIPT_NAME
Generate a new password and print it to stdout.
Defaults to producing a password that matches tr's $default_characters
Usage:
$SCRIPT_NAME
[-s | --size password size:${size}] - Size of password to generate
(default: $size)
[--no-clipboard] - Don't copy the new password to the clipboard
Exclusive of --no-stdout
[--no-stdout] - Don't echo the new password to STDOUT
Exclusive of --no-clipboard
Character classes
[-a | --alpha] - Add alphabetic characters to the list of allowed characters
[-s | --ascii] - Add all non-control ASCII characters to the list of allowed characters
(from "!" [33] to "~" [126])
[-c | --characters]* - Allowed characters
[-d | --digits] - Add numeric characters to the list of allowed characters
[-x | --hex] - Add hexidecimal characters to the list of allowed characters
[-n | --alphanumeric] - Add alpha-numeric characters to the list of allowed characters
[-p | --punct] - Add punctuation characters to the list of allowed characters
(limited to common US punctuation)
[-q | --all-punct] - Add all punctuation characters to the list of allowed characters
(will often choose non-US punctuation)
HELP
while [ "${1+defined}" ]; do
case $1 in
-h|--help) echo "$HELP" && return 0;;
-a|--alpha) characters+="[:alpha:]";;
-s|--ascii) characters+="!-~";;
-c|--chars|--characters) characters+="$2"; shift;;
-d|--digits) characters+="[:digit:]";;
-x|--hex) characters+="[:xdigit:]";;
-n|--alphanumeric) characters+="[:alnum:]";;
-p|--punct|--punctuation) characters+="$default_punctuation";;
-q|--all-punct|--all-punctuation) characters+="[:punct:]";;
-s|--size) size="$2"; shift;;
--no-stdout) if [ -z "$clipboard_cmd" ]; then clipboard_cmd=clip; else error "Cannot set --no-clipboard and --no-stdout together"; return 1; fi;;
--no-clip|--no-clipboard) if [ -z "$clipboard_cmd" ]; then clipboard_cmd="xargs -0"; else error "Cannot set --no-clipboard and --no-stdout together"; return 1; fi;;
*) error "$HELP"; error; error Invalid argument "'$1'" provided; return 1;;
esac
shift
done
# TODO: What if output to STDOUT isn't properly encoded
if [[ -z "$clipboard_cmd" ]]; then
# Bash (as of 5.1.8) doesn't properly handle process substitution inside of command substitution
< /dev/urandom gtr -dc "${characters:-$default_characters}" | head -c$size | tee >( clip ) && echo
else
< /dev/urandom gtr -dc "${characters:-$default_characters}" | head -c$size | $clipboard_cmd && echo
fi
}
dequarantine() {
local SCRIPT_NAME=$FUNCNAME
local HELP=
read -rd '' HELP << HELP
$SCRIPT_NAME
Remove the quarantine attribute from a downloaded file
Usage:
$SCRIPT_NAME
/path/to/executable...
HELP
while [ "${1+defined}" ]; do
case $1 in
-h|--help) echo "$HELP" && return 0;;
*) xattr -r -d com.apple.quarantine "$1";;
esac
shift
done
return;
}
alias unquarantine=dequarantine
function ocr-clipboard() {
echo "$(pngpaste - | tesseract stdin stdout)"
}
alias clipboard-ocr=ocr-clipboard
declare -a _command_logging_verbose
export _command_logging_verbose
# Inspired by https://unix.stackexchange.com/a/332639
function _log() {
for cmd in "${_command_logging_verbose[@]}"; do
if [[ "$1" =~ "$cmd" ]]; then
echo "${@}"
fi
done
}
# TODO: Make this work for functions
# Right now log some_function works if you call the function directly
# but does not work if you call it from another function
# or from a sub-shell.
function log() {
if [[ "$1" = "--reset" ]]; then
_command_logging_verbose=()
# Stop tracking commands now
trap - DEBUG
else
_command_logging_verbose+=("${@}")
if [[ ${#} = ${#_command_logging_verbose[@]} ]]; then
# We had no logged commands before, so add the listener now
trap '_log "$BASH_COMMAND"' DEBUG
fi
fi
}
# Override fzf to use the faster fd instead of find
# See https://github.com/junegunn/fzf#settings
_fzf_compgen_path() {
fd --hidden --follow --exclude ".git" . "$1"
}
_fzf_compgen_dir() {
fd --type d --hidden --follow --exclude ".git" . "$1"
}