-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.bash-functions.sh
620 lines (550 loc) · 13.5 KB
/
.bash-functions.sh
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
#
# A collection of useful bash functions
#
#
#
# =========================== useful functions ==============================
#
#
#
# --------------------- Scripting --------------------------
#
# Usage: source_if <path>
# If a file is present at <path>, it will be sourced into the current script.
source_if()
{
local path="$1"
if [ -f "$path" ]; then
source "$path"
fi
}
# Usage: doalias <alias> [args]
# executes an alias
doalias()
{
local cmd="$1"
shift
local expanded=$(alias "$cmd" | perl -ne 'if ( m/.*?=.(.*)./ ) { print $1 }')
echo "Expanded alias: $expanded $@"
eval $expanded $@
}
#
# --------------------- env-var manipulations --------------------------
#
# Usage: path_append [variable] <path>
# Appends <path> to the variable [variable],
# (if [variable] is not supplied, defaults to PATH)
path_append()
{
local target="$1"
if [ -z "$2" ]; then
local pathvar=PATH
else
local pathvar=$2
fi
if [ -e "$target" ]; then
if [[ ! $(eval echo \${$pathvar}) == *$target* ]]; then
eval export ${pathvar}=\"\${$pathvar}:$target\"
fi
fi
}
# Usage: path_prepend [variable] <path>
# Prepends <path> to the variable [variable],
# (if [variable] is not supplied, defaults to PATH)
path_prepend()
{
local target="$1"
if [ -z $2 ]; then
local pathvar=PATH
else
local pathvar=$2
fi
if [ -e "$target" ]; then
if [[ ! $(eval echo \${$pathvar}) == *$target* ]]; then
eval export ${pathvar}=$target:\${$pathvar}
fi
fi
}
# Usage: path_set <path> <variable>
# Sets the env variable <variable> to <path>,
# if and only if <path> exists.
#
path_set()
{
thepath="$1"
varname="$2"
# echo "Evaluating: $thepath for $varname"
if [ -e "$thepath" ]; then
# echo "Path found. Setting $varname to $thepath"
eval export ${varname}=${thepath}
fi
# eval echo "$varname is \${$varname}"
}
path_set_if_empty()
{
thepath="$1"
varname="$2"
varvalue=$(eval echo "\$$varname")
if [ -z "$varvalue" ]; then
path_set "$thepath" "$varname"
fi
}
path_print()
{
varname="$1"
echo "${varname}="
eval echo -e \$\{$varname//:/\\\\n\}
}
#
# Sets an env var, by choosing from a key-value list.
# The key-value list is established simply by defining a series of env vars with a common prefix;
# e.g.
# WGEN_DB_key1="value1"
# WGEN_DB_key2="value2"
# ...
#
#
# Usage: choose <var-to-set> <key-prefix> <key> [-q]
#
# e.g. choose DB_OF_MY_DREAMS WGEN_DB_ key2
# will perform:
# export DB_OF_MY_DREAMS="value2"
#
choose()
{
local var_to_set="$1"
local key_prefix="$2"
local key="$3"
local quiet_arg="$4"
if [ ! -z "$quiet_arg" ]; then
if [ "$quiet_arg" = "-q" -o "$quiet_arg" = "--quiet" ]; then
local quiet="YES"
else
local quiet="NO"
fi
else
local quiet="NO"
fi
if [ -z "$key" ]; then # list the possibilities for this variable
echo "Currently,"
echo " ${var_to_set}=$(eval echo \$${var_to_set})"
echo " "
echo "Available values:"
env | perl -ne 'if (m/^'$key_prefix'(\w+)=(.+)/) { printf "%20s: %s\n", $1, $2 }'
else
# get the value for the key given
local value=$(eval echo \$${key_prefix}${key})
if [ -z "$value" ]; then
# We don't seem to have a value for that key
# So we'll just use the key itself as the value
local value="$key"
fi
# set the target variable
eval export ${var_to_set}=\"$value\"
if [ "$quiet" != "YES" ]; then
echo "export ${var_to_set}=\"$(eval echo \$${var_to_set})\""
fi
fi
}
#
# --------------------- filepath manipulations --------------------------
#
function basename()
{
local name="${1##*/}"
echo "${name%$2}"
}
#
# Usage: left_half <separator> <string>
#
# returns the left half of <string>, up to & not including <separator>,
# e.g. left_half . filename.txt returns filename
function left_half()
{
local separator="$1"
local name=${2##*/}
local name0="${name%${separator}*}"
echo "${name0:-$name}"
}
#
# Usage: right_half_with_sep <separator> <string>
#
# returns the right half of <string>, from <separator> forward,
# including <separator>
# e.g. right_half_with_sep . filename.txt returns .txt
#
function right_half_with_sep()
{
local separator="$1"
local name=${2##*/}
local name0="${name%${separator}*}"
local ext=${name0:+${name#$name0}}
echo "${ext:-${separator}}"
}
#
# Usage: right_half <separator> <string>
#
# returns the right half of <string>, from <separator> forward
# (not including <separator>)
# e.g. right_half . filename.txt returns txt
function right_half()
{
local separator="$1"
local name=${2##*/}
local name0="${name%${separator}*}"
local ext=${name0:+${name#$name0}}
local ext=${ext#${separator}}
echo "${ext}"
}
function namename() # get the name without the file extension
{
echo $(left_half . "$1")
}
function ext() # get the file extension, including '.'
{
echo $(right_half_with_sep . "$1")
}
function extonly() # get the file extension, without '.'
{
echo $(right_half . "$1")
}
function dirname()
{
local dir="${1%${1##*/}}"
[ "${dir:=./}" != "/" ] && dir="${dir%?}"
echo "$dir"
}
#
# --------------------- directory navigation --------------------------
#
#
# lf makes a nicely indented listing of directory structure, up
# to the given depth
#
function lf()
{
local depth=2
if [ ! -z $1 ]; then
depth=$1
fi
find . -maxdepth $depth -type d | perl -ne ' $count = @matches = m/\//g; print " " x $count; print'
}
#
# Usage: mycd <path>
#
# Replacement for builtin 'cd', which keeps a separate bash-history
# for every directory.
function mycd()
{
history -w # write current history file
builtin cd "$@" # do actual cd
local HISTDIR="$HOME/.bash_history.d$PWD" # use nested folders for history
if [ ! -d "$HISTDIR" ]; then # create folder if needed
mkdir -p "$HISTDIR"
fi
export HISTFILE="$HISTDIR/${USER}_bash_history.txt" # set new history file
history -c # clear memory
history -r #read from current histfile
# if we're entering a project directory, check for a virtualenv
this_dir=$(basename "$PWD")
parent_dir=$(dirname "$PWD")
if [ ! -z "$PROJECT_HOME" -a "$parent_dir" == "$PROJECT_HOME" ]; then
if [ -z "$WORKINGON" ]; then
if [ -d "$WORKON_HOME/${this_dir}" ]; then
echo "Activating virtualenv $this_dir..."
export WORKINGON="$this_dir"
workon "${this_dir}"
fi
fi
else
unset WORKINGON
fi
}
#
# back: toggle between current and previous directory.
# This is equivalent to: cd -
# It might be nice to implement this as an actual stack.
#
function back()
{
if [ ! -z "$OLDPWD" ]; then
mycd "$OLDPWD"
fi
}
#
# pff: change terminal directory to current Path Finder folder (pff!)
#
function pff()
{
# if under Path Finder, cd to the current PF directory
if [ "$OS" = "Darwin" ]; then
if [ "$LAUNCHING_APP" = "Path Finder" ]; then
# get new path
pf_path=$(osascript "$HOME/software/$PLATFORM/share/scripts/get_path_finder_path.scpt")
if [ ! -z "$pf_path" ]; then
if [ "$pf_path" != "$PWD" ]; then
cd "$pf_path"
fi
fi
fi
fi
}
#
# pf: open specified directory in Path Finder
#
function pf()
{
open -a 'Path Finder' $@
}
#
# pft: change Path Finder window to current Path Finder Terminal
#
function pft()
{
if [ "$OS" = "Darwin" ]; then
if [ "$LAUNCHING_APP" = "Path Finder" ]; then
# get new path as a "folder 'blah' of disk 'foo'" type string
folder_path=`perl -e '$_ = $ENV{PWD};
chomp; @parts = reverse( split(/\//) );
print "folder \""; $folder_str = join("\" of folder \"", @parts);
$folder_str =~ s/folder \"$/disk \"\/\"/;
print $folder_str'`
osascript <<EOS
tell app "Path Finder"
set the window_list to the Finder windows
set front_window to item 1 of window_list
set new_path to $folder_path
set the target of front_window to new_path
end tell
EOS
fi
fi
}
function calc()
{
echo $* | bc
}
#
# ------------------------ Display ---------------------------------
#
# Returns the length, in characters, of the longest of the arguments
function length_of_longest_arg()
{
local max_length=0
for arg in "$@"; do
arg_len=${#arg}
if [ $arg_len -gt $max_length ]; then
max_length=$arg_len
fi
done
echo $max_length
}
#
# Repeats a string the given number of times.
#
# Usage: str_repeat "a" "14"
#
# produces: aaaaaaaaaaaaaa
#
function str_repeat()
{
local str="$1"
local n="$2"
local spaces=$(printf "%*s" $n "")
if [ "$str" = " " ]; then # hack to print spaces. Must be a better way.
echo "$spaces"
else
echo ${spaces// /${str}}
fi
}
#
# Usage: display_boxed [--centered] "line one" "line two" "etc."
#
# Displays the given lines of text in pretty fashion,
# wrapped in a plus-and-pipe box. If --centered is
# passed as the first argument, the lines will be centered
# (otherwise, left-justified). Example:
#
# display_boxed --centered "the quick brown fox" "jumped over" "the very lazy dog"
#
# in unicode:
# ┌─────────────────────┐
# │ the quick brown fox │
# │ jumped over │
# │ the very lazy dog │
# └─────────────────────┘
#
# and in ascii:
# +---------------------+
# | the quick brown fox |
# | jumped over |
# | the very lazy dog |
# +---------------------+
#
#
#
function display_boxed()
{
local top_ascii="+-+"
local mid_ascii="| |"
local bot_ascii="+-+"
local top_unicode="┌─┐"
local mid_unicode="│ │"
local bot_unicode="└─┘"
# choose character set
if [ "$OS" = "Darwin" ]; then
local charset="unicode"
else
local charset="ascii"
fi
local charset_top=$(eval echo \$top_${charset})
local charset_mid=$(eval echo \$mid_${charset})
local charset_bot=$(eval echo \$bot_${charset})
local tl=${charset_top:0:1}
local tc=${charset_top:1:1}
local tr=${charset_top:2:1}
local ml=${charset_mid:0:1}
local mc=${charset_mid:1:1}
local mr=${charset_mid:2:1}
local bl=${charset_bot:0:1}
local bc=${charset_bot:1:1}
local br=${charset_bot:2:1}
local centered=0
if [ "$1" = "--centered" ]; then
centered=1
shift
fi
maxlen=$(length_of_longest_arg "$@")
let innerwidth=maxlen+2
box_top_center=$(str_repeat "$tc" $innerwidth)
box_top="${tl}${box_top_center}${tr}"
box_mid_center=$(str_repeat "$mc" $innerwidth)
box_bot_center=$(str_repeat "$bc" $innerwidth)
box_bot="${bl}${box_bot_center}${br}"
echo "$box_top"
for line in "$@"; do
left_spaces_len=0
if [ $centered -eq 1 ]; then
let left_spaces_len=(maxlen-${#line})/2
fi
let right_spaces_len=maxlen-${#line}-left_spaces_len
leftspaces=${box_mid_center:0:$left_spaces_len}
rightspaces=${box_mid_center:0:$right_spaces_len}
boxed_line="${ml}${mc}${leftspaces}${line}${rightspaces}${mc}${mr}"
echo "$boxed_line"
done
echo "$box_bot"
}
#
# -------------------------- Virtualenv --------------------------
#
function virtualenv_display()
{
local no_control_sequences="$1"
if [ -z "$no_control_sequences" ]; then
local left_color="${TERM_WHITE}"
local main_color="${TERM_GREEN}"
local right_color="${TERM_WHITE}"
fi
local left="["
local right="]"
if [[ "$VIRTUAL_ENV" != "" ]]; then
local venv_name=${VIRTUAL_ENV##*/}
if [[ "$OS" == "Darwin" ]]; then
local python_name="🐍 "
else
local python_name=""
fi
echo "${left_color}${left}${main_color}${python_name}${venv_name}${right_color}${right}"
else
echo ""
fi
}
#
# ----------------------------- Git ---------------------------------
#
function is_git_dir()
{
status_result=$(git status &>/dev/null; echo $?)
if [ $status_result -eq 0 -o $status_result -eq 1 ]; then
echo "true"
else
echo "false"
fi
}
function is_git_dirty()
{
local git_status=$(git diff-index --name-only HEAD 2>/dev/null)
if [ -z "$git_status" ]; then
echo "false"
else
echo "true"
fi
}
function is_git_ahead_of_remote()
{
local is_ahead_result=$(git status 2>/dev/null | grep "Your branch is ahead" &>/dev/null; echo $?)
if [ $is_ahead_result -eq 0 ]; then
echo "true"
else
echo "false"
fi
}
function git_branch_name()
{
local branch_name=$(git status 2>/dev/null | perl -ne 'if (m/On branch (.+)/) { print $1}')
echo $branch_name
}
function git_dirty_display()
{
local no_control_sequences="$1"
local is_dirty=$(is_git_dirty)
local is_ahead=$(is_git_ahead_of_remote)
if [ -z "$no_control_sequences" ]; then
local left_color="${TERM_WHITE}"
local right_color="${TERM_WHITE}"
local dirty_color="${TERM_RED}"
local ahead_color="${TERM_GREEN}"
fi
if [ "$is_dirty" = "true" ]; then
local dirty="* "
if [[ "$OS" == "Darwin" ]]; then
local dirty="✏️ "
fi
else
local dirty=" "
fi
if [ "$is_ahead" = "true" ]; then
local ahead="@ "
if [[ "$OS" == "Darwin" ]]; then
local ahead="💭 "
fi
else
local ahead=" "
fi
local left="["
local right="]"
echo "${left_color}${left}${dirty_color}${dirty}${ahead_color}${ahead}${right_color}${right}"
}
function git_info()
{
local no_control_sequences="$1"
if [ $(is_git_dir) = "true" ]; then
local dirty=$(git_dirty_display $no_control_sequences)
local branch=$(git_branch_name)
if [ ! -z "$no_control_sequences" ]; then
echo "${dirty} ${branch}"
else
echo "${dirty} ${TERM_GREEN}${branch}"
fi
else
echo ""
fi
}
#
# ----------------------------- Web ---------------------------------
#
function wiki()
{
dig +short txt "$*".wp.dg.cx
}