/
functions
301 lines (266 loc) 路 7.54 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
#!/bin/env bash
# Shebang set to make shellcheck happy.
# Utility shell functions.
# vi: foldmarker={,} filetype=sh foldmethod=marker foldlevel=0: tabstop=4 shiftwidth=4:
# source functions.d/ {
# Dynamically source functions from the drop-in directory.
if [ -d "${XDG_CONFIG_HOME:-$HOME/.config}/shell/functions.d" ]; then
for funcfile in "${XDG_CONFIG_HOME:-$HOME/.config}"/shell/functions.d/*.sh; do
source $funcfile
done;
fi
# }
# Check if we have a program in PATH
program_is_in_path() {
local program="$1"
type "$program" >/dev/null 2>&1
}
# Shell detect functions {
export SHELL_PLATFORM=unknown
#ostype() { echo $OSTYPE | tr '[:upper:]' '[:lower:]'; }
ostype() { echo "$OSTYPE"; } # tr is not built-in => expensive. See if this works in practice, to not lowercase.
case "$(ostype)" in
*'linux'* ) SHELL_PLATFORM=linux ;;
*'darwin'* ) SHELL_PLATFORM=macos ;;
*'freebsd'* ) SHELL_PLATFORM=freebsd ;;
*'bsd'* ) SHELL_PLATFORM=bsd ;;
*'msys'* ) SHELL_PLATFORM=windows ;;
esac
shell_is_linux() { [ "$SHELL_PLATFORM" = linux ]; }
shell_is_macos() { [ "$SHELL_PLATFORM" = macos ]; }
shell_is_freebsd() { [ "$SHELL_PLATFORM" = freebsd ]; }
shell_is_bsd() { [ "$SHELL_PLATFORM" = bsd ] || [ "$SHELL_PLATFORM" = freebsd ] || [ "$SHELL_PLATFORM" = macos ]; }
shell_is_windows() { [ "$SHELL_PLATFORM" = windows ]; }
# Test if the shell is interactive.
shell_is_interactive() {
#tty -s >/dev/null 2>/dev/null
case $- in
*i*) return 0;;
*) return 1;;
esac
}
# }
# ps-grep
# List matching processes. Wrap in function instead of alias to avoid bug when searching for name that is also binary found in PATH
psg() {
ps aux | grep "$*"
}
# cd-which
# cd to the directory containing the program found in PATH.
cdw() {
local prog="$1"
if type "$prog" >/dev/null 2>&1; then
dir=$(dirname $(which "$prog"))
echo "$dir"
cd "$dir"
else
echo "\"${prog}\" not found in \$PATH." >&2
fi
}
export cdw >/dev/null
[ -n "$completion_func" ] && shell_is_interactive && $completion_func -cf cdw
# Time conversions.
# Usage: $ epoch2iso8601 1685708111
epoch2iso8601() {
local epoch="$1"
local len=$(echo -n "$epoch" | wc -m)
# Assume that a longer string means we have ms or ns - simply strip down to seconds.
if [ "$len" -gt 10 ]; then
epoch=$(echo $epoch | cut -c 1-10)
fi
if shell_is_linux; then
date -d "@$epoch" +%Y-%m-%dT%H:%M:%S%z
elif shell_is_bsd; then
date -r "$epoch" "+%FT%TZ"
fi
}
export epoch2iso8601 >/dev/null
iso86012epoch() {
local iso="$1"
if shell_is_linux; then
date "$iso" +%s
elif shell_is_bsd; then
date -j -f "%FT%TZ" "$iso" +%s
fi
}
export iso86012epoch >/dev/null
# Git overlay which adds a command to cd to the root of a git repo.
git() {
if [ "$1" = root ]; then
# Try get root from git submodule:
local root="$(command git rev-parse --show-superproject-working-tree)"
# Else we're in the main repo already:
# --show-cdup will not take us to the root if we came here from a symlink.
#test -n "$root" || root="$($gitbin rev-parse --show-cdup)"
# Instead get full path with --show-to-level https://stackoverflow.com/q/39746533/265508
test -n "$root" || root="$(command git rev-parse --show-toplevel)"
[ -n "$root" ] && cd "$root"
else
command git $@
fi
}
# Get path to the best vi(m) to use.
vi_path() {
if program_is_in_path nvim; then
which nvim
else
which vim
fi
}
# Wrapper around the classic 'vi with ack' with search highlighting.
# Usage example: viack -i "search_term
# Last argument is the search string. Preceding arguments are for ack.
viack() {
local search
# Get the last argument. Reference: https://stackoverflow.com/a/1853993/265508
for search; do true; done
vi="$(vi_path)"
"$vi" -p $(ack -l $@) -c 1 +/$search # Go to first line then search downwards.
}
# Wrapper around the classic 'vi with grep'.
vigrep() {
local search
for search; do true; done
vi="$(vi_path)"
$"vi" -p $(grep -Rl $@) -c 1 +/$search
}
# Wrapper around the classic 'rg with grep'.
virg() {
local search
for search; do true; done
vi="$(vi_path)"
"$vi" -p $(rg -l $@) -c 1 +/$search
}
# Wrapper around the classic 'fd with grep'.
vifd() {
vi="$(vi_path)"
"$vi" -p $(fd $@)
}
# Encrypt file with a symmetric cipher.
encryptf() {
local file="$1"
local filecrypt="$1.gpg"
[ -z "$file" ] && echo "No filename given!" >&2 && return
if ! [ -e "$file" ]; then
echo "File '$file' does not exist!" >&2
return
fi
gpg --symmetric --output "$filecrypt" "$file" >/dev/null
[ "$?" -ne 0 ] && echo "Encryption failed!" >&2 && return
rm "$file"
printf "Encrypted %s to %s\n" "$file" "$filecrypt"
# Clear gpg-agent password cache
echo RELOADAGENT | gpg-connect-agent >/dev/null
}
# Decrypt file with a symmetric cipher.
decryptf() {
local filecrypt="$1"
local file=${filecrypt%.gpg}
[ -z "$filecrypt" ] && echo "No filename given!" >&2 && return
if ! [ -e "$filecrypt" ]; then
echo "File '$filecrypt' does not exist!" >&2
return
fi
gpg --decrypt --output "$file" "$filecrypt" 2>/dev/null
[ "$?" -ne 0 ] && echo "Decryption failed!" >&2 && return
rm "$filecrypt"
printf "Decrypted %s to %s\n" "$filecrypt" "$file"
}
# cd in to newly created directory.
function mkdircd() {
local dir="$1"
mkdir -p "$dir"
cd "$dir"
}
alias mkcd=mkdircd
# cd in to newly created directory.
function mkdirtodaycd() {
# BSD date don't have the -I switch like GNU date.
local today=$(date +%Y-%m-%d)
mkdircd "$today"
}
# Connect ssh and start tmux e.g.
# $ sshmux <host>
# Reference: https://stackoverflow.com/a/27614878/265508
sshmux () {
local args="$@"
ssh -t $args "tmux attach || tmux new-session"
}
# Connect mosh and start tmux.
moshmux () {
local args="$@"
mosh $args -- sh -c "tmux attach || tmux new-session"
}
# cd(1) to installation of gem from bundle.
bundlecd() {
local gem="$*"
local path=$(bundle info --path "$gem")
test $? -eq 0 && cd "$path"
}
# cd(1) to installation of go module from bundle.
# Usage: gomodcd github.com/aws/aws-sdk-go
gomodcd() {
local mod="$*"
local path=$(go list -m -f '{{.Dir}}' "$mod")
test $? -eq 0 && cd "$path"
}
# Swap two file's names. Reference: https://stackoverflow.com/a/1119738/265508
swap() {
local TMPFILE=tmp.$$
mv "$1" $TMPFILE
mv "$2" "$1"
mv $TMPFILE "$2"
}
# Sleep random time within an interval.
# Reference: https://serverfault.com/questions/347582/adding-a-random-delay-for-a-linux-command
sleep_random() {
max_sleep_sec="$1"
#perl -e "sleep int(rand(${max_sleep_sec}))"
sleep $((RANDOM % $max_sleep_sec))
}
# Sleep specified time and then shut down
# Usage: sleep_shutdown 3h
# Usage: sleep_shutdown 2d
sleep_shutdown() {
time="$1"
if program_is_in_path gsleep; then
gsleep $time && shutdown -h now
else
sleep $time && shutdown -h now
fi
}
# Search Dash.app.
# Note, can't use name 'dash' as this is the dash shell.
# Usage: dashs "term"
dashs() {
local term="$*"
open "dash://${term}"
}
# Run rails test. Usage:
# t
# t <file> <method>
# t <file1> <file2> <file3> ...
# t <file1> <dir/path1> <dir/path2> ...
# t test/pattern/*
# Assumption: a test method should not have the name of a file/dir that exist...
function t() {
local files=($@)
local method_args=()
if ! [ -e "${files[-1]}" ]; then
method_args=(-n ${files[-1]})
unset 'files[-1]'
fi
echo bin/rails test "${files[@]}" "${method_args[@]}"
bin/rails test "${files[@]}" "${method_args[@]}"
}
# Allow local .clocignore
# Though not supporting to look for .clocignore in a possible path argument.
# Ref: https://stackoverflow.com/a/26679008/265508
function cloc() {
local args="$@"
if [ -e .clocignore ]; then
command cloc --exclude-dir=$(tr '\n' ',' < .clocignore) $args
else
command cloc $args
fi
}