-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions
More file actions
607 lines (547 loc) · 16.5 KB
/
functions
File metadata and controls
607 lines (547 loc) · 16.5 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
#!/bin/sh
#
# Jeremy Brubaker <jbru362@gmail.com>
# in case atwork is not installed default to being at work
command -v atwork >/dev/null || atwork() { true; }
# Color Escape Functions {{{1
###################################################
# Functions to set colors and attributes
#
# $(FX bold) sets bold attribute
# $(FG 1) sets foreground color to ANSI color 1
# $(BG 1) sets background color to ANSI color 1
# $(FX bold; FG 1) sets foreground color to ANSI
# color 1 and bold in one command
#
# These functions automatically interpret escape
# sequences so you don't need to pass '-e' to echo
#
# Based on P. C. SHyamshankar's spectrum script
# for zsh <github.com/sykora>.
# Changed to use functions instead of hashes for speed
# tput(1) is not used in order to avoid a process
###################################################
FX() { # Set terminal attributes (e.g., bold, italic) {{{2
case "$1" in
reset) printf "[0m" ;;
bold) printf "[1m" ;;
nobold) printf "[22m" ;;
dim) printf "[2m" ;;
nodim) printf "0m" ;; # Unsupported
italic) printf "[3m" ;;
noitalic) printf "[23m" ;;
underline) printf "[4m" ;;
nounderline) printf "[24m" ;;
blink) printf "[5m" ;;
fastblink) printf "[6m" ;;
noblink) printf "[25m" ;;
reverse) printf "[7m" ;;
noreverse) printf "[27m" ;;
hidden) printf "[8m" ;;
nohidden) printf "[28m" ;;
standout) printf "[7m" ;;
nostandout) printf "[27m" ;;
strikeout) printf "[9m" ;;
nostrikeout) printf "[29m" ;;
fancyul) printf "[4:1m" ;;
dblfancyul) printf "[4:2m" ;;
undercurl) printf "[4:3m" ;;
dotfancyul) printf "[4:4m" ;;
dashfancyul) printf "[4:5m" ;;
nofancyul) printf "[4:0m" ;;
*) echo "";
esac
}
# FG(), FGt(), BG(), BGt(): Set foreground and background colors { {{{2
if [ -n "$HAS_COLOR" ]; then
# Expects: color number 0-255
FG() { printf %s "[38;5;$1m"; }
BG() { printf %s "[48;5;$1m"; }
# Expects: 3 values (r g b) of 0-255
FGt() { printf %s "[38;2;$1;$2;$3m"; }
BGt() { printf %s "[48;2;$1;$2;$3m"; }
else # Define as no-op if colors are not available
FG() { :; }
BG() { :; }
FGt() { :; }
BGt() { :; }
fi
# Overload cd and friends {{{1
#
[ -n "$BASH_VERSION" -a -r "$cdlog_path" ] && . "$cdlog_path"
if command -v todo.sh >/dev/null || command -v rpg-cli >/dev/null; then
_cd_overload() {
cmd=$1; shift
oldpwd=$(pwd)
# Run the actual command, saving $?
$cmd "$@"; r=$?
# If the command was successful we may be in a new directory
if [ "$r" = 0 ]; then
# Run overloads only if we are in a new directory
if [ "$r" = 0 -a "$oldpwd" != "$(pwd)" ]; then
if [ "$RPG_CLI_CD_OVERLOAD" = 1 ] && ! atwork 2>/dev/null; then
rpg-cli cd -f .
rpg-cli battle
fi
if [ "$TODOSH_CD_OVERLOAD" = 1 ]; then
todo.sh --local ls
fi
fi
else
# The command failed so return its exit value
# (which is only guaranteed to != 0)
return "$r"
fi
}
# Create aliases to use the overload function
alias cd='_cd_overload "builtin cd"'
alias pushd='_cd_overload "builtin pushd"'
alias popd='_cd_overload "builtin popd"'
# Create additional aliases if cdlog.sh is availabled
if command -v cdlog.chdir >/dev/null; then
alias cd='_cd_overload "cdlog.chdir -P"'
alias pd='_cd_overload "cdlog.pop"'
alias cs='_cd_overload "cdlog.rot"'
alias mcd='_cd_overload "cdlog.mcd"'
alias mcs='_cd_overload "cdlog.mcd -s"'
fi
fi
# Miscellaneous {{{1
pathshow() { # Split a PATH-style variable into multiple lines {{{2
# Split <var> into multiple lines (Default: PATH)
# Usage: pathshow [<var>]
#
# Example: $ pathshow XDG_DATA_DIRS
eval echo "\$${1:-PATH}" | tr : '\n'
}
rmh() { # Remove a host from ~/.ssh/known_hosts {{{2
# Although ssh-keygen -R can be used to remove host entries, that requires
# both adding the port (which I don't feel like remembering) and enclosing
# the host in '[]' (which is too much typing)
#
# Escape '/' so the g/re/cmd doesn't get screwed up
h=$(printf '%s' "$1" | sed 's@/@\\/@g')
printf 'g/^\[\\?%s/d\nw\nq\n' "$h" | ed ~/.ssh/known_hosts >/dev/null
}
http_code () { # Get meaning of HTTP error code {{{2
code=$1
case $code in
'100') echo '100 (continue)';;
'101') echo '101 (switching protocols)';;
'200') echo 'done';;
'201') echo '201 (created)';;
'202') echo '202 (accepted)';;
'203') echo '203 (non-authoritative information)';;
'204') echo '204 (no content)';;
'205') echo '205 (reset content)';;
'206') echo '206 (partial content)';;
'300') echo '300 (multiple choices)';;
'301') echo '301 (moved permanently)';;
'302') echo '302 (found)';;
'303') echo '303 (see other)';;
'304') echo '304 (not modified)';;
'305') echo '305 (use proxy)';;
'306') echo '306 (switch proxy)';;
'307') echo '307 (temporary redirect)';;
'400') echo '400 (bad request)';;
'401') echo '401 (unauthorized)';;
'402') echo '402 (payment required)';;
'403') echo '403 (forbidden)';;
'404') echo '404 (not found)';;
'405') echo '405 (method not allowed)';;
'406') echo '406 (not acceptable)';;
'407') echo '407 (proxy authentication required)';;
'408') echo '408 (request timeout)';;
'409') echo '409 (conflict)';;
'410') echo '410 (gone)';;
'411') echo '411 (length required)';;
'412') echo '412 (precondition failed)';;
'413') echo '413 (request entity too large)';;
'414') echo '414 (request URI too long)';;
'415') echo '415 (unsupported media type)';;
'416') echo '416 (requested range)';;
'417') echo '417 (expectation failed)';;
'418') echo "418 (I'm a teapot)";;
'419') echo '419 (authentication timeout)';;
'420') echo '420 (enhance your calm)';;
'426') echo '426 (upgrade required)';;
'428') echo '428 (precondition required)';;
'429') echo '429 (too many requests)';;
'431') echo '431 (request header fields too large)';;
'451') echo '451 (unavailable for legal reasons)';;
'500') echo '500 (internal server error)';;
'501') echo '501 (not implemented)';;
'502') echo '502 (bad gateway)';;
'503') echo '503 (service unavailable)';;
'504') echo '504 (gateway timeout)';;
'505') echo '505 (HTTP version not supported)';;
'506') echo '506 (variant also negotiates)';;
'510') echo '510 (not extended)';;
'511') echo '511 (network authentication required)';;
*) echo "$code (unknown)"
esac
}
lsp () { # Print numerical permissions at the start of ls -l output {{{2
#
# Inspired by:
# https://github.com/blaenk/dots/blob/master/zsh/zsh/functions.zsh
#
# Globals:
# LS
# LS_OPTS
#
# If ls is supposed to be colored, we have to force it because
# piping the output with --color=auto strips color codes
_opts=$(echo "$LS_OPTS" | sed 's/--color=auto/--color=always/')
# If grc(1) is available, use it and force color through the pipe
unset _grc
command -v grc >/dev/null &&
_grc="grc $GRC_OPTS --colour=on"
# shellcheck disable=SC2086
$_grc "$LS" $_opts -l "$@" | awk '{
mode = gensub("\x1b[^m]*m", "", "g", $1)
k = 0; h = 0;
for (i = 0; i <= 8; i++) {
c = substr(mode, i+2, 1)
k += (c ~ /[rwx]/) * 2^(8-i);
h += (c ~ /[Tt]/) * 1;
h += (c ~ /[Ss]/) * (i == 2 ? 4 : 2);
}
printf("%o%03o %s\n", h, k, $0);
}'
unset _opts _grc
}
# ip() # Add 'get' command to ip(8) {{{2
#
# Remove an ip alias in favor of this function
unalias ip 2>/dev/null
ip () {
#
# https://jip.dev/posts/dots/
#
# 'ip get' prints current ip address and optionally copies to clipboard
# All other commands are passed to the real 'ip' command
#
# Use grc if it is available
if command -v grc >/dev/null; then
ip="grc ip"
else
ip="command ip"
fi
case "$1" in
g | ge | get)
res=$(curl -s ipinfo.io/ip)
case $2 in
c | co | cop | copy)
if command -v xclip >/dev/null; then
printf "%s" "$res" | xclip -in -selection clipboard
printf "copied %s to clipboard\n" "$res" >&2
else
printf "%s\n" "not copied: xclip is not installed" >&2
fi
;;
h | he | hel | help)
cat >&2 <<EOF
Usage: ip get [copy]
Print public IP address to stdout or to the X11 clipboard if [copy] is present
EOF
return
;;
esac
printf "%s\n" "$res"
;;
*) $ip "$@" ;;
esac
}
google () { # Google something (using $WWW_SEARCH as the search engine) {{{2
# Create search string if arguments were passed
if [ $# != 0 ]; then
# Google search strings replace spaces with '+'
IFS='+'
search_string="$*"
unset IFS
url="search?hl=en&lr=&ie=UTF-8&oe=UTF-8&q="
url="$url$search_string&btnG=Google+Search"
fi
# Open URL in browser
# If no arguments were passed it merely opens your search engine
openurl "${WWW_SEARCH:-www.google.com}/$url"
}
rtfm() { # Check various forms of documentation {{{2
if whatis "$1" >/dev/null 2>&1; then
man "$1"
elif [ -f "/usr/share/info/$1.info" ]; then
info "$1"
else
openurl "${WWW_SEARCH:-www.google.com}/?q=%21documentation+for+$1"
fi
}
# hb(), hr(), hbl(): Bold, Reverse-Video and Blinking highlighted search {{{2
#
# Arguments:
# $1: search string
# $2: optional foreground color number
#
# Examples:
# who | hb "$USER" 1
# ps | hr ".*$PPID.*" | hbl ".*$$.*"
####
hb() {
fx="[1m"
_hb_hr_hbl "$1" "$fx" "$2"
}
hr() {
fx="[7m"
_hb_hr_hbl "$1" "$fx" "$2"
}
hbl() {
fx="[5m"
_hb_hr_hbl "$1" "$fx" "$2"
}
_hb_hr_hbl() {
[ "$2" ] && color="[38;5;$3m"
reset="[0m"
sed "s/\($1\)/$2$color\1$reset/gI"
}
lh() { # List last "n" commands in history {{{2
#
# Arguments:
# $1: number of commands to show
#
history | tail -"$1"
}
manf() { # Open manpage for $1 at the first occurence of flag $2 {{{2
#
# https://jip.dev/posts/dots/
#
# Arguments:
# $1: manpage to open
# $2: flag to jump to (omit the first '-')
#
case $MANPAGER in
vimpager) _pager="vimpager -c 'silent! /^\s\+-.*$2/'" ;;
*) _pager="less --pattern '^\s+-.*$2'" ;;
esac
man -P "$_pager" "$1"
}
wiki() { # Interact with wiki {{{2
#
# Inspired by: https://vimwiki.github.io/vimwikiwiki/Tips%20and%20Snips.html
#
# Globals:
# BROWSER
# WIKI_DIR
#
# Arguments:
# $1: edit|git|make|view|help
# $2: arguments needed by $1
#
if [ -z "$WIKI_DIR" ]; then
printf "%s\n" '$WIKI_DIR is not defined'
return 1
fi
case "$1" in
git) shift; git -C "$WIKI_DIR" "$@" ;;
make) shift; (cd "$WIKI_DIR" && make "$@") ;;
view) openurl "$WIKI_DIR/site/index.html" ;;
help) cat <<'END'
Usage: wiki <command> [args ...]
Commands:
edit Edit $WIKI_DIR/content/index.md in $EDITOR
git [args] Pass [args] to git(1) and execute in $WIKI_DIR
make [args] Run make(1) [args] in $WIKI_DIR
view Use $BROWSER to view the local wiki at $WIKI_DIR/site
help View this help
Edit is the default command
Note: $WIKI_DIR must be defined
END
;;
edit | *)
$EDITOR "$WIKI_DIR/content/index.md"
;;
esac
}
sdfmap() { # Print ASCII map location of SDF user {{{2
#
# Arguments:
# $1: user to print
#
curl "http://plewylli.sdf-eu.org/asciimap.cgi?${1:-$(id -un)}"
}
elinks() { # Reuse existing elinks instance {{{2
#
# Based on elinks contrib/TIPS-AND-TRICKS
#
# Arguments:
# $1: URL to open
#
if command elinks -remote "ping()" 2>/dev/null; then
if [ -n "$1" ]; then
command elinks -remote "openURL($1,new-tab)"
else
command elinks -remote "reload()"
fi
else
command elinks "$1"
fi
}
rpmlist() { # List the contents of an RPM {{{2
#
# Arguments:
# $1: RPM to list
#
rpm2cpio "$1" | cpio -t
}
rpmextract() { # Extract the contents of an RPM without installing {{{2
#
# Arguments:
# $1: RPM to extract
#
rpm2cpio "$1" | cpio -idmv
}
# weather() {{{2
#
# Get weather from graph.no {{{2
#
if command -v finger >/dev/null; then
weather() {
#
# Arguments:
# $1: Query. Empty to print help
#
unset lead width
while getopts ':ibw:f1h' c; do
case $c in
i) lead=^ ;;
b) lead=£ ;;
w) width=~$OPTARG ;;
f) lead=¤ ;;
1) lead=o: ;;
h) echo help; return 0 ;;
?) echo "Invalid option: -$OPTARG"; return 1 ;;
esac
done
shift $((OPTIND-1))
OPTIND=1
if [ -z "$1" ]; then
unset lead
unset width
fi
finger "$lead$1$width@graph.no"
}
fi
# ping() # Wrap ping(1) to allow pinging by SSH Host entry {{{2
#
# Remove a ping alias in favor of this function
unalias ping 2>/dev/null
ping() {
# Use grc if it is available
#
# stdbuf is required because if ping gives **no** response, grc will buffer
# everything until ping is killed. This allows the intial line to be
# displayed so you know something is actually happening
if command -v grc >/dev/null && command -v stdbuf >/dev/null; then
ping="grc $GRC_OPTS -c conf.ping stdbuf -oL ping"
else
ping='command ping'
fi
# shellcheck disable=SC2046
$ping $(__gethost "$@")
unset _grc
}
# delve() # rpg-cli directory crawl {{{2
if command -v rpg-cli >/dev/null; then
delve () {
current=$(basename $(pwd))
case $current in
# starting the delve
*[!0123456789]* ) next=dungeon/1 ;;
# now we're delving
[!0]*) next=$((current + 1)) ;;
esac
command mkdir -p "$next" &&
cd "$next" &&
rpg-cli ls
}
fi
# navi {{{1
if command -v navi >/dev/null; then
_navi_call() {
result="$(navi --path ~/share/navi "$@" </dev/tty)"
if [ -z "${result}" ]; then
result="$(navi --path ~/share/navi --print </dev/tty)"
fi
printf "%s" "$result"
}
_navi_widget() {
input="${READLINE_LINE}"
last_command="$(echo "${input}" | navi fn widget::last_command)"
if [ -z "${last_command}" ]; then
output="$(_navi_call --print --fzf-overrides '--no-select-1')"
else
find="$last_command"
replacement="$(_navi_call --print --query "${last_command}")"
output=$(echo "$input" | sed "s/$find/$replacement/")
fi
READLINE_LINE="$output"
READLINE_POINT=${#READLINE_LINE}
}
fi
# Helper Functions {{{1
# (prefix names with '__')
#
__gethost() { # Call gethost with the last argument passed {{{2
#
# This allows wrapping commands to use your SSH config to
# resolve hostname while still being able to pass options
# to them
#
# Example: ping -c10 <host> will call gethost <host> but
# still see the -c10 option
#
options=
host=
i=0
for arg; do
i=$((i+1))
# Passthru all but the last arg
if [ "$i" -lt "$#" ]; then
options="$options $arg"
else
host=$(gethost "$arg")
fi
done
printf '%s %s\n' "$options" "$host"
}
# Bash only functions {{{1
#
if [ -n "$BASH_VERSION" ]; then
# rename_fn {{{2
#
# Rename a function so it can be wrapped by a function with the same name.
# The old name is no longer available after calling this function.
#
# Usage: rename_fn OLD_NAME NEW_NAME
#
# Example:
#
# $ hello() { echo Hello world; }
# $ rename_fn hello hello_orig
# $ hello
# foo: command not found
# $ hello_orig
# Hello world
# $ hello() { echo Hi; hello_orig; }
# $ hello
# Hi
# Hello world
#
# Taken from https://stackoverflow.com/a/34177402
#
rename_fn()
{
local a="$(declare -f "$1")" &&
eval "function $2 ${a#*"()"}" &&
unset -f "$1"
}
fi