-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdot_prompt
337 lines (306 loc) · 11.3 KB
/
dot_prompt
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
#!/usr/bin/env bash
# @see https://github.com/mathiasbynens/dotfiles/blob/13e29f408fc360360b4468aef2c318dff287c7d2/.bash_prompt#L8-L12
if [[ $COLORTERM = gnome-* && $TERM = xterm ]] && infocmp gnome-256color >/dev/null 2>&1; then
export TERM='gnome-256color';
elif infocmp xterm-256color >/dev/null 2>&1; then
export TERM='xterm-256color';
fi;
bash_minor_version="$(echo "${BASH_VERSION}" | egrep --only-matching "^[[:digit:]]+\.[[:digit:]]")"
# @see https://stromberg.dnsalias.org/~strombrg/PS0-prompt/
if [ "$(echo "${bash_minor_version}" | awk '{ print ($1 >= 4.4) }')" -eq 1 ] ; then
supports_PS0="t"
else
supports_PS0="f"
fi
# @see https://github.com/mathiasbynens/dotfiles/blob/13e29f408fc360360b4468aef2c318dff287c7d2/.bash_prompt#L14-L58
prompt_git() {
local s='';
local branchName='';
# Check if the current directory is in a Git repository.
git rev-parse --is-inside-work-tree &>/dev/null || return;
# Check for what branch we’re on.
# Get the short symbolic ref. If HEAD isn’t a symbolic ref, get a
# tracking remote branch or tag. Otherwise, get the
# short SHA for the latest commit, or give up.
branchName="$(git symbolic-ref --quiet --short HEAD 2> /dev/null || \
git describe --all --exact-match HEAD 2> /dev/null || \
git rev-parse --short HEAD 2> /dev/null || \
echo '(unknown)')";
# Check for uncommitted changes in the index.
if ! $(git diff --quiet --ignore-submodules --cached); then
s+='+';
fi;
# Check for unstaged changes.
if ! $(git diff-files --quiet --ignore-submodules --); then
s+='!';
fi;
# Check for untracked files.
if [ -n "$(git ls-files --others --exclude-standard)" ]; then
s+='?';
fi;
# Check for stashed files.
if $(git rev-parse --verify refs/stash &>/dev/null); then
s+='$';
fi;
[ -n "${s}" ] && s=" [${s}]";
echo -e "${1}${branchName}${2}${s}";
}
# @see https://github.com/mathiasbynens/dotfiles/blob/13e29f408fc360360b4468aef2c318dff287c7d2/.bash_prompt#L60-L88
if tput setaf 1 &> /dev/null; then
tput sgr0; # reset colors
bold=$(tput bold);
reset=$(tput sgr0);
# Solarized colors, taken from http://git.io/solarized-colors.
black=$(tput setaf 0);
blue=$(tput setaf 33);
cyan=$(tput setaf 37);
green=$(tput setaf 64);
orange=$(tput setaf 166);
purple=$(tput setaf 125);
red=$(tput setaf 124);
violet=$(tput setaf 61);
white=$(tput setaf 15);
yellow=$(tput setaf 136);
else
bold='';
reset="\e[00m";
black="\e[1;30m";
blue="\e[1;34m";
cyan="\e[1;36m";
green="\e[1;32m";
orange="\e[1;33m";
purple="\e[1;35m";
red="\e[1;31m";
violet="\e[1;35m";
white="\e[1;37m";
yellow="\e[1;33m";
fi;
# @see https://github.com/mathiasbynens/dotfiles/blob/13e29f408fc360360b4468aef2c318dff287c7d2/.bash_prompt#L90-L102
# Highlight the user name when logged in as root.
if [[ "${EUID}" = "0" || "${USER}" = "root" ]] ; then
userColor="${bold}${red}"
else
userColor="${orange}"
fi
# Detect if this session is connected via SSH. `$SSH_TTY` is the simplest way
# to check, but the variable won't be set inside `sudo su`, even if `SSH_TTY`
# is in the `sudoers` `env_keep`.
is_ssh_connection() {
local is_ssh
is_ssh='f'
if [ -n "${SSH_TTY}" ] ; then
is_ssh='t'
elif [ -n "${SSH_CONNECTION}" ] ; then
is_ssh='t'
# Local machine:
# who am i
# # jordancole ttys007 Aug 25 11
#
# SSH connection to remote machine:
# whoami
# # root pts/0 2020-08-26 23:05 (macbook-air)
elif who am i | egrep --quiet "\(.+\)" ; then
is_ssh='t'
fi
if [[ "${is_ssh}" = 't' ]] ; then
echo 0
else
echo 1
fi
}
if [[ "$(is_ssh_connection)" = "0" ]] ; then
hostColor="${bold}${red}"
connecting_host="$(who am i | egrep --only-matching "\(.+\)" | sed s/^\(// | sed s/\)$//)"
VIA_HOSTNAME=" (via ${connecting_host})"
else
hostColor="${yellow}"
VIA_HOSTNAME=""
fi
if [[ "${LANG}" =~ "UTF-8" ]] ; then
HOST_EMOJI="🟤"
if [[ "$(hostname)" =~ "dev-" ]] ; then
HOST_EMOJI="🟡"
elif [[ "$(hostname)" =~ "preview" ]] ; then
HOST_EMOJI="🟡"
elif [[ "$(hostname)" =~ "staging-" ]] ; then
HOST_EMOJI="🟠"
elif [[ "$(is_ssh_connection)" = "0" ]] ; then
HOST_EMOJI="🔴"
fi
HOST_EMOJI=" ${HOST_EMOJI} "
fi
# @see https://redandblack.io/blog/2020/bash-prompt-with-updating-time/
DIRECTORY="\w"
HOSTNAME="\h"
NEWLINE="\n"
PRINTING_OFF="\["
PRINTING_ON="\]"
PROMPT_COLOUR="${yellow}"
PS1_PROMPT="\$ "
PS2_PROMPT="→ "
RESTORE_CURSOR_POSITION="\e[u"
SAVE_CURSOR_POSITION="\e[s"
TIMESTAMP="\D{%FT%T%z (%Z)}"
TIMESTAMP_PLACEHOLDER="--:--"
USERNAME="\u"
ansi_escape() {
echo "${PRINTING_OFF}${1}${PRINTING_ON}"
}
# This is shared between PS0 and PS1 -- PS0 needs it to correctly reproduce
# PS1's user-input line.
COMMAND_PROMPT_ELEMENTS=(
"${NEWLINE}"
"$(ansi_escape "${white}")" "${PS1_PROMPT}"
"$(ansi_escape "${reset}")"
)
# Return the rows printed in the terminal since the previous command was
# executed -- PS1, PS2, and the command that was executed. PS1 and the command
# can each can span one or more lines, and PS2 is interpolated into the command
# if relevant.
#
# @note This strips out ANSI escape sequences.
lines_from_prompt_and_command() {
# `history 1` prints a command with some additional information: a whitespace-
# padded sequence number for the command's index in the `history`, and (if
# set), the result of passing `$HISTTIMEFORMAT` to `strftime`.
#
# The default `$HISTTIMEFORMAT`, which isn't set, will result in something
# like ` 53 man read`. For a custom format like
# `HISTTIMEFORMAT="[%FT%T%z]%_*"`, `history 1` might return something
# like ` 53 [2020-04-23T13:59:42-0700]*man read`.
local command
# This `sed` attempts to find static characters in `$HISTTIMEFORMAT` by
# stripping out everything prefixed with a `%` (indicating a date-time
# formatting token passed to `strftime`). It will produce an empty string if
# `HISTTIMEFORMAT` isn't set, or ends with a `%` formatting token.
static_histtimeformat="$(echo "${HISTTIMEFORMAT}" | sed -E 's/^.*%[[:alnum:]_]//')"
# If `static_histtimeformat` is a non-empty string, `cut` can easily strip
# out everything prior to the executed command, implicitly also stripping
# out the sequence number.
if [ -n "${static_histtimeformat}" ] ; then
command="$(history 1 | cut -d "${static_histtimeformat}" -f 2-)"
# Otherwise, simply strip out the sequence number.
else
# Using `\s+\d+\s+` as the pattern didn't seem to work, but it does work
# using character classes.
command="$(history 1 | sed -E 's/[[:space:]]+[[:digit:]]+[[:space:]]+//')"
fi
# Evaluate PS1 and PS2 to get an accurate view of how many lines they span.
# The `@P` operator was added in Bash 4.4.
#
# @see https://stackoverflow.com/a/37137981/672403
# @see https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
expanded_PS1="$(printf '%s' "${PS1@P}")"
expanded_PS2="$(printf '%s' "${PS2@P}")"
# If the command spanned multiple lines (due to newlines, not soft-wrapping)
# put `$PS2_PROMPT` at the start of every line beginning with the second
# line, to match how things appear in the shell.
#
# @see https://gist.github.com/JPvRiel/b337dfee8f273aac1332447ed1342304
command_with_ps2="${command/$'\n'/$'\n'${expanded_PS2}}"
all_lines="${expanded_PS1}${command_with_ps2}"
# Strip ANSI escape sequences.
#
# `\x1B` is decimal 27, the escape key (`\e`), so this matches any sequence
# that begins with `\e[` followed by a digit, `;`, or letter.
#
# @see https://stackoverflow.com/a/43627833/672403
sanitized="$(echo "${all_lines}" | sed $'s,\x1B\[[0-9;]*[a-zA-Z],,g')"
echo "${sanitized}"
}
count_lines_after_timestamp_placeholder() {
# It's important to know how many lines `$TIMESTAMP_PLACEHOLDER` was printed
# before the line where the user enters commands, because that's how many
# lines backwards `move_cursor_to_start_of_ps1` will need to move to
# overwrite `$TIMESTAMP_PLACEHOLDER` with `$TIMESTAMP`.
#
# `$TIMESTAMP_PLACEHOLDER` may not be on the first line of PS1. This `perl`
# snippets removes any newlines before `$TIMESTAMP_PLACEHOLDER` to compensate
# for this.
relevant_lines="$(lines_from_prompt_and_command | perl -pe "s/^\s+//")"
# Count the rows consumed by PS1 + command, including lines that are so long
# the terminal soft-wraps them to multiple rows (e.g. if PS1 includes `\w`
# and you're in a deeply-nested directory).
#
# @see https://unix.stackexchange.com/a/275797
total_rows=0
while IFS=$'\n' read -r line ; do
line_length="${#line}"
# Bash arithmetic rounds down; this is a trick to fake rounding up.
#
# @see https://stackoverflow.com/a/2395294/672403
(( line_rows = (line_length + COLUMNS - 1) / COLUMNS ))
(( total_rows += line_rows ))
done <<< "${relevant_lines}"
echo "${total_rows}"
}
# @see https://redandblack.io/blog/2020/bash-prompt-with-updating-time/
move_cursor_to_start_of_ps1() {
if [[ "${supports_PS0}" = "t" ]] ; then
tput cuu "$(count_lines_after_timestamp_placeholder)"
fi
}
# @note PS0 was added in Bash 4.4 (http://stromberg.dnsalias.org/~strombrg/PS0-prompt/).
# macOS ships with Bash 3.x because newer versions are under GPL v3
# (https://www.reddit.com/r/bash/comments/393oqv/why_is_the_version_of_bash_included_in_os_x_so_old/)
# To make PS0 work, you'll need to install a more recent version of Bash
# (https://www.cyberciti.biz/faq/change-default-shell-to-bash-on-macos-catalina/).
PS0_ELEMENTS=(
"${SAVE_CURSOR_POSITION}"
"\$(move_cursor_to_start_of_ps1)"
"${PROMPT_COLOUR}" "${TIMESTAMP}" "${reset}"
"${RESTORE_CURSOR_POSITION}"
"${NEWLINE}"
"$(IFS=; echo "${COMMAND_PROMPT_ELEMENTS[*]}")"
# Push output to the line below the end of PS1 & the user input.
"\$(printf '\n%.0s' {1..count_lines_after_timestamp_placeholder})"
"${NEWLINE}"
)
PS0=$(IFS=; echo "${PS0_ELEMENTS[*]}")
export PS0
if [[ "${supports_PS0}" = "t" ]] ; then
TIMESTAMP_LINE_ELEMENTS=(
"$(ansi_escape "${PROMPT_COLOUR}")" "${TIMESTAMP_PLACEHOLDER}"
"$(ansi_escape "${reset}")"
"${NEWLINE}"
)
TIMESTAMP_LINE=$(IFS=; echo "${TIMESTAMP_LINE_ELEMENTS[*]}")
else
TIMESTAMP_LINE=""
fi
git_branch_prefix=(
"$(ansi_escape "${white}")" "on" "$(ansi_escape "${violet}")"
)
git_status_prefix=(
"$(ansi_escape "${blue}")"
)
PS1_ELEMENTS=(
# visually separate prompt from output of previous command
"${NEWLINE}"
"${TIMESTAMP_LINE}"
"$(ansi_escape "${userColor}")" "${USERNAME}"
"$(ansi_escape "${reset}")"
"$(ansi_escape "${white}")" " at"
# hostname
"$(ansi_escape "${hostColor}")" "${HOST_EMOJI}" "${HOSTNAME}"
"$(ansi_escape "${reset}")"
"$(ansi_escape "${yellow}")" "${VIA_HOSTNAME}"
"$(ansi_escape "${white}")" " in"
"$(ansi_escape "${green}")" " ${DIRECTORY}"
# git branch and status
"\$(prompt_git \"${git_branch_prefix[*]}\" \"${git_status_prefix[*]}\")"
"$(IFS=; echo "${COMMAND_PROMPT_ELEMENTS[*]}")"
)
PS1=$(IFS=; echo "${PS1_ELEMENTS[*]}")
export PS1
PS2_ELEMENTS=(
"$(ansi_escape "${PROMPT_COLOUR}")" "${PS2_PROMPT}"
"$(ansi_escape "${reset}")"
)
PS2=$(IFS=; echo "${PS2_ELEMENTS[*]}")
export PS2
# > [T]his covers a corner case by showing the result of a history substitution
# > command in a subsequent prompt for verification rather than executing it
# > immediately. Without it, history substitution commands like !! and !274
# > cause the time to be written one line too low when the command is run.
shopt -s histverify