diff --git a/lib/functions.zsh b/lib/functions.zsh index efb73a1b..5f8ca6eb 100644 --- a/lib/functions.zsh +++ b/lib/functions.zsh @@ -62,6 +62,32 @@ function try_alias_value() { alias_value "$1" || echo "$1" } +# +# Alias only if not already a command/function/alias +# Use option ALLOW_OVERRIDE_ALIASES to force overriding +# +# Arguments: +# 1. my_alias='my alias value' +# Same argument you would pass to the "alias" built-in +# Return value: +# 0 if the alias was safely created, 73 otherwise +# +function safe_alias() { + emulate -L zsh + local cmd lhs rhs + cmd=(${(s:=:)1}) + lhs=$cmd[1] + rhs=$cmd[2,-1] + if (( $+commands[$lhs] || $+functions[$lhs] || $+aliases[$lhs] )); then + if [[ $ALLOW_OVERRIDE_ALIASES = "true" ]]; then + >&2 echo "WARN: override \"$lhs\" with alias \"$rhs\"" + else + return 73 # os.EX_CANTCREAT + fi + fi + alias $lhs="$rhs" +} + # # Set variable "$1" to default value "$2" if "$1" is not yet defined. # diff --git a/templates/zshrc.zsh-template b/templates/zshrc.zsh-template index 44e8b0d1..ce03da35 100644 --- a/templates/zshrc.zsh-template +++ b/templates/zshrc.zsh-template @@ -37,6 +37,11 @@ ZSH_THEME="robbyrussell" # much, much faster. # DISABLE_UNTRACKED_FILES_DIRTY="true" +# Uncomment the following line to allow aliases defined in libs and plugins to +# override existing commands/functions/aliases. A warning will be printed for +# every alias overriding an existing name. +# ALLOW_OVERRIDE_ALIASES="true" + # Uncomment the following line if you want to change the command execution time # stamp shown in the history command output. # The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"