-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.shell-common
More file actions
611 lines (538 loc) · 21 KB
/
.shell-common
File metadata and controls
611 lines (538 loc) · 21 KB
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
# 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?
# Don't do anything if not an interactive shell
if [[ $- != *i* ]]; then
return
fi
# 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 sr='sudo -E $SHELL'
alias cdd='cd $HOME/data'
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 ))'
alias dmesg='dmesg -T'
# 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"'
# Weather fun
alias wf='curl --max-time 5 --connect-timeout 3 "wttr.in/Boise?Fud"'
alias ws='curl --max-time 5 --connect-timeout 3 "wttr.in/Boise?Fu&format=%c+%t(+%f)+%p+%h+%w+%m";echo'
alias wg='curl --max-time 5 --connect-timeout 3 "v2n.wttr.in/Boise?Fu"'
# Set some dotfile repo settings
# Export the path, so I can use the dotfiles script can reference other sourced files
export DOTREPO=$HOME/dotfiles
alias cdot='cd $DOTREPO'
alias dot='$DOTREPO/setup.sh'
# Turn on vi mode and set our default editor
set -o vi
export EDITOR; EDITOR=$(command -v nvim >/dev/null 2>&1 && echo nvim || echo vim)
export VISUAL=$EDITOR
alias e='$EDITOR'
alias vi='$EDITOR'
# Set PAGER
export PAGER=less
# Lets make things pretty with bat
# Check which bat binary to use
[ -x "$(command -v batcat)" ] && BATCATBIN=batcat
[ -x "$(command -v bat)" ] && BATCATBIN=bat
if [ -n "$BATCATBIN" ]; then
alias bat="$BATCATBIN --style=rule"
alias b=bat
# Lets make man pages look nice with bat
export MANPAGER="sh -c 'sed -u -e \"s/\\x1B\[[0-9;]*m//g; s/.\\x08//g\" | $BATCATBIN -p -lman --theme ansi --pager \"less -s -M +Gg\"'"
# was going to try less as a simple coloring option but it didnt seem to work for some reason
#export MANPAGER="less -R --use-color -Dd+r -Du+b"
fi
# 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 __refreshSSHvars() {
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 __refreshSSHvars() {
return
}
fi
# insead of using a preexec, I'm just going to run the function when the shell
# starts up here.
__refreshSSHvars
alias sshre='__refreshSSHvars'
# 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 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
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
fi
# Load built in FZF completion and keybinds based on shelltype
eval "$(fzf --"$SHELLTYPE")"
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 with exact matches instead of fuzzy
export FZF_CTRL_R_OPTS='--no-sort --exact'
# 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=$(mktemp)
if [ ! -f "$TMPFILE" ] || [ "$(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; 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 [ -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
# It should support zsh and bash like shells
# Allow user to define ~/.toolrc as a way to quickly setup their own tools
[[ -f ~/.toolrc ]] && source ~/.toolrc
[[ -f ~/.config/toolrc ]] && source ~/.config/toolrc
# Set up a short alias
alias t=tool
tool () {
# Get toolname with bash funcname then fall back to zsh
local TOOLNAME="${FUNCNAME[0]:-$0}"
local YEL='\033[1;33m' NC='\033[0m' UND='\033[4m'
usage() {
local USAGE; USAGE=$(cat <<EOF
${YEL}Usage: $TOOLNAME [list|show|help] [tool_name] <extra_args>${NC}
Commands:
list List all available tools and their descriptions
show [tool_name] Show the function definition of the specified tool
help [tool_name] Show help for the specified tool, not all tools have help
All extra_args are passed directly to the tool in question, they
relate to the underlying command defined in the tool
EOF
)
echo -e "$USAGE"
}
# Print usage if no arguments were passed
[[ -z "$1" ]] && usage && return 1
case "$1" in
list|ls)
# This will display the description by convention. Its kinda horrible but it MUST be the first line in the function and only one line long
echo -e "${YEL}${UND}Available tools:${NC}"
if [[ -n "$ZSH_VERSION" ]]; then
tools=$(typeset -f | grep -E '^__tool_' -A5)
else
tools=$(declare -f | grep -E '^__tool_' -A5)
fi
current_tool=""
echo "$tools" | while IFS= read -r line; do
if [[ "$line" =~ ^__tool_ ]]; then
current_tool=$(echo "$line" | sed -E 's/^__tool_([^( ]*).*/\1/')
elif [[ "$line" =~ DESC= ]]; then
desc=$(echo "$line" | sed -E 's/.*DESC="?([^";]*)"?;?/\1/')
[[ -n "$current_tool" ]] && echo "$current_tool: $desc"
current_tool=""
fi
done| column -t -s:
;;
show)
[[ -n "$ZSH_VERSION" ]] && functions "__tool_$2" || declare -f "__tool_$2"
;;
help|usage)
[[ -z "$2" ]] && usage && return 1
local tool_name="__tool_$2"
shift
$tool_name "$@" TOOLHELP
;;
*)
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
local DESC="Run a puppet apply"
[[ $2 == "TOOLHELP" ]] && { echo -e "${HELP:-$DESC}"; return; }
cd /opt/puppet || exit
__tool-execute "sudo puppet apply manifests $*"
cd - > /dev/null || exit
}
# Puppet disable with prompting and user tagging
__tool_puppet-disable() {
local DESC="Disable puppet executions"
[[ $2 == "TOOLHELP" ]] && { echo -e "${HELP:-$DESC}"; return; }
local USER; 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() {
local DESC="Enable puppet executions"
[[ $2 == "TOOLHELP" ]] && { echo -e "${HELP:-$DESC}"; return; }
__tool-execute "puppet agent --enable"
}
# Do a git pull on the puppet repo using sudo. Only users with sudo will work
# This uses sudo -E so that the users SSH agent keys will be passed through.
__tool_puppet-pull() {
local DESC="Perform a git pull on the puppet repo using sudo"
[[ $2 == "TOOLHELP" ]] && { echo -e "${HELP:-$DESC}"; return; }
cd /opt/puppet || exit
__tool-execute "sudo -E git pull"
cd - > /dev/null || exit
}
# Run docker compose with our compose file and project
__tool_compose() {
local DESC="Run docker compose against our compose file"
local FN="${FUNCNAME[0]:-$0}"
local HELP; HELP=$(cat <<EOF
${YEL}Usage: $TOOLNAME ${FN/__tool_/} [options]${NC}
$DESC
This is simply docker compose. Its just wrapped with the location of our compose file
and the project name. You can use all the standard compose options.
Examples:
$TOOLNAME ${FN/__tool_/} --help
$TOOLNAME ${FN/__tool_/} up -d
$TOOLNAME ${FN/__tool_/} down thetadata-terminal
$TOOLNAME ${FN/__tool_/} ps
$TOOLNAME ${FN/__tool_/} logs thetadata-terminal
EOF
)
[[ $2 == "TOOLHELP" ]] && { echo -e "${HELP:-$DESC}"; return; }
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 $@"
#}
# Simple helper for healthcheck.sh
# Healthcheck.sh is a much more complex script than merits putting as a native tool
__tool_healthcheck() {
local DESC="Alias for healtcheck.sh"
local FN="${FUNCNAME[0]:-$0}"
local HELP; HELP=$(cat <<EOF
${YEL}Usage: $TOOLNAME ${FN/__tool_/} [options]${NC}
$DESC
This is basically here to make it easier to call healthcheck.sh
You can call healthcheck.sh directly if you want as well.
Healthcheck.sh is a much more complex script than merits putting as a native tool
Also note that sometimes its useful to pipe it to more if there are a lot
of error logs at the moment.
EOF
)
[[ $2 == "TOOLHELP" ]] && { echo -e "${HELP:-$DESC}"; return; }
# The actual call to healthcheck.sh
__tool-execute "healthcheck.sh"
}
__tool_logs() {
local DESC="Interact with your dev logs using journalctl"
local FN="${FUNCNAME[0]:-$0}"
local HELP; HELP=$(cat <<EOF
${YEL}Usage: $TOOLNAME ${FN/__tool_/} [options]${NC}
$DESC
Options:
Any valid journalctl options
By default you will get --no-pager and -t trader-$USER
You could add -f to live tail the logs for example
EOF
)
[[ $2 == "TOOLHELP" ]] && { echo -e "${HELP:-$DESC}"; return; }
cmd=$(printf '%q ' journalctl --no-pager -t trader-"$USER" "$@")
__tool-execute "$cmd"
}
__tool_log-search() {
local DESC="Search journalctl logs using fzf"
local FN="${FUNCNAME[0]:-$0}"
# This help info is used when inside the FZF tool
local APP_HELP
APP_HELP=$(cat <<EOF
Use up or down arrow keys to select another line from the search results list
Use 'alt-h' to show this help
Press Enter on a selected line to pretty print the JSON contained in that line
Press Escape to exit the search tool
alt-b to go to the bottom of the search results
alt-t to go to the top of the search results
FZF Filter examples (use without quotes):
Spaces make new search terms. Searches are case insensitive.
You can combine all of these together in any combination.
"Mar\\\ 15" - Search for a specific month and day
"!cron !sshd" - Search for all logs except cron and sshd services
"trader error" - Search for errors on lines with "trader" in them.
"\'fuzzy" - Fuzzy search for the letters f-u-z-y
EOF
)
local HELP; HELP=$(cat <<EOF
${YEL}Usage: $TOOLNAME ${FN/__tool_/} [options]${NC}
$DESC
Options:
Any valid journalctl options
You can use -f to live tail the logs
You can use -n1000 to search the last 1000 lines (the default)
You can use -t<tag> to search a specific tag
You can use -u<unit> to search a specific unit
You can use -p<priority> to use info, warning, error, or crit etc
You can use "--since -2d" to search the last 2 days
${APP_HELP}
EOF
)
[[ $2 == "TOOLHELP" ]] && { echo -e "${HELP:-$DESC}"; return; }
# Set a default search if one is not passed in
# Setting it in an array so it properly handles spaces
local OPTS
if [[ "$*" == "" ]]; then
OPTS=('-n' '1000')
else
OPTS=("$@")
fi
# We are in follow mode
local FOLLOW_MODE FOLLOW_TXT
FOLLOW_MODE=false
if [[ "${OPTS[*]}" == *"-f"* ]]; then
# An indicator if we are in follow mode
FOLLOW_MODE=true
FOLLOW_TXT='- In Follow Mode'
fi
local BASE_CMD
BASE_DEFAULT="journalctl --no-pager"
# Read the default command into an array based on the shell type
if [[ -n ${ZSH_VERSION:-} ]]; then
# Zsh-specific syntax
read -rA BASE_CMD <<< "$BASE_DEFAULT"
else
# Bash syntax
read -ra BASE_CMD <<< "$BASE_DEFAULT"
fi
# Make a temp file so we can use it for the fzf preview
local TMPFILE
TMPFILE=$(mktemp) || { echo "Error: Failed to create temporary file." >&2; return 1; }
# Set up a trap to clean up the temp file. This does not always work so we do one below as well
# shellcheck disable=SC2064 # We want this to expand now
trap "rm $TMPFILE > /dev/null 2>&1" TERM INT EXIT
local FZF_BORDER_LABEL
FZF_BORDER_LABEL="[INPUT: ${BASE_CMD[*]} ${OPTS[*]}] Use 'alt-h' for help"
# Define the FZF options we will execute FZF with
local -a FZF_OPTIONS=(
--no-multi
#--track
--ansi
--exact
#--layout=reverse
--no-sort
--with-nth=2.. # This is important for the preview to work with nl
--preview-window=down:65%:wrap
--preview-label="Relative log entries"
--preview-label-pos=5
# Use OPTS here for display as its the original string
--border-label="$FZF_BORDER_LABEL"
--border-label-pos=5
# When we start up, move the bottom of the dataset, for some reason does not work when in follow mode
--bind "load:last"
--bind "start:last"
# Reset primary UI elements back to initial state. Also allows us to update the clock when we move around.
--bind "focus:change-preview-label(Relative Entries)+transform-border-label(echo \" \$(date '+%b %d %H:%M:%S') ${FOLLOW_TXT} ${FZF_BORDER_LABEL}\")"
--bind "enter:change-preview-label(JSON Preview)+preview(
entry=\$(sed -n \${1}p < \"$TMPFILE\" | cut -f2-)
json_part=\$(echo \"\$entry\" | grep -o '{.*}')
echo 'Use up or down arrow keys to select another line from the search results list.'
echo
if [ -n \"\$json_part\" ]; then
echo 'JSON Preview of selected line:'
echo \"\$json_part\" |jq .| \"$BATCATBIN\" --language=json --style=plain --color=always
else
echo 'No JSON detected in selected line.'
fi
)"
--bind "alt-h:change-preview-label(Help Context)+preview(echo \"${APP_HELP}\")"
--bind "alt-b:last"
--bind "alt-t:first"
# Generate the preview. This reads the selected line number in the search results
# and then displays relative lines from the tempfile using batcat for coloring.
--preview "line=\$(echo {1} | tr -d '[:alpha:]');
start=\$((line - 15));
end=\$((line + 15));
[ \"\$start\" -lt 1 ] && start=1;
sed -n \"\${start},\${end}p\" < \"$TMPFILE\" |cut -f2- | \"$BATCATBIN\" --language=log --style=plain --color=always --highlight-line \$((line - start + 1))
"
)
echo "Command used to gather input: ${BASE_CMD[*]} ${OPTS[*]}"
# Gather input and send it to FZF, but determine if it is using a follow method
# This simply is looking for -f since it is a common follow option, this is likely to not cover all situations
if [[ $FOLLOW_MODE == true ]]; then
echo "Waiting for log input... You might need to CTRL-C to stop the intput stream if it does not exit on it's own"
# Tee to a file while we follow new input for use by the preview window
"${BASE_CMD[@]}" "${OPTS[@]}" | stdbuf -oL nl | tee "$TMPFILE" | fzf "${FZF_OPTIONS[@]}"
else
"${BASE_CMD[@]}" "${OPTS[@]}" | nl > "$TMPFILE"
fzf "${FZF_OPTIONS[@]}" < "$TMPFILE"
fi
# Remove our trap
trap - TERM INT EXIT
# An extra cleanup just to be sure since the trap is not reliable
rm "$TMPFILE" > /dev/null 2>&1
}
# vim: set filetype=sh