-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd-status.plugin.zsh
74 lines (63 loc) · 1.91 KB
/
cmd-status.plugin.zsh
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
# load colors module that allows things like $fg[red]
autoload colors && colors
: ${ZSH_CMD_STATUS_DURATION_THRESHOLD:=10}
function _zsh_cmd_return_code() {
local code=$?
if [[ code -ne 0 ]]; then
printf "${fg_bold[red]}returned ${code}${reset_color}"
fi
}
function _zsh_cmd_render_duration() {
local duration=$1
local sec=$(( duration % 60 ))
local min=$(( duration % 3600 / 60 ))
local hour=$(( duration / 3600 ))
if [[ $hour -gt 0 ]]; then
printf '%dh %dm %ds' $hour $min $sec
elif [[ $min -gt 0 ]]; then
printf '%dm %ds' $min $sec
else
printf '%ds' $sec
fi
}
function _zsh_cmd_duration() {
if [ -z "${_zsh_cmd_status_start_time}" ]; then
return 0
fi
local end_time
end_time="$SECONDS"
local duration=$(( end_time - _zsh_cmd_status_start_time ))
local threshold=${ZSH_CMD_STATUS_DURATION_THRESHOLD:=10}
if [ "$duration" -lt "$threshold" ]; then
return 0
fi
pretty="$(_zsh_cmd_render_duration ${duration})"
printf "${fg_bold[yellow]}took ${pretty}${reset_color}"
}
function _zsh-cmd-status-preexec() {
_zsh_cmd_status_preexec_was_run=true
_zsh_cmd_status_start_time="$SECONDS"
}
function _zsh-cmd-status-precmd() {
# First thing MUST be to get return code
local ret="$(_zsh_cmd_return_code)"
local dur="$(_zsh_cmd_duration)"
# If a command isn't present when enter/return is pressed, preexec functions
# don't execute. If this happens, don't output any stats.
if [[ -z "${_zsh_cmd_status_preexec_was_run}" ]]; then
return 0
fi
# Join the retcode and duration with an ampersand
# If one is unset, no ampersand will be added
# if both are unset, nothing will be added
local out=(${ret} ${dur})
out="${(j: & :)out}"
if [[ -n "${out}" ]]; then
printf "\n${out}\n"
fi
unset _start_time
unset _zsh_cmd_status_preexec_was_run
}
autoload -Uz add-zsh-hook
add-zsh-hook preexec _zsh-cmd-status-preexec
add-zsh-hook precmd _zsh-cmd-status-precmd