Show path from project root in ZSH Prompt

promptzsh

If my pwd is ~/repos/blog/app/views/, I'd like to show only blog/app/views in the prompt i.e. I want to show only the project root. Project root is the parent directory of .git directory. Is there a way I can achieve this?

Best Answer

You can execute arbitrary code to display the prompt if you set the prompt_subst option. You don't need to look up the .git directory every time a prompt is displayed: in practice, it's enough to update a variable on every current directory change, in the chpwd hook, and use that variable in your prompt.

setopt prompt_subst
chpwd () {
  git_root=$PWD
  while [[ $git_root != / && ! -e $git_root/.git ]]; do
    git_root=$git_root:h
  done
  if [[ $git_root = / ]]; then
    unset git_root
    prompt_short_dir=%~
  else
    prompt_short_dir=${PWD#$git_root/}
  fi
}
chpwd
PS1='${prompt_short_dir}%# '
Related Question