forked from alrra/dotfiles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bash_functions
559 lines (429 loc) · 18.2 KB
/
bash_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
#!/usr/bin/env bash
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Simple Calculator.
? () {
local result=""
# ┌─ default (when --mathlib is used) is 20
result="$( printf "scale=10;%s\n" "$*" | bc --mathlib | tr -d "\\\n" )"
# remove the tailing "\" and "\n" ─┘
# (large numbers are printed on multiple lines)
# See https://www.gnu.org/software/bc/manual/html_node/bc_toc.html
if [[ "$result" == *.* ]]; then
# Improve the output for decimal numbers.
printf "%s" "$result" |
sed -e "s/^\./0./" -e "s/^-\./-0./" -e "s/0*$//;s/\.$//"
# | | └─ remove tailing zeros.
# | └─ add "0" for cases like "-.5".
# └─ add "0" for cases like ".5".
else
printf "%s" "$result"
fi
printf "\n"
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Clone a repository and install its dependencies.
clone() {
git clone "$1" \
|| return
cd "$(basename "${1%.*}")" \
|| return
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Check if there are dependencies to be installed.
if [ ! -f "package.json" ]; then
return
fi
# Check if the project uses Yarn.
if [ -f "yarn.lock" ] && command -v "yarn" $> /dev/null; then
printf "\n"
yarn install
return
fi
# If not, assume it uses npm.
if command -v "npm" $> /dev/null; then
printf "\n"
npm install
fi
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Create data URI from a file.
datauri() {
# $1 : file to generate data uri for
local mimeType=""
# -f : True if file exists and is a regular file.
if [ ! -f "$1" ]; then
printf "%s is not a file.\n" "$1"
return
fi
mimeType=$(file --brief --mime-type "$1")
# └─ do not prepend the filename to the output
if [[ $mimeType == text/* ]]; then
mimeType="$mimeType;charset=utf-8"
fi
printf "data:%s;base64,%s" \
"$mimeType" \
"$(openssl base64 -in "$1" | tr -d "\n")"
# │ │ │ └── Delete characters in string argument from string passed in
# │ │ └── translate characters command
# │ └── base64 encode file
# └── convert input text to open ssl format? (technically this isn't actually needed)
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Delete files that match a certain pattern from the current directory.
# This lists the files deleted via the -ls option
delete-files() {
# $1 : file pattern to search for files to delete
local q="${1:-*.DS_Store}"
find . -type f -name "$q" -ls -delete
# | | | | └─── delete found files (or directories)
# │ │ │ └─── list file information
# │ │ └─── pattern of filename to search for
# │ └──── search for files
# └────── current directory to recursively traverse to find files
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Search git repositories from current director and display report with
# remote information.
git-remotes-list() {
echo "*********************************************************************"
echo "$PWD"
echo "*********************************************************************"
find -L . -name .git -type d | while read -r d; do
cd "$d/.." || exit
# Same as: echo "$PWD" | sed -e 's|'"$OLDPWD"'||'
echo "${PWD//$OLDPWD/}"
printf "%s\n" "$(git remote -v | sed -e 's/^\(.*\)$/ \1/')"
cd "$OLDPWD" || exit
done
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Create config for topics folder. This config will be used by other computers
# to sync the repositories.
# Config:
# - 1st column: Topic relative path from parent topics folder
# - 2nd column: git clone url
# - 3rd column: Relative path from parent topics folder to clone topic to
create-topics-config() {
if [[ "$PWD" == *topics ]]
then
rm "$PWD/.topics.config"
find -L . -name .git -type d -mindepth 2 | while read -r d; do
cd "$d/.." || exit
local topicRelativePath="${PWD//$OLDPWD/}"
local topicAbsolutePath="${PWD}"
local topicParentAbsolutePath="$(dirname "$topicAbsolutePath")"
local symlinkRelativeToTopicPath="$(readlink "$topicAbsolutePath")"
local symlinkAbsolutePath="$topicParentAbsolutePath/$symlinkRelativeToTopicPath"
local symlinkRelativeToTopicParentPath="$(relpath "$symlinkAbsolutePath" "$OLDPWD")"
local gitUrl="$(git remote get-url origin)"
local configItem="$topicRelativePath $gitUrl $symlinkRelativeToTopicParentPath"
echo "$configItem"
echo "$configItem" >> "$OLDPWD/.topics.config"
cd "$OLDPWD" || exit
done
else
echo "Please run 'create-topics-config' under 'topics' directory"
fi
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Sync config for topics folder from topics config.
# Config:
# - 1st column: Topic relative path from parent topics folder
# - 2nd column: git clone url
# - 3rd column: Relative path from parent topics folder to clone topic to
sync-topics-config() {
if [[ "$PWD" == *topics ]]
then
local topicsConfig="$PWD/.topics.config"
while read -r name
do
local gitCloneUrl="$(echo "$name" | awk '{ print $2 }')"
local gitDestinationPath="$(echo "$name" | awk '{ print $3 }')"
if [[ -d "$gitDestinationPath" ]]
then
echo "$gitDestinationPath already exists"
else
echo "git clone $gitCloneUrl $gitDestinationPath"
git clone "$gitCloneUrl" "$gitDestinationPath"
fi
done < "$topicsConfig"
else
echo "Please run 'sync-topics-config' under 'topics' directory"
fi
}
# Sync symbolic links for topics folder from topics config.
# Config:
# - 1st column: Topic relative path from parent topics folder
# - 2nd column: git clone url
# - 3rd column: Relative path from parent topics folder to clone topic to
sync-topics-symbolic-links() {
if [[ "$PWD" == *topics ]]
then
local topicsConfig="$PWD/.topics.config"
while read -r name
do
local topicsFolderAndSubFolder="$(echo "$name" | awk '{ print $1 }')"
local topicsSymbolicLinkPath="$(echo "$name" | awk '{ print $3 }')"
if [ "$(readlink "${topicsFolderAndSubFolder:1:${#topicsFolderAndSubFolder}}")" == "../$topicsSymbolicLinkPath" ];
then
echo "$topicsFolderAndSubFolder → ../$topicsSymbolicLinkPath already exists"
else
echo "add-topic $topicsFolderAndSubFolder $topicsSymbolicLinkPath"
fi
done < "$topicsConfig"
else
echo "Please run 'sync-topics-sync-topics-symbolic-links' under 'topics' directory"
fi
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Execute Vim macro
evm() {
local numberOfTimes="${*: -1}"
local files
if [[ "$numberOfTimes" =~ ^[0-9]+$ ]]; then
files=("${@:1:$#-1}")
else
numberOfTimes="1"
files=("$@")
fi
for file in "${files[@]}"; do
printf "* %s\n" "$file"
vim \
-c "norm! $numberOfTimes@q" \
-c "wq" \
"$file"
done
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Get gzip information (gzipped file size + reduction size).
gz() {
# $1 : file to get gzip information from
# declare integers
declare -i gzippedSize=0
declare -i originalSize=0
# -f: True if file exists and is a regular file.
if [ -f "$1" ]; then
# -s : True if file exists and has a size greater than zero.
if [ -s "$1" ]; then
originalSize=$( wc -c < "$1" )
# %12s\n : 12 chars long, convert to string, append \n
# See http://en.cppreference.com/w/cpp/io/c/fprintf
printf "\n original size: %12s\n" "$(hrfs "$originalSize")"
# gzip -c to standard output
gzippedSize=$( gzip -c "$1" | wc -c )
printf " gzipped size: %12s\n" "$(hrfs "$gzippedSize")"
printf " ─────────────────────────────\n"
printf " reduction: %12s [%s%%]\n\n" \
"$( hrfs $((originalSize - gzippedSize)) )" \
"$( printf "%s" "$originalSize $gzippedSize" | \
awk '{ printf "%.1f", 100 - $2 * 100 / $1 }' | \
sed -e "s/0*$//;s/\.$//" )"
# └─ remove tailing zeros
else
printf "\"%s\" is empty.\n" "$1"
fi
else
printf "\"%s\" is not a file.\n" "$1"
fi
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Human readable file size
# (because `du -h` doesn't cut it for me).
hrfs() {
# $1 : number to convert to file size
printf "%s" "$1" |
awk '{
i = 1;
split("B KB MB GB TB PB EB ZB YB WTFB", v);
value = $1;
# confirm that the input is a number
if ( value + .0 == value ) {
while ( value >= 1024 ) {
value/=1024;
i++;
}
if ( value == int(value) ) {
printf "%d %s", value, v[i]
} else {
printf "%.1f %s", value, v[i]
}
}
}' |
sed -e ":l" \
-e "s/\([0-9]\)\([0-9]\{3\}\)/\1,\2/; t l"
# └─ add thousands separator
# (changes "1023.2 KB" to "1,023.2 KB")
# See http://www.grymoire.com/Unix/Sed.html
# -e : combine multiple commands by using -e before each command
# :l : create label
# t l : execute code at label if a pattern match is found
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Return relative path to $1 from $2.
# Example:
# `relpath /foo/bar /foo/baz/foo` return `../../bar`
relpath() {
# http://www.tldp.org/LDP/abs/html/parameter-substitution.html
# $1 : Path we wish to get relative path for
# $2 : Path from which to generate relative path from
python -c "import os.path; print (os.path.relpath('$1','${2:-$PWD}'))" ;
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Adds symbolic link in 'topics' directory with $1 path to $2 optional path or current directory.
# - add-topic topics/subtopics
# - add-topic topics/subtopics path (optional)
# - add-topic topics/subtopics /path (optional)
add-topic() {
# http://www.tldp.org/LDP/abs/html/parameter-substitution.html
# $1 : Path we wish to get relative path for
# $2 : Path from which to generate relative path from
# python -c "import os.path; print (os.path.relpath('$1','${2:-$PWD}'))" ;
local topicsPath="$(z -l topics | head -n 1 | awk '{ print $2 }')"
local destinationSymlink="$topicsPath/$1"
local destinationSymlinkParentDirectory=$(dirname "$destinationSymlink")
local sourceRelativePathFromTopics=$(relpath "${2:-$PWD}" "$destinationSymlinkParentDirectory")
echo "mkdir -p $destinationSymlinkParentDirectory && ln -s $sourceRelativePathFromTopics $destinationSymlink"
mkdir -p "$destinationSymlinkParentDirectory" && ln -s "$sourceRelativePathFromTopics" "$destinationSymlink"
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Create new directories and enter the first one.
mkcd() {
# $* : arguments passed to mkd which is the directories to create
# -n : True if the length of string is nonzero.
if [ -n "$*" ]; then
mkdir -p "$@"
# └─ make parent directories if needed
cd "$@" \
|| exit 1
fi
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Search history.
sh() {
# $* : arguments passed to sh which is the search text
# HISTFILE : https://www.gnu.org/software/bash/manual/html_node/Bash-History-Facilities.html
#
# ┌─ Enable colors for pipe.
# │ ("--color=auto" enables colors only
# │ if the output is in the terminal.)
grep --color=always "$*" "$HISTFILE" \
| less --no-init --raw-control-chars
# │ └─ Display ANSI color escape sequences in raw form.
# └─ Don't clear the screen after quitting less.
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Search for text recursively within the current directory.
st() {
# $* : arguments passed to st which is the search text
grep --color=always "$*" \
--exclude-dir=".git" \
--exclude-dir="node_modules" \
--ignore-case \
--recursive \
. \
| less --no-init --raw-control-chars
# │ └─ Display ANSI color escape sequences in raw form.
# └─ Don't clear the screen after quitting less.
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# http://apple.stackexchange.com/questions/139807/what-does-update-terminal-cwd-do-in-the-terminal-of-os-x
# Supposed to be defined in /etc/bashrc but was missing and was being called by tmux-resurrect
update_terminal_cwd() {
# Identify the directory using a "file:" scheme URL,
# including the host name to disambiguate local vs.
# remote connections. Percent-escape spaces.
local SEARCH=' '
local REPLACE='%20'
local PWD_URL="file://$HOSTNAME${PWD//$SEARCH/$REPLACE}"
printf '\e]7;%s\a' "$PWD_URL"
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Upgrade nvm if it is installed.
upgrade-nvm() {
declare -r NVM_DIRECTORY="$HOME/.nvm"
if [ -d "$NVM_DIRECTORY" ]; then # -d : True if file exists and is a directory.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Ensure the latest version of `nvm` is used
execute_without_spinner \
"cd $NVM_DIRECTORY \
&& git fetch --quiet origin \
&& git checkout --quiet \$(git describe --abbrev=0 --tags) \
&& . $NVM_DIRECTORY/nvm.sh \
&& cd -" \
"nvm (upgrade)"
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fi
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Upgrade tpm if it is installed.
upgrade-tpm() {
declare -r TPM_DIR="$HOME/.tmux/plugins/tpm"
if [ -d "$TPM_DIR" ]; then # -d : True if file exists and is a directory.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Ensure the latest version of `tpm` is used
#
# Replace:
# `&& git checkout --quiet master \`
# with:
# `&& git checkout --quiet \$(git describe --abbrev=0 --tags) \`
# when release tags are properly updated/maintained.
execute_without_spinner \
"cd $TPM_DIR \
&& git fetch --quiet origin \
&& git checkout --quiet master \
&& cd -" \
"tpm (upgrade)"
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fi
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Install/update tpm plugins if it is installed.
install-update-tpm-plugins() {
declare -r TPM_DIR="$HOME/.tmux/plugins/tpm"
if [ -d "$TPM_DIR" ]; then # -d : True if file exists and is a directory.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Ensure the latest version of `tpm` is used
execute_without_spinner \
"cd $TPM_DIR \
&& $TPM_DIR/bin/install_plugins \
&& $TPM_DIR/bin/update_plugins all \
&& cd -" \
"tpm plugins (install/update)"
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fi
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Update vim plugins
update-vim-plugins() {
execute_without_spinner \
"vim +PluginsSetup" \
"vim plugins (update)"
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Update global npm modules for all node versions installed via nvm.
# NOTE: To copy global npm packages across different node versions, use:
# `nvm install 8.9.4 --reinstall-packages-from=node`
# Check global packages list via `npm ls -g --depth 0``
update-global-npm-modules-for-all-node-versions() {
# Remember current node version to restore later. Remove 'v' and carriage returns
declare CURRENT_NODE_VERSION=$(node --version | sed "s/[v\r]//g")
# Get all versions of node installed via `nvm`
# Delete any text: '(', Delete any text: 'system', Delete any empty lines, Remove any spaces, 'v', '*', '->'
mapfile -t NODE_VERSIONS < <(nvm list --no-colors | sed -e "s/.*(.*//g" | sed "s/system//g" | sed "s/[[:space:]]//g" | sed "s/[v*>-]//g" | sed "/^\s*$/d")
for i in "${NODE_VERSIONS[@]}"; do
# Switch node versions
echo "${i}"
nvm use "${i}"
sleep 1s
# Get all globally installed modules for current node version
# Delete first line, first 4 characters of each line, Delete line starting with 'npm@', Delete any empty lines
mapfile -t GLOBAL_NPM_MODULES < <(npm ls -g --depth 0 | sed -e "1d" | sed "s/^....//g" | sed "/^npm@/d" | sed "/^\s*$/d")
# [[ "${i}" == "${CURRENT_NODE_VERSION}" ]] && echo '==' || echo '!='
for j in "${GLOBAL_NPM_MODULES[@]}"; do
echo "Updating global npm module: '${j}' for node version: '${i}'"
npm update -g "${j}"
done
done
# Restore to previous version that we set via nvm
nvm use "${CURRENT_NODE_VERSION}"
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -