-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.bash
536 lines (469 loc) · 16.4 KB
/
index.bash
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
# Copyright 2021 Timo Tijhof <https://github.com/Krinkle/dotfiles>
# This is free and unencumbered software released into the public domain.
# Overview:
#
# 1. Functions
# 2. Aliases
# 3. Setup
# -------------------------------------------------
# § 1. Functions
# -------------------------------------------------
function _dotfiles-prompt-choice {
read -p "$1 (y/n): > " choice
case "$choice" in
y|Y)
return 0
;;
esac
return 1
}
function _dotfiles-ps1-time {
local text=""
if [[ "$KDF_timer_show" != "0" ]]; then
text="${KDF_timer_show}s "
fi
echo "$text"
}
function _dotfiles-ensure-link {
if [ -z "$2" ]; then
echo "usage: ${FUNCNAME[0]} <link-path> <link-dest>"
return 1
fi
local path="$1"
local dest="$2"
local name="$(basename $dest)"
local backup_dest="$HOME/.dotfiles.backup"
local suffix
# Do nothing if the path is already a link to the same destination.
if [[ ! -L "$path" || "$(readlink $path)" != "$dest" ]]; then
if [ -L "$path" ]; then
# Remove existing link with different destination.
rm "$path"
fi
if [ -e "$path" ]; then
# Create backup of existing non-link (file or directory).
echo "... moving existing $name to ~/.dotfiles.backup"
suffix=".$(date +%Y-%m-%dT%H%I%S).$RANDOM.bak"
mkdir -p "$backup_dest"
mv "$path" "$backup_dest/${name}${suffix}"
fi
echo "... linking $name"
ln -s "$dest" "$path"
fi
}
function _dotfiles-ensure-copy {
if [ -z $2 ]; then
echo "usage: ${FUNCNAME[0]} <src> <dest>"
return 1
fi
local src=$1
local dest=$2
local name="$(basename $src)"
local backup_dest="$HOME/.dotfiles.backup"
local suffix
if [[ -e $dest ]]; then
if [[ -L $dest ]]; then
# Remove link (without backup)
rm "$dest"
else
# Create backup of non-link (file or directory).
echo "... moving existing $name to ~/.dotfiles.backup"
suffix=".$(date +%Y-%m-%dT%H%I%S).$RANDOM.bak"
mkdir -p "$backup_dest"
mv "$dest" "$backup_dest/${name}${suffix}"
fi
fi
echo "... copying $name template"
cp "$src" "$dest"
}
# Default PS1 on macOS: '\h:\W \u\$'
function _dotfiles-ps1-setup {
local ec="$?"
local host="$KDF_PS1_HOST_NAME"
local clr_user="$CLR_CYAN"
local clr_host="$KDF_PS1_HOST_COLOR"
local prompt="\$"
local supportcolor
if [ "$LOGNAME" = "root" ]; then
clr_user="$CLR_RED"
prompt="#"
fi
if [[ $ec != 0 ]]; then
prompt="\[$CLR_RED\]$ec\[$CLR_NONE\] $prompt"
fi
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
supportcolor=1
fi
if [[ -n $supportcolor ]]; then
PS1="\[$CLR_WHITE\][\$(date +%H:%M\ %Z)] \[$clr_user\]\u\[$CLR_WHITE\] at \[$clr_host\]$host\[$CLR_WHITE\] in \[$CLR_YELLOW\]\w\$(_dotfiles-git-ps1)\[$CLR_NONE\]\n\$(_dotfiles-ps1-time)$prompt "
else
PS1="[\$(date +%H:%M\ %Z)] \u@$host:\w$prompt "
fi
}
# Last command run-time measuring
#
# http://jakemccrary.com/blog/2015/05/03/put-the-last-commands-run-time-in-your-bash-prompt/
#
# Installation:
# > trap '_dotfiles-timer-start' DEBUG
# > PROMPT_COMMAND="$PROMPT_COMMAND; _dotfiles-timer-stop"
# > PS1='[${KDF_timer_show}s] [\w]$ "
function _dotfiles-timer-start {
export KDF_timer=${KDF_timer:-$SECONDS}
}
function _dotfiles-timer-stop {
export KDF_timer_show=$(($SECONDS - $KDF_timer))
unset KDF_timer
}
# Git status
#
# Based on the "official" git-completion.bash
# But more simplified and with colors.
#
function _dotfiles-git-ps1 {
local st_staged=0
local st_unstaged=0
local st_untracked=0
local indicator
local branch
CLR_GITST_CLS="$CLR_GREEN" # Clear state
CLR_GITST_SC="$CLR_YELLOW" # Staged changes
CLR_GITST_USC="$CLR_RED" # Unstaged changes
CLR_GITST_UT="$CLR_WHITE" # Untracked files
CLR_GITST_BR="$CLR_GREEN"
if [[ -z "$(git rev-parse --is-inside-work-tree 2> /dev/null)" ]]; then
return 1
fi
if [[ -n "$(git diff-index --cached HEAD 2> /dev/null)" ]]; then
# ls-files has no way to list files that are staged, we have to use the
# significantly slower (for large repos) diff-index command instead
indicator="$indicator${CLR_GITST_SC}+" # Staged changes
fi
if [[ -n "$(git ls-files --modified 2> /dev/null)" ]]; then
indicator="$indicator${CLR_GITST_USC}*" # Unstaged changes
fi
if [[ -n "$(git ls-files --others --exclude-standard 2> /dev/null)" ]]; then
indicator="$indicator${CLR_GITST_UT}%" # Untracked files
fi
branch="`git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'`"
echo -n "${CLR_GITST_BR} ($branch$indicator${CLR_GITST_BR})"
}
function dotfiles-pull {
cd $KDF_BASE_DIR
git fetch origin
# Sanity check before potentially executing arbitrary bash commands
git log HEAD^...origin/main --decorate --abbrev-commit --pretty=oneline --color=auto
git diff HEAD...origin/main --stat --color=auto && git diff HEAD...origin/main --color=auto
if _dotfiles-prompt-choice "OK to pull down now?"; then
git reset --hard origin/main
cd -
else
echo "Dotfiles update aborted."
cd -
return 1
fi
}
function genpass {
if [ -z "$1" ]; then
echo "usage: ${FUNCNAME[0]} <length>"
return 1
fi
pwgen -Bs $1 1 | tee >(pbcopy)
echo "Has been copied to clipboard"
}
function doclonegerrit {
if [ -z "$1" ]; then
echo "usage: ${FUNCNAME[0]} <name>"
return 1
fi
if [ -z $2 ]; then
dest=$(echo "$1" | tr '/' '-')
else
dest="$2"
fi
git clone "https://gerrit.wikimedia.org/r/$1" "$dest"
}
function doaddwmext {
if [ -z "$1" ]; then
echo "usage: ${FUNCNAME[0]} <name>"
return 1
fi
local extDir="$HOME/Development/mediawiki/extensions"
cd "$extDir" && doclonegerrit "mediawiki/extensions/$1" "$1" && cd "$1"
}
function domwextforeach {
local extDir="$HOME/Development/mediawiki/extensions"
cd "$extDir"
for dir in $(ls); do
if [[ "$dir" == "README" ]]; then
continue
fi
echo "Next: $dir"
cd "$dir"
bash -c "$1"
cd "$extDir"
done
}
function doupdatemwext {
domwextforeach 'git checkout master -q && git pull -q'
}
function _globalgitstatus_read {
local treedir
while read gitdir; do
treedir=$(dirname "$gitdir")
cd "$treedir"
# there should generally be only one local branch
# (e.g. 'master', 'production', or 'dev')
# with a few exceptions, such as gh-pages.
branches=$(git branch | grep -vE 'gh-pages|puppet-stage')
branchCount=$(echo "$branches" | wc -l)
stash=$(git stash list)
content=()
if [[ $branchCount -gt 1 ]]; then
content+=("$branches")
fi
if test -n "$stash"; then
content+=("$stash")
fi
content=$(printf '%s\n' "${content[@]}")
if test -n "$content"; then
echo
echo "$(dirname "$treedir")/${CLR_BOLD}$(basename "$treedir")$CLR_NONE"
printf '%s\n' "$content"
fi
done
}
# Find possibly forgotten git stashes and branches.
# Check all .git repositories (upto a certain depth)
# and report any stashes and custom branches.
function do-globalgitstatus {
cwd=$PWD
base="$HOME/Development"
find "$base" -type d -name '.git' -mindepth 1 -maxdepth 6 | _globalgitstatus_read
cd $cwd
}
function vlc-convert-m4a {
if [ -z "$1" ]; then
echo "usage: ${FUNCNAME[0]} <input>"
return 1
fi
vlc="/Applications/VLC.app/Contents/MacOS/VLC"
input="$1"
# swap last extension
output="${input%.*}.m4a"
# strip any quotes
output="${output//\"}"
"$vlc" -I dummy --sout "#transcode{acodec=mp4a,ab=256,channels=2,samplerate=44100}:std{access=file,mux=mp4,dst=\"$output\"}" "$input" "vlc://quit"
}
# Workaround: 'arc patch' doesn't work properly when applying patches
# that upstream Phabricator knows will go into an SVN repo, when the
# local is a Git repo. It will eagerly demand to find the latest SVN
# revision in the local Git repo by scanning every commit in the history
# for the right 'git-svn-id:' text in the commit message, which takes
# forever.
#
# https://secure.phabricator.com/T9044
#
function pullfrom0ad {
if [ -z "$1" ]; then
echo "usage: ${FUNCNAME[0]} <Dnnn>"
return 1
fi
patch="$1"
curl "https://code.wildfiregames.com/{$patch}?download=true" -L 2>/dev/null > /tmp/arc.diff
# Create or overwrite a dedicated branch and quitely reset to latest origin/master.
# This uses 'git checkout -B' instead of 'git branch -f' because the latter doesn't
# work if you're already on the given branch.
git checkout -q -B "arcpatch_$patch" origin/master
# Note, ideally this should be:
# `arc patch --force --nocommit --patch /tmp/arc.diff`
#
# ... because Arcanist is from Phabricator, which is where the patch is downloaded
# from. Unfortunately, arc-diff doesn't understand its own output.
# For new files it uses '--- /dev/null +++ new/file.txt', which arc-diff fails to apply:
# > error: dev/null: does not exist in index
# > Usage Exception: Unable to apply patch!
#
# Work around by using 'git apply' instead, which does understand it.
git apply -p0 --index -v /tmp/arc.diff
git commit -q -m "${patch}"
}
function gigisu {
git lg-prefix "${1:-}" | less
}
[ -z "${PS1:-}" ] && return
# -------------------------------------------------
# § 2. Aliases
# -------------------------------------------------
# Enable 'ls' colors by default.
# For Ubuntu/Debian/Solaris: 'ls --color'
# For macOS (Darwin): 'ls -G', but I install GNU coreutils via Homebrew,
# which means 'ls --color' will work there just as well.
alias ls='ls --color=auto'
alias grep='grep --color=auto'
alias ll='ls -halF'
alias l='ll'
alias lchmod='stat -c "%a %n"'
alias ..='cd ..'
alias ...='cd ../..'
alias fit='fresh-node -- npm install-test'
alias fet='fresh-node -- npm test'
alias dsize='du -hs'
alias _yt-dlp='docker run --rm -v $HOME/dlp:/media tnk4on/yt-dlp --format b -o "/media/%(upload_date>%Y-%m-%d)s %(uploader)s - %(title)s %(id)s.%(ext)s" --no-playlist'
alias yt-basic-dlp='_yt-dlp'
alias yt-dlp='_yt-dlp --embed-subs --embed-metadata --write-description'
alias yt-audio-dlp='_yt-dlp -x'
# https://unix.stackexchange.com/a/81699/37512
# dig @resolver3.opendns.com myip.opendns.com +short # IPv4
# dig @resolver4.opendns.com myip.opendns.com +short # IPv4
# dig @resolver1.ipv6-sandbox.opendns.com AAAA myip.opendns.com +short # IPv6
# dig @ns1-1.akamaitech.net ANY whoami.akamai.net +short # IPv4
# dig @ns1.google.com TXT o-o.myaddr.l.google.com +short # IPv4+IPv6
# dig @ns1.google.com TXT o-o.myaddr.l.google.com +short -4 # IPv4
# dig @ns1.google.com TXT o-o.myaddr.l.google.com +short -6 # IPv6
alias wanip='dig @resolver4.opendns.com myip.opendns.com +short'
alias wanip4='dig @resolver4.opendns.com myip.opendns.com +short -4'
alias wanip6='dig @resolver1.ipv6-sandbox.opendns.com AAAA myip.opendns.com +short -6'
# Version control
alias g='git'
alias gi='git'
alias gir='git'
alias dogitcommit='git commit -F ~/Temp/COMMIT.txt'
alias gogogerrit='git review -R'
alias grabfromgerrit='git review -d'
alias domakejenkinscommit='git remote update origin && git co -b jenkins -t origin/master && touch jenkins.js jenkins.css jenkins.php .jenkins && git add jenkins.js jenkins.css jenkins.php .jenkins && git commit -m "Sample commit for Jenkins"'
alias diff='colordiff'
alias sdi='svn diff | colordiff'
# http://ariejan.net/2011/11/08/fixing-a-slow-starting-terminal-or-iterm2-on-mac-os-x
# https://discussions.apple.com/thread/2178316?start=0&tstart=0
# http://osxdaily.com/2010/05/06/speed-up-a-slow-terminal-by-clearing-log-files/
alias dotruncateasl='sudo rm /var/log/asl/*.asl'
# http://support.apple.com/kb/ht5343
alias doflushdns='sudo killall -HUP mDNSResponder'
# https://snipt.net/Yannick/delete-recursively-a-file-ds_store-thumbsdb-desktopini-etc/
alias dormdsstore='find . -name ".DS_Store" -type f -exec rm {} \;'
alias dormnodedirs='find . -name "node_modules" -type d -print -exec rm -rf {} \; 2>/dev/null'
alias dotfiles-push='cd $KDF_BASE_DIR; git add -p && _dotfiles-prompt-choice "OK to push now?" && git commit -m "update dotfiles" && git push origin HEAD; cd -'
# -------------------------------------------------
# § 3. Setup
# -------------------------------------------------
# Colors
# http://linux.101hacks.com/ps1-examples/prompt-color-using-tput/
CLR_NONE=$(tput sgr0 2>/dev/null || true)
CLR_LINE=$(tput smul 2>/dev/null || true)
CLR_BOLD=$(tput bold 2>/dev/null || true)
CLR_BLACK=$(tput setaf 0 2>/dev/null || true)
CLR_RED=$(tput setaf 1 2>/dev/null || true)
CLR_GREEN=$(tput setaf 2 2>/dev/null || true)
CLR_YELLOW=$(tput setaf 3 2>/dev/null || true)
CLR_BLUE=$(tput setaf 4 2>/dev/null || true)
CLR_MAGENTA=$(tput setaf 5 2>/dev/null || true)
CLR_CYAN=$(tput setaf 6 2>/dev/null || true)
CLR_WHITE=$(tput setaf 7 2>/dev/null || true)
# Meta variables for Krinkle Dotfiles itself
export KDF_BASE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/../.." && pwd )"
export KDF_PS1_HOST_NAME="$( hostname -f 2>/dev/null )"
export KDF_PS1_HOST_COLOR="$CLR_CYAN"
# Bash
#
# Shell configuration
# https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html
shopt -s autocd >/dev/null 2>&1 || true
shopt -s checkwinsize >/dev/null 2>&1 || true
shopt -s globstar >/dev/null 2>&1 || true
shopt -s histappend >/dev/null 2>&1 || true
shopt -s hostcomplete >/dev/null 2>&1 || true
shopt -s interactive_comments >/dev/null 2>&1 || true
shopt -s no_empty_cmd_completion >/dev/null 2>&1 || true
shopt -u mailwarn >/dev/null 2>&1 || true
# Shell history
export HISTCONTROL=ignorespace:erasedups
export HISTSIZE=50000
export HISTFILESIZE=50000
# GnuPG
export GPG_TTY=$(tty)
# MediaWiki
export MW_SERVER='http://localhost:8080'
export MW_SCRIPT_PATH='/w'
export MEDIAWIKI_USER='Admin'
export MEDIAWIKI_PASSWORD='dockerpass'
# Fixes "sort: string comparison failed: Illegal byte sequence"
# Fixes Ruby stuff
#
# NOTE: This depends on the arguably broken way that (some version of)
# Darwin/macOS has these locales configured. It should not be copied to
# my dotfiles for Linux.
export LANG=en_US.UTF-8
export LC_ALL="C"
# Fixes "ArgumentError: invalid byte sequence in US-ASCII" from
# everything Ruby/Jekyll-related.
#
# Yes, this is mutually exclusive with the above, so do this manually
# as-needed. It's only here as reminder.
#
# https://github.com/jekyll/jekyll/issues/960#issuecomment-21311957
# export LC_ALL="en_US.UTF-8"
# Sort dotfiles before "a" in ls(1) and sort(1)
# https://superuser.com/a/448294/164493
export LC_COLLATE="C"
# See also gitconfig/core.pager
# https://serverfault.com/a/414763/180257
export LESSCHARSET=utf-8
export EDITOR=vim
# Homebrew
#
# From `homebrew shellenv`
export HOMEBREW_PREFIX="/opt/homebrew";
export HOMEBREW_CELLAR="$HOMEBREW_PREFIX/Cellar";
export HOMEBREW_REPOSITORY="$HOMEBREW_PREFIX";
export PATH="$HOMEBREW_PREFIX/bin:$HOMEBREW_PREFIX/sbin${PATH+:$PATH}";
export MANPATH="$HOMEBREW_PREFIX/share/man${MANPATH+:$MANPATH}:";
export INFOPATH="$HOMEBREW_PREFIX/share/info:${INFOPATH:-}";
# https://github.com/Homebrew/brew/blob/3.0.9/docs/Analytics.md
export HOMEBREW_NO_ANALYTICS=1
# Don't reinstall the whole world when installing one package
# https://brew.sh/2021/06/21/homebrew-3.2.0/
export HOMEBREW_NO_INSTALL_UPGRADE=1
# Bins
#
# - Homebrw's system overrides
# * gnu-coreutils without 'g' prefix, e.g. realpath
# * new curl
# * new ruby
export PATH="$HOMEBREW_PREFIX/opt/coreutils/libexec/gnubin:$PATH"
export PATH="$HOMEBREW_PREFIX/opt/curl/bin:$PATH"
export PATH="$HOMEBREW_PREFIX/opt/ruby/bin:$PATH"
# - Gems
# https://stackoverflow.com/a/14138490/319266
# Based on "`gem environment gemdir`/bin"
export PATH="$HOMEBREW_PREFIX/lib/ruby/gems/3.2.0/bin:$PATH"
# - Sublime Text (subl)
# https://www.sublimetext.com/docs/command_line.html
export PATH="/Applications/Sublime Text.app/Contents/SharedSupport/bin:$PATH"
# - Homebrew's Git provides diff-highlight
export PATH="$HOMEBREW_PREFIX/opt/git/share/git-core/contrib/diff-highlight:$PATH"
# - Arcanist
# https://secure.phabricator.com/book/phabricator/article/arcanist_quick_start/
export PATH="${PATH}:${HOME}/Development/arcanist/bin"
# - My dotfiles
export PATH="$KDF_BASE_DIR/hosts/primary/bin:$PATH"
# - My Home
export PATH="${HOME}/bin:${PATH}"
# If running interactively, do the below as well (non-interactively, it's not useful and causes issues).
# Except when we're provisioning, as it would fail due to missing files.
if [ -n "${PS1:-}" ] && [ -z "${KDF_INSTALLER:-}" ]; then
# Completion modules from Homebrew-installed packages
. $HOMEBREW_PREFIX/etc/profile.d/bash_completion.sh
# See also "Aliases"
__git_complete g __git_main
__git_complete gi __git_main
__git_complete gir __git_main
# Autojump
. $HOMEBREW_PREFIX/etc/profile.d/autojump.sh
# Bash prompt
PROMPT_COMMAND="_dotfiles-ps1-setup${PROMPT_COMMAND:+; $PROMPT_COMMAND}"
# Measure duration of last command
trap '_dotfiles-timer-start' DEBUG
# This MUST be the very last thing in PROMPT_COMMAND.
PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND;} _dotfiles-timer-stop"
fi