-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.shell-common
347 lines (307 loc) · 11.7 KB
/
.shell-common
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
# This file should contain common shell setups that are sourced in to each
# rc file. At this time it supports Bash and Zsh. Maybe others?
# Determine our shell type
# if running bash
if [ -n "$BASH_VERSION" ]; then
SHELLTYPE=bash
elif [ -n "$ZSH_VERSION" ]; then
SHELLTYPE=zsh
fi
echo "Configuring as a $SHELLTYPE shell."
# Set up some command aliases
alias cdd='cd $HOME/data'
alias vi='nvim'
# vimwiki
alias vw='vi -c ":VimwikiIndex 1"'
alias vww='vi -c ":VimwikiIndex 2"'
alias ls='ls -F --color=auto'
alias la='ls -a'
alias ll='ls -l'
alias el='eza -gl'
alias lla='ls -la'
alias ela='eza -gla'
alias lha='ls -lha'
alias lt='ls -lt'
alias et='eza -gl -s time -r'
alias ltr='ls -ltr'
alias etr='eza -gl -s time'
alias ..='cd ..'
alias ...='cd ../..'
alias mkdir='mkdir -pv'
alias pa='ps aux | grep'
alias ports="sudo lsof -i -n | egrep 'COMMAND|LISTEN|UDP|TCP'"
alias h='history'
# let diff know the width of my screen
alias diff='diff -W $(( $(tput cols) - 2 ))'
# git aliases
alias gs='git status'
alias gsb='git status -sb'
alias gca='git commit -a -m'
alias gb='git branch'
alias gr='git remote'
alias grpo='git remote prune origin'
alias gp='git pull'
alias gf='git fetch'
alias gd='git diff'
alias gco='git checkout'
alias gu='git push'
alias gwt='git worktree'
alias stash='git stash'
alias glog="git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
# git branch list with date and time
alias gblist="git for-each-ref --sort='-committerdate:iso8601' --format='%(committerdate:iso8601)%09%(refname)' refs/heads"
# Date and time in US timezones
# d or t then pt, mt, ct, et for each timezone and ut for utc
alias dpt='TZ=America/Los_Angeles date'
alias dmt='TZ=America/Denver date'
alias dct='TZ=America/Chicago date'
alias det='TZ=America/New_York date'
alias dut='TZ=UTC date'
# Times are in AM/PM format here
alias tpt='dpt +"%r"'
alias tmt='dmt +"%r"'
alias tct='dct +"%r"'
alias tet='det +"%r"'
alias tut='dut +"%r"'
# Turn on vi mode
set -o vi
export EDITOR=vi
# If in tmux, refresh ssh and display variables. This is cleaner than the
# ssh_reagent function below.
# taken from https://babushk.in/posts/renew-environment-tmux.html
if [ -n "$TMUX" ]; then
function refreshvars() {
sshauth=$(tmux show-environment | grep "^SSH_AUTH_SOCK")
if [ $sshauth ]; then
export $sshauth
fi
display=$(tmux show-environment | grep "^DISPLAY")
if [ $display ]; then
export $display
fi
}
else
function refreshvars() {
return
}
fi
# insead of using a preexec, I'm just going to run the function when the shell
# starts up here.
refreshvars
# Create ssh_reagent command to attached to existing agent sockets
# Leaving this if needed later, Prefer TMUX refreshvars above
ssh_reagent () {
for agent in /tmp/ssh-*/agent.*; do
export SSH_AUTH_SOCK=$agent
if ssh-add -l &>/dev/null; then
echo Found working SSH Agent:
ssh-add -l 2>/dev/null
return
fi
done
echo Cannot find ssh agent - maybe you should reconnect and forward it?
}
alias sshre='ssh_reagent'
# If we have the brew install of the libfido2 library, use it for ssh
# https://github.com/Yubico/libfido2/issues/464 on Sonoma and above Macs
if [ -f /usr/local/lib/libsk-libfido2.dylib ] &> /dev/null; then
export SSH_SK_PROVIDER=/usr/local/lib/libsk-libfido2.dylib
fi
# Load iterm2 shell integration on Macs
test -e "${HOME}/.iterm2_shell_integration.${SHELLTYPE}" && source "${HOME}/.iterm2_shell_integration.${SHELLTYPE}"
# Load up brew environment on ARM systems, do I need this for intel?
if [ -f /opt/homebrew/bin/brew ] &> /dev/null; then
eval "$(/opt/homebrew/bin/brew shellenv)"
fi
# https://starship.rs - a shell augmentation that seems simple
# get dejavumono nerdfont for iterm.
if command -v starship &> /dev/null; then
type starship_zle-keymap-select >/dev/null || \
{
echo "Enabling starship.."
eval "$(starship init $SHELLTYPE)"
}
fi
# Terraform configuration
if command -v terraform &> /dev/null; then
# terraform
alias tf='terraform'
alias tfin='terraform init'
alias tfa='terraform apply'
alias tfv='terraform validate'
alias tfim='terraform import'
# Fancy, color on terminal, no color in txt file, include stderr to txt file. Add summary tags, also copy to clipboard.
alias tfp="terraform plan -out my.plan 2>&1 | tee >(sed -e 's/\x1b\[[0-9;]*m//g' -e '1s~.*~<details><summary>Click for TF Plan</summary>\n~' -e '$s~$~\n</details>~' | tee plan.txt | pbcopy)"
# terraform autocomplete
autoload -U +X bashcompinit && bashcompinit
complete -o nospace -C /opt/homebrew/bin/terraform terraform
fi
######################### Setup FZF ################
# Load FZF integrations for macs or unix
if command -v brew &> /dev/null; then
# Set Brew related FZF elements
BREWPREFIX=$(brew --prefix)
if [[ ! "$PATH" == *${BREWPREFIX}/opt/fzf/bin* ]]; then
PATH="${PATH:+${PATH}:}${BREWPREFIX}/opt/fzf/bin"
fi
# FZF Auto-completion
[[ $- == *i* ]] && source "${BREWPREFIX}/opt/fzf/shell/completion.${SHELLTYPE}" 2> /dev/null
# FZF Key bindings
[[ -f ${BREWPREFIX}/opt/fzf/shell/key-bindings.${SHELLTYPE} ]] && KEYBINDPATH="${BREWPREFIX}/opt/fzf/shell/key-bindings.${SHELLTYPE}"
elif command -v nix &> /dev/null; then
# Nix locations
[[ -f ~/.nix-profile/share/fzf/completion.${SHELLTYPE} ]] && source ~/.nix-profile/share/fzf/completion.${SHELLTYPE}
[[ -f ~/.nix-profile/share/fzf/key-bindings.${SHELLTYPE} ]] && KEYBINDPATH=~/.nix-profile/share/fzf/key-bindings.${SHELLTYPE}
else
# shell completions already installed to system via fzf package
# Debian linux location for fzf bindings per shell type
[[ -f /usr/share/doc/fzf/examples/completion.${SHELLTYPE} ]] && source /usr/share/doc/fzf/examples/completion.${SHELLTYPE}
[[ -f /usr/share/doc/fzf/examples/key-bindings.${SHELLTYPE} ]] && KEYBINDPATH=/usr/share/doc/fzf/examples/key-bindings.${SHELLTYPE}
[[ -f /usr/share/fzf/key-bindings.${SHELLTYPE} ]] && KEYBINDPATH=/usr/share/fzf/key-bindings.${SHELLTYPE}
fi
# Source in the fzf keybindings determined above, may be overkill but it ensures its there.
source $KEYBINDPATH
# Add fzf keybindings to zsh vim plugin
zvm_after_init_commands+=("source $KEYBINDPATH")
export FZF_COMPLETION_TRIGGER=','
export FZF_TMUX_HEIGHT=60% # not strictly TMUX only
export FZF_DEFAULT_OPTS="--layout=reverse --border --info=inline --bind ctrl-h:preview-up,ctrl-l:preview-down"
export FZF_CTRL_T_OPTS="--preview '(highlight -O ansi -l {} 2> /dev/null || cat {} ) 2> /dev/null | head -100'"
# history in chronological order
export FZF_CTRL_R_OPTS='--no-sort'
# Set up an ONA command for looking into ona from CLI.. acts as ping. Cache results for awhile.
alias ona='ping -c5'
_fzf_complete_ona() {
local TMPFILE
TMPFILE=/tmp/fzf-onalist.out
if [ ! -f $TMPFILE -o $(find $TMPFILE -mmin +120 2>/dev/null) ]
then
command curl -ks "https://ona/dcm.php?module=ona_sql&sql=list_all_hosts.sql&header=no"|tail -n +2|awk -F':' '{ print $1; print $3; print $4 }'|sort -u|grep "\S" > $TMPFILE
fi
_fzf_complete +m -- "$@" < <(
command grep -v '^[[:digit:]]' $TMPFILE|sort -V && grep '^[[:digit:]]' $TMPFILE|sort
)
}
_fzf_comprun() {
local command=$1
shift
case "$command" in
cd) fzf "$@" --preview 'tree -C {} | head -100' ;;
export|unset) fzf "$@" --preview "eval 'echo \$'{}" ;;
ssh) fzf "$@" --preview 'host {}' --tac ;;
# ona) fzf "$@" --preview 'HN={}; curl -ks "https://ona/dcm.php?module=host_display&host=${HN}"|tail -n +2' --header-first --header ' ONA search for FQDN, IP or MAC then ping the result.';;
ona) fzf "$@" --preview 'HN={}; curl -ks "https://ona/dcm.php?module=host_display&host=${HN}&format=json"|jq -C .' --header-first --header ' ONA search for FQDN, IP or MAC then ping the result.';;
*) fzf "$@" --preview '(tree -C {} | highlight -O ansi -l {} 2> /dev/null || cat {} ) 2> /dev/null | head -100' ;;
esac
}
################### Setup FZF END ############
########## TMUX window renaming ##############
# Make short hostname only if its not an IP address
__tm_get_hostname(){
local HOST="$(echo $* | rev | cut -d ' ' -f 1 | rev)"
if [[ $HOST =~ "([0-9]{1,3}\.){3}[0-9]{1,3}" ]]; then
echo $HOST # It's an IPv4 addr
else
echo $HOST| cut -d . -f 1-2 # Display first two octets of FQDN as provided
fi
}
__tm_get_current_window(){
tmux list-windows| awk -F : '/\(active\)$/{print $1}'
}
# Rename window according to __tm_get_hostname and then restore it after the command
__tm_command() {
# if [ "$(ps -p $(ps -p $$ -o ppid=) -o comm=| cut -d : -f 1)" = "tmux" ]; then
if [ -n "$TMUX" ]; then
__tm_window=$(__tm_get_current_window)
# Use current window to change back the setting. If not it will be applied to the active window
[ "$SHELLTYPE" = "bash" ] && trap "tmux set-window-option -t $__tm_window automatic-rename on 1>/dev/null" RETURN
[ "$SHELLTYPE" = "zsh" ] && precmd() { tmux set-window-option -t $__tm_window automatic-rename on 1>/dev/null }
tmux rename-window "$(__tm_get_hostname $*)"
fi
command "$@"
}
ssh() {
__tm_command ssh "$@"
}
mosh() {
__tm_command mosh "$@"
}
############ TMUX window renaming END ########
#### Useful shell functions ######
# A good overview of alias/functions/scripts: https://www.baeldung.com/linux/bash-alias-vs-script-vs-new-function
# Tool is a generalized wrapper to manage some common tools
tool () {
case "$1" in
list)
# This will display the description by convention. Its kinda horrible but it MUST be the first line in the function
echo "Available tools:"
functions | grep -A1 "^__tool_" | while read -r line; do
if [[ $line =~ ^__tool_ ]]; then
tool_name=$(echo "$line" | sed -e 's/__tool_\([^ ]*\) (.*/\1/')
elif [[ $line =~ ^DESC= ]]; then
desc=$(echo "$line" | sed -e 's/DESC="\([^"]*\)"/\1/')
echo "$tool_name: $desc"
fi
done| column -t -s:
;;
show)
functions "__tool_$2"
;;
*)
local tool_name="__tool_$1"
shift
$tool_name "$@"
;;
esac
}
# Wrapper function to print out the command being executed so the user has context
# Note that there may be other setup and activities that the calling tool does to make the resulting echoed command functional.
__tool-execute() {
local CMD="$@"
echo "[FUNCTION] Executing: $CMD"
eval "$CMD"
}
# Run a puppet apply
# It will CD to the right place and give the proper default options
# you can pass additional options as needed
__tool_puppet-run() { # Puppet run
DESC="Run a puppet apply"
cd /opt/puppet
__tool-execute "sudo puppet apply manifests $@"
cd - > /dev/null
}
# Puppet disable with prompting and user tagging
__tool_puppet-disable() {
DESC="Disable puppet executions"
local USER=$(who am i | awk '{print $1}')
echo -n "Provide reason for disabling: "
read REPLY
__tool-execute "puppet agent --disable \"$USER: ${REPLY}\""
}
# Simple Puppet enable
__tool_puppet-enable() {
DESC="Enable puppet executions"
__tool-execute "puppet agent --enable"
}
# Run docker compose with our compose file and project
__tool_compose() {
DESC="Run docker compose against our compose file"
if [ ! -f /opt/docker/compose.yaml ]; then
echo "Compose environment not defined on this server."
else
__tool-execute "docker compose -f /opt/docker/compose.yaml -p bedrock $@"
fi
}
# Journalctl tail -f of the users instance
# TODO: Work out journal vs regular log file method here.
#__tool_tail-app-logs() {
# DESC="Tail -f the application logs for the user environment using journalctl"
# __tool-execute "journalctl -f -t trader-$USER $@"
#}
# Generic journalctl wrapper
__tool_logs() {
DESC="Interact with your dev logs using journalctl"
cmd=$(printf '%q ' journalctl --no-pager "$@")
__tool-execute "$cmd"
}
# vim: set filetype=sh