Overridable functions in Zsh

oh-my-zshzsh

Consider the following two functions:

function slow_git_prompt_info() {
  if [[ "$(command git config --get oh-my-zsh.hide-status 2>/dev/null)" != "1" ]]; then
    ref=$(command git symbolic-ref HEAD 2> /dev/null) || \
    ref=$(command git rev-parse --short HEAD 2> /dev/null) || return 0
    echo "$ZSH_THEME_GIT_PROMPT_PREFIX${ref#refs/heads/}$(parse_git_dirty)$ZSH_THEME_GIT_PROMPT_SUFFIX"
  fi
}

and:

function branch_name_only_git_prompt_info() {
  ref=$(git symbolic-ref HEAD 2> /dev/null) || return
  echo "$ZSH_THEME_GIT_PROMPT_PREFIX${ref#refs/heads/}$ZSH_THEME_GIT_PROMPT_SUFFIX"
}

I would like to define another third function that, when called, overrides/defines the function git_prompt_info() in the main "namespace" to make it "point" to fast_git_prompt_info

E.g. something like:

# Pseudo-code:
function redefine_git_prompt_info() {
   git_prompt_info = branch_name_only_git_prompt_info
}

Is this at all possible with Zsh? If so, how?

Best Answer

You can define a function anywhere. To chain another function, just call it with the same parameters.

redefine_git_prompt_info () {
  git_prompt_info () { branch_name_only_git_prompt_info "$@"; }
}

If branch_name_only_git_prompt_info is later redefined, a call to redefine_git_prompt_info will call the new definition. If you want to copy the current definition, in zsh, you can do it easily thanks to the functions array.

redefine_git_prompt_info () {
  functions[git_prompt_info]=$functions[branch_name_only_git_prompt_info]
}
Related Question