#!/bin/zshexportYSU_VERSION='1.11.1'if ! type"tput" > /dev/null; thenprintf"WARNING: tput command not found on your PATH.\n"printf"zsh-you-should-use will fallback to uncoloured messages\n"elseNONE="$(tput sgr0)"BOLD="$(tput bold)"RED="$(tput setaf 1)"YELLOW="$(tput setaf 3)"PURPLE="$(tput setaf 5)"fifunction check_alias_usage(){# Optional parameter that limits how far back history is checked# I've chosen a large default value instead of bypassing tail because it's simplerlocallimit="${1:-${HISTSIZE:-9000000000000000}}"local key
declare -A usage
for key in"${(@k)aliases}"; do usage[$key]=0done# TODO:# Handle and (&&) + (&)# others? watch, time etc...local -a histfile_lines
histfile_lines=("${(@f)$(<$HISTFILE)}")histfile_lines=("${histfile_lines[@]#*;}")localcurrent=0localtotal=${#histfile_lines}if[[$total -gt $limit]]; thentotal=$limitfilocal entry
for line in${histfile_lines[@]} ; dofor entry in${(@s/|/)line}; do# Remove leading whitespaceentry=${entry##*[[:space:]]}# We only care about the first word because that's all aliases work with# (this does not count global and git aliases)localword=${entry[(w)1]}if[[ -n ${usage[$word]}]]; then(( usage[$word]++ ))fidone# print current progress(( current++ ))printf"Analysing: [$current/$total]\r"done# Clear all previous line outputprintf"\r\033[K"# Print ordered usagefor key in${(k)usage}; doecho"${usage[$key]}: ${(q+)key}=${(q+)aliases[$key]}"done | sort -rn -k1
}# Writing to a buffer rather than directly to stdout/stderr allows us to decide# if we want to write the reminder message before or after a command has been executedfunction _write_ysu_buffer(){_YSU_BUFFER+="$@"# Maintain historical behaviour by defaultlocalposition="${YSU_MESSAGE_POSITION:-before}"if[["$position"="before"]]; then _flush_ysu_buffer
elif[["$position" !="after"]]; then(>&2printf"${RED}${BOLD}Unknown value for YSU_MESSAGE_POSITION '$position'. ")(>&2printf"Expected value 'before' or 'after'${NONE}\n") _flush_ysu_buffer
fi}function _flush_ysu_buffer(){# It's important to pass $_YSU_BUFFER to printfs first argument# because otherwise all escape codes will not printed correctly(>&2printf"$_YSU_BUFFER")_YSU_BUFFER=""}function ysu_message(){localDEFAULT_MESSAGE_FORMAT="${BOLD}${YELLOW}\Found existing %alias_type for ${PURPLE}\"%command\"${YELLOW}. \You should use: ${PURPLE}\"%alias\"${NONE}"localalias_type_arg="${1}"localcommand_arg="${2}"localalias_arg="${3}"# Escape arguments which will be interpreted by printf incorrectly# unfortunately there does not seem to be a nice way to put this into# a function because returning the values requires to be done by printf/echo!!command_arg="${command_arg//\%/%%}"command_arg="${command_arg//\\/\\\\}"localMESSAGE="${YSU_MESSAGE_FORMAT:-"$DEFAULT_MESSAGE_FORMAT"}"MESSAGE="${MESSAGE//\%alias_type/$alias_type_arg}"MESSAGE="${MESSAGE//\%command/$command_arg}"MESSAGE="${MESSAGE//\%alias/$alias_arg}" _write_ysu_buffer "$MESSAGE\n"}# Prevent command from running if hardcore mode enabledfunction _check_ysu_hardcore(){localalias_name="$1"localhardcore_lookup="${YSU_HARDCORE_ALIASES[(r)$alias_name]}"if((${+YSU_HARDCORE}))||[[ -n "$hardcore_lookup"&&"$hardcore_lookup"=="$alias_name"]]; then _write_ysu_buffer "${BOLD}${RED}You Should Use hardcore mode enabled. Use your aliases!${NONE}\n"kill -s INT $$fi}function _check_git_aliases(){localtyped="$1"localexpanded="$2"# sudo will use another user's profile and so aliases would not applyif[["$typed"="sudo "* ]]; thenreturnfiif[["$typed"="git "* ]]; thenlocalfound=false git config --get-regexp "^alias\..+$" | sort | whileread key value; dokey="${key#alias.}"# if for some reason, read does not split correctly, we# detect that and manually split the key and valueif[[ -z "$value"]]; thenvalue="${key#* }"key="${key%% *}"fiif[["$expanded"="git $value"||"$expanded"="git $value "* ]]; then ysu_message "git alias""$value""git $key"found=truefidoneif$found; then _check_ysu_hardcore
fifi}function _check_global_aliases(){localtyped="$1"localexpanded="$2"localfound=falselocal tokens
local key
local value
local entry
# sudo will use another user's profile and so aliases would not applyif[["$typed"="sudo "* ]]; thenreturnfialias -g | sort | whileIFS="="read -r key value; dokey="${key## }"key="${key%% }"value="${(Q)value}"# Skip ignored global aliasesif[[${YSU_IGNORED_GLOBAL_ALIASES[(r)$key]}=="$key"]]; thencontinuefiif[["$typed"= *" $value "* ||\"$typed"= *" $value"||\"$typed"="$value "* ||\"$typed"="$value"]]; then ysu_message "global alias""$value""$key"found=truefidoneif$found; then _check_ysu_hardcore
fi}# Returns 0 if the first word of typed resolves (via alias chain) to target_alias,# 1 otherwise. Handles cyclic chains by tracking visited aliases.function _typed_resolves_to_alias(){localtyped_cmd="${1%% *}"localtarget_alias="$2"localcheck_value="${aliases[$typed_cmd]}"local check_cmd
local -A visited_aliases
visited_aliases[$typed_cmd]=1while[[ -n "$check_value"]]; doif[["$check_value"="$target_alias"||"$check_value"="$target_alias "* ]]; thenreturn0ficheck_cmd="${check_value%% *}"if[[ -n "${visited_aliases[$check_cmd]}"]]; thenbreakfi visited_aliases[$check_cmd]=1check_value="${aliases[$check_cmd]}"donereturn1}function _check_aliases(){localtyped="$1"localexpanded="${2:-$1}"local found_aliases
found_aliases=()localbest_match=""localbest_match_value=""local key
local value
# sudo will use another user's profile and so aliases would not applyif[["$typed"="sudo "* ]]; thenreturnfi# Find alias matchesfor key in"${(@k)aliases}"; dovalue="${aliases[$key]}"# Skip ignored aliasesif[[${YSU_IGNORED_ALIASES[(r)$key]}=="$key"]]; thencontinuefiif[["$expanded"="$value"||"$expanded"="$value "* ]]; then# if the alias longer or the same length as its command# we assume that it is there to cater for typos.# If not, then the alias would not save any time# for the user and so doesn't hold much value anywayif[["${#value}" -gt "${#key}"]]; thenfound_aliases+="$key"# Match aliases to longest portion of commandif[["${#value}" -gt "${#best_match_value}"]]; thenbest_match="$key"best_match_value="$value"# on equal length, choose the shortest aliaselif[["${#value}" -eq "${#best_match_value}"&&${#key} -lt "${#best_match}"]]; thenbest_match="$key"best_match_value="$value"fififidone# Print result matches based on current modeif[["$YSU_MODE"="ALL"]]; thenfor key in${(@ok)found_aliases}; dovalue="${aliases[$key]}"if[["$typed"="$key"||"$typed"="$key "* ]]|| _typed_resolves_to_alias "$typed""$key"; thencontinuefi ysu_message "alias""$value""$key" _check_ysu_hardcore "$key"doneelif[[(-z "$YSU_MODE"||"$YSU_MODE"="BESTMATCH")&& -n "$best_match"]]; then# make sure that the best matched alias has not already# been typed by the uservalue="${aliases[$best_match]}"if[["$typed"="$best_match"||"$typed"="$best_match "* ]]|| _typed_resolves_to_alias "$typed""$best_match"; thenreturnfi ysu_message "alias""$value""$best_match" _check_ysu_hardcore "$best_match"fi}function disable_you_should_use(){ add-zsh-hook -D preexec _check_aliases
add-zsh-hook -D preexec _check_global_aliases
add-zsh-hook -D preexec _check_git_aliases
add-zsh-hook -D precmd _flush_ysu_buffer
}function enable_you_should_use(){ disable_you_should_use # Delete any possible pre-existing hooks add-zsh-hook preexec _check_aliases
add-zsh-hook preexec _check_global_aliases
add-zsh-hook preexec _check_git_aliases
add-zsh-hook precmd _flush_ysu_buffer
}autoload -Uz add-zsh-hook
enable_you_should_use