replace TMOUT with zsh/sched and aquired time with zsh/datetime

This commit is contained in:
Alwaysproblem 2022-03-26 20:48:52 +08:00
parent 4c7cb8e455
commit 68aa0d6945

View file

@ -1,60 +1,31 @@
# gdate for macOS function strf_real_time() {
# REF: https://apple.stackexchange.com/questions/135742/time-in-milliseconds-since-epoch-in-the-terminal local time_str;
if [[ "$OSTYPE" == "darwin"* ]]; then local format=${1:='%Y-%m-%d {%u} %H:%M:%S'}
{ strftime -s time_str ${format} $EPOCHSECONDS
gdate # strftime -s time_str "%Y-%m-%d {%u} %H:%M:%S" $EPOCHSECONDS
} || { local time="[${time_str}]";
echo "\n$fg_bold[yellow]passsion.zsh-theme depends on cmd [gdate] to get current time in milliseconds$reset_color" echo -e ${time}
echo "$fg_bold[yellow][gdate] is not installed by default in macOS$reset_color" }
echo "$fg_bold[yellow]to get [gdate] by running:$reset_color"
echo "$fg_bold[green]brew install coreutils;$reset_color";
echo "$fg_bold[yellow]\nREF: https://github.com/ChesterYue/ohmyzsh-theme-passion#macos\n$reset_color"
}
fi
# time # time
function real_time() { function real_time() {
local color="%{$fg_no_bold[cyan]%}"; # color in PROMPT need format in %{XXX%} which is not same with echo local color="%{$fg_no_bold[cyan]%}"; # color in PROMPT need format in %{XXX%} which is not same with echo
local time="[$(date +%H:%M:%S)]"; # local time_str;
local color_reset="%{$reset_color%}"; # strftime -s time_str "%Y-%m-%d {%u} %H:%M:%S" $EPOCHSECONDS
echo "${color}${time}${color_reset}"; # local time="[${time_str}]";
local _time="$(strf_real_time '%H:%M:%S')"
local color_reset="%{$reset_color%}";
echo "${color}${_time}${color_reset}";
} }
# login_info
function login_info() {
local color="%{$fg_no_bold[cyan]%}"; # color in PROMPT need format in %{XXX%} which is not same with echo
local ip
if [[ "$OSTYPE" == "linux-gnu" ]]; then
# Linux
ip="$(ifconfig | grep ^eth1 -A 1 | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' | head -1)";
elif [[ "$OSTYPE" == "darwin"* ]]; then
# macOS
ip="$(ifconfig | grep ^en1 -A 4 | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' | head -1)";
elif [[ "$OSTYPE" == "cygwin" ]]; then
# POSIX compatibility layer and Linux environment emulation for Windows
elif [[ "$OSTYPE" == "msys" ]]; then
# Lightweight shell and GNU utilities compiled for Windows (part of MinGW)
elif [[ "$OSTYPE" == "win32" ]]; then
# I'm not sure this can happen.
elif [[ "$OSTYPE" == "freebsd"* ]]; then
# ...
else
# Unknown.
fi
local color_reset="%{$reset_color%}";
echo "${color}[%n@${ip}]${color_reset}";
}
# directory # directory
function directory() { function directory() {
# local color="%{$fg_no_bold[cyan]%}"; # local color="%{$fg_no_bold[cyan]%}";
local color="$FG[111]"; local color="$FG[111]";
# REF: https://stackoverflow.com/questions/25944006/bash-current-working-directory-with-replacing-path-to-home-folder # REF: https://stackoverflow.com/questions/25944006/bash-current-working-directory-with-replacing-path-to-home-folder
local directory="${PWD/#$HOME/~}"; local directory="${PWD/#$HOME/~}";
local color_reset="%{$reset_color%}"; local color_reset="%{$reset_color%}";
echo "${color}[${directory}]${color_reset}"; echo "${color}[${directory}]${color_reset}";
} }
@ -91,55 +62,40 @@ function vscode_git_status() {
# This cannot use the prompt constants, as they may be empty # This cannot use the prompt constants, as they may be empty
local -A prefix_constant_map local -A prefix_constant_map
prefix_constant_map=( prefix_constant_map=(
'\?\? ' 'UNTRACKED' '\?\? ' 'UNTRACKED'
'[MTARC][ MTD] ' 'STAGED' '[MTARC][ MTD] ' 'STAGED'
'D ' 'STAGED' 'D ' 'STAGED'
' [AMTD] ' 'UNSTAGED' ' [AMTD] ' 'UNSTAGED'
'[MTARC][MTD] ' 'UNSTAGED' '[MTARC][MTD] ' 'UNSTAGED'
'[DAU][DAU] ' 'UNMERGED' '[DAU][DAU] ' 'UNMERGED'
'ahead' 'AHEAD' 'ahead' 'AHEAD'
'behind' 'BEHIND' 'behind' 'BEHIND'
'diverged' 'DIVERGED' 'diverged' 'DIVERGED'
'stashed' 'STASHED' 'stashed' 'STASHED'
) )
# '(?![DAU][DAU])[MTARCD][AMTD ] ' 'STAGED' # exclude the `[DAU][DAU]`
# '(?![DAU][DAU])[MTARCD ][AMTD] ' 'UNSTAGED'
# prefix_constant_map=(
# '\?\? ' 'UNTRACKED'
# '[MTARC][MTD] ' 'STAGEDUNSTAGED'
# '[MTARC] ' 'STAGED'
# 'D ' 'STAGED'
# ' [AMD] ' 'UNSTAGED'
# '[DAU][DAU] ' 'UNMERGED'
# 'ahead' 'AHEAD'
# 'behind' 'BEHIND'
# 'diverged' 'DIVERGED'
# 'stashed' 'STASHED'
# )
# Maps the internal constant to the prompt theme # Maps the internal constant to the prompt theme
local -A constant_prompt_map local -A constant_prompt_map
constant_prompt_map=( constant_prompt_map=(
'UNTRACKED' "$ZSH_THEME_GIT_PROMPT_UNTRACKED" 'UNTRACKED' "$ZSH_THEME_GIT_PROMPT_UNTRACKED"
'ADDED' "$ZSH_THEME_GIT_PROMPT_ADDED" 'ADDED' "$ZSH_THEME_GIT_PROMPT_ADDED"
'MODIFIED' "$ZSH_THEME_GIT_PROMPT_MODIFIED" 'MODIFIED' "$ZSH_THEME_GIT_PROMPT_MODIFIED"
'RENAMED' "$ZSH_THEME_GIT_PROMPT_RENAMED" 'RENAMED' "$ZSH_THEME_GIT_PROMPT_RENAMED"
'DELETED' "$ZSH_THEME_GIT_PROMPT_DELETED" 'DELETED' "$ZSH_THEME_GIT_PROMPT_DELETED"
'UNMERGED' "$ZSH_THEME_GIT_PROMPT_UNMERGED" 'UNMERGED' "$ZSH_THEME_GIT_PROMPT_UNMERGED"
'AHEAD' "$(git_commits_ahead)" 'AHEAD' "$(git_commits_ahead)"
'BEHIND' "$(git_commits_behind)" 'BEHIND' "$(git_commits_behind)"
'DIVERGED' "$ZSH_THEME_GIT_PROMPT_DIVERGED" 'DIVERGED' "$ZSH_THEME_GIT_PROMPT_DIVERGED"
'STASHED' "$ZSH_THEME_GIT_PROMPT_STASHED" 'STASHED' "$ZSH_THEME_GIT_PROMPT_STASHED"
'STAGED' "$ZSH_THEME_GIT_PROMPT_STAGED" 'STAGED' "$ZSH_THEME_GIT_PROMPT_STAGED"
'UNSTAGED' "$ZSH_THEME_GIT_PROMPT_UNSTAGED" 'UNSTAGED' "$ZSH_THEME_GIT_PROMPT_UNSTAGED"
) )
# The order that the prompt displays should be added to the prompt # The order that the prompt displays should be added to the prompt
local status_constants local status_constants
status_constants=( status_constants=(
UNTRACKED ADDED MODIFIED RENAMED DELETED UNTRACKED ADDED MODIFIED RENAMED DELETED
STASHED UNMERGED AHEAD BEHIND DIVERGED STAGED UNSTAGED STASHED UNMERGED AHEAD BEHIND DIVERGED STAGED UNSTAGED
) )
local status_text local status_text
@ -147,14 +103,14 @@ function vscode_git_status() {
# Don't continue on a catastrophic failure # Don't continue on a catastrophic failure
if [[ $? -eq 128 ]]; then if [[ $? -eq 128 ]]; then
return 1 return 1
fi fi
# A lookup table of each git status encountered # A lookup table of each git status encountered
local -A statuses_seen local -A statuses_seen
if __git_prompt_git rev-parse --verify refs/stash &>/dev/null; then if __git_prompt_git rev-parse --verify refs/stash &>/dev/null; then
statuses_seen[STASHED]=1 statuses_seen[STASHED]=1
fi fi
local status_lines local status_lines
@ -162,80 +118,76 @@ function vscode_git_status() {
# If the tracking line exists, get and parse it # If the tracking line exists, get and parse it
if [[ "$status_lines[1]" =~ "^## [^ ]+ \[(.*)\]" ]]; then if [[ "$status_lines[1]" =~ "^## [^ ]+ \[(.*)\]" ]]; then
local branch_statuses local branch_statuses
local match branch_statuses=("${(@s/,/)match}")
local branch_status for branch_status in $branch_statuses; do
branch_statuses=("${(@s/,/)match}") if [[ ! $branch_status =~ "(behind|diverged|ahead) ([0-9]+)?" ]]; then
for branch_status in $branch_statuses; do continue
if [[ ! $branch_status =~ "(behind|diverged|ahead) ([0-9]+)?" ]]; then fi
continue local last_parsed_status=$prefix_constant_map[$match[1]]
fi statuses_seen[$last_parsed_status]=$match[2]
local last_parsed_status=$prefix_constant_map[$match[1]] done
statuses_seen[$last_parsed_status]=$match[2]
done
fi fi
local status_prefix
# For each status prefix, do a regex comparison # For each status prefix, do a regex comparison
for status_prefix in ${(k)prefix_constant_map}; do for status_prefix in ${(k)prefix_constant_map}; do
local status_constant="${prefix_constant_map[$status_prefix]}" local status_constant="${prefix_constant_map[$status_prefix]}"
local status_regex=$'(^|\n)'"$status_prefix" local status_regex=$'(^|\n)'"$status_prefix"
if [[ "$status_text" =~ $status_regex ]]; then if [[ "$status_text" =~ $status_regex ]]; then
statuses_seen[$status_constant]=1 statuses_seen[$status_constant]=1
fi fi
done done
# Display the seen statuses in the order specified # Display the seen statuses in the order specified
local status_prompt local status_prompt
for status_constant in $status_constants; do for status_constant in $status_constants; do
if (( ${+statuses_seen[$status_constant]} )); then if (( ${+statuses_seen[$status_constant]} )); then
local next_display=$constant_prompt_map[$status_constant] local next_display=$constant_prompt_map[$status_constant]
status_prompt="$next_display$status_prompt" status_prompt="$next_display$status_prompt"
fi fi
done done
echo $status_prompt echo $status_prompt
} }
function update_git_status() { function update_git_status() {
if __git_prompt_git rev-parse --git-dir &>/dev/null; then if __git_prompt_git rev-parse --git-dir &>/dev/null; then
GIT_STATUS=$(__git_branch); GIT_STATUS=$(__git_branch);
local git_status="$(vscode_git_status)" local git_status="$(vscode_git_status)"
if [[ $git_status != "" ]]; then if [[ $git_status != "" ]]; then
GIT_STATUS+=" ${git_status}"; GIT_STATUS+=" ${git_status}";
fi fi
GIT_STATUS+=${ZSH_THEME_GIT_PROMPT_END_SUFFIX}; GIT_STATUS+=${ZSH_THEME_GIT_PROMPT_END_SUFFIX};
else else
GIT_STATUS="" GIT_STATUS=""
fi fi
} }
function git_status() { function git_status() {
update_git_status; update_git_status;
echo "${GIT_STATUS}" echo "${GIT_STATUS}"
} }
# command # command
function update_command_status() { function update_command_status() {
local arrow=""; local arrow="";
local color_reset="%{$reset_color%}"; local color_reset="%{$reset_color%}";
local reset_font="%{$fg_no_bold[white]%}"; local reset_font="%{$fg_no_bold[white]%}";
COMMAND_RESULT=$1; COMMAND_RESULT=$1;
export COMMAND_RESULT=$COMMAND_RESULT export COMMAND_RESULT=$COMMAND_RESULT
if $COMMAND_RESULT; if $COMMAND_RESULT;
then then
arrow="%{$fg_bold[red]%}❱%{$fg_bold[yellow]%}❱%{$fg_bold[green]%}❱"; arrow="%{$fg_bold[red]%}❱%{$fg_bold[yellow]%}❱%{$fg_bold[green]%}❱";
else else
arrow="%{$fg_bold[red]%}❱❱❱"; arrow="%{$fg_bold[red]%}❱❱❱";
fi fi
COMMAND_STATUS="${arrow}${reset_font}${color_reset}"; COMMAND_STATUS="${arrow}${reset_font}${color_reset}";
} }
update_command_status true; update_command_status true;
function command_status() { function command_status() {
echo "${COMMAND_STATUS}" echo "${COMMAND_STATUS}"
} }
# settings # settings
@ -245,123 +197,121 @@ typeset +H my_orange="$FG[214]"
# separator dashes size # separator dashes size
function afmagic_dashes { function afmagic_dashes {
local ratio=1 local ratio=1
echo $((COLUMNS * ratio)) echo $((COLUMNS * ratio))
} }
current_time_millis() {
local time_millis;
time_millis=$EPOCHREALTIME
echo $time_millis;
}
# output command execute after # output command execute after
output_command_execute_after() { output_command_execute_after() {
if [ "$COMMAND_TIME_BEIGIN" = "-20200325" ] || [ "$COMMAND_TIME_BEIGIN" = "" ]; if [ "$COMMAND_TIME_BEIGIN" = "-20200325" ] || [ "$COMMAND_TIME_BEIGIN" = "" ];
then then
return 1; return 1;
fi fi
# cmd # cmd
local cmd="${$(fc -l | tail -1)#* }"; local cmd="${$(fc -l | tail -1)#* }";
local color_cmd=""; local color_cmd="";
if $1; if $1;
then then
color_cmd="$fg_no_bold[green]"; color_cmd="$fg_no_bold[green]";
else else
color_cmd="$fg_bold[red]"; color_cmd="$fg_bold[red]";
fi fi
local color_reset="$reset_color"; local color_reset="$reset_color";
cmd="${color_cmd}${cmd}${color_reset}" cmd="${color_cmd}${cmd}${color_reset}"
# time # time
local time="[$(date +%H:%M:%S)]" # you can use the real_time command to replace
local color_time="$fg_no_bold[cyan]"; local color_time="$fg_no_bold[cyan]";
time="${color_time}${time}${color_reset}"; local _time="${color_time}$(strf_real_time)${color_reset}";
# cost # cost
local time_end="$(current_time_millis)"; local time_end="$(current_time_millis)";
local cost=$(bc -l <<<"${time_end}-${COMMAND_TIME_BEIGIN}"); local cost=$(bc -l <<<"${time_end}-${COMMAND_TIME_BEIGIN}");
COMMAND_TIME_BEIGIN="-20200325" COMMAND_TIME_BEIGIN="-20200325"
local length_cost=${#cost}; local length_cost=${#cost};
if [ "$length_cost" = "4" ]; if [ "$length_cost" = "11" ]; # 11 means the length of cost
then then
cost="0${cost}" cost="0${cost}"
fi fi
cost="[cost ${cost}s]" cost="[cost ${cost}s]"
local color_cost="$fg_no_bold[yellow]"; local color_cost="$fg_no_bold[yellow]";
cost="${color_cost}${cost}${color_reset}"; cost="${color_cost}${cost}${color_reset}";
echo -e "${time} ${cost} ${cmd}"; echo -e "${_time} ${cost} ${cmd}";
echo -e "";
local echo_dark_gray="\033[2;49;39m"
echo -e "$echo_dark_gray${(l.$(afmagic_dashes)..-.)}${color_reset}" echo -e "";
local echo_dark_gray="\033[2;49;39m"
echo -e "$echo_dark_gray${(l.$(afmagic_dashes)..-.)}${color_reset}"
} }
# command execute before # command execute before
# REF: http://zsh.sourceforge.net/Doc/Release/Functions.html # REF: http://zsh.sourceforge.net/Doc/Release/Functions.html
preexec() { preexec() {
COMMAND_TIME_BEIGIN="$(current_time_millis)"; COMMAND_TIME_BEIGIN="$(current_time_millis)";
} }
current_time_millis() {
local time_millis;
if [[ "$OSTYPE" == "linux-gnu" ]]; then
# Linux
time_millis="$(date +%s.%3N)";
elif [[ "$OSTYPE" == "darwin"* ]]; then
# macOS
time_millis="$(gdate +%s.%3N)";
elif [[ "$OSTYPE" == "cygwin" ]]; then
# POSIX compatibility layer and Linux environment emulation for Windows
elif [[ "$OSTYPE" == "msys" ]]; then
# Lightweight shell and GNU utilities compiled for Windows (part of MinGW)
elif [[ "$OSTYPE" == "win32" ]]; then
# I'm not sure this can happen.
elif [[ "$OSTYPE" == "freebsd"* ]]; then
# ...
else
# Unknown.
fi
echo $time_millis;
}
# command execute after # command execute after
# REF: http://zsh.sourceforge.net/Doc/Release/Functions.html # REF: http://zsh.sourceforge.net/Doc/Release/Functions.html
dash_passion_precmd() { dash_passion_precmd() {
# last_cmd # last_cmd
local last_cmd_return_code=$?; local last_cmd_return_code=$?;
local last_cmd_result=true; local last_cmd_result=true;
if [ "$last_cmd_return_code" = "0" ]; if [ "$last_cmd_return_code" = "0" ];
then then
last_cmd_result=true; last_cmd_result=true;
else else
last_cmd_result=false; last_cmd_result=false;
fi fi
# update_git_status # update_git_status
update_git_status update_git_status
# update_command_status # update_command_status
update_command_status $last_cmd_result; update_command_status $last_cmd_result;
# output command execute after # output command execute after
output_command_execute_after $last_cmd_result; output_command_execute_after $last_cmd_result;
} }
TMOUT=1; # real time clock for zsh.
# https://stackoverflow.com/questions/2187829/constantly-updated-clock-in-zsh-prompt
schedprompt() {
emulate -L zsh
zmodload -i zsh/sched
TRAPALRM() { # Remove existing event, so that multiple calls to
# $(git_prompt_info) cost too much time which will raise stutters when inputting. so we need to disable it in this occurence. # "schedprompt" work OK. (You could put one in precmd to push
# if [ "$WIDGET" != "expand-or-complete" ] && [ "$WIDGET" != "self-insert" ] && [ "$WIDGET" != "backward-delete-char" ]; then # the timer 30 seconds into the future, for example.)
# black list will not enum it completely. even some pipe broken will appear. integer i=${"${(@)zsh_scheduled_events#*:*:}"[(I)schedprompt]}
# so we just put a white list here. (( i )) && sched -$i
if [ "$WIDGET" = "" ] || [ "$WIDGET" = "accept-line" ] ; then
zle reset-prompt; # Test that zle is running before calling the widget (recommended
fi # to avoid error messages).
# Otherwise it updates on entry to zle, so there's no loss.
if [ "$WIDGET" = "" ] || [ "$WIDGET" = "accept-line" ] ; then
zle && zle reset-prompt;
fi
# This ensures we're not too far off the start of the minute
sched +1 schedprompt
} }
zmodload -i zsh/datetime
setopt prompt_subst setopt prompt_subst
PROMPT='$(real_time) $(directory) $(git_status) $(command_status) '; PROMPT='$(real_time) $(directory) $(git_status) $(command_status) ';
RPROMPT='%{$FG[242]%}%n@%m $(battery_pct_prompt)${color_reset}'; RPROMPT='%{$FG[242]%}%n@%m $(battery_pct_prompt)${color_reset}';
autoload -Uz add-zsh-hook autoload -Uz add-zsh-hook
add-zsh-hook precmd dash_passion_precmd add-zsh-hook precmd dash_passion_precmd
schedprompt