Bulix.org » Life snippets

A faster git branch in your prompt

← Billet précédent · Billet suivant →

A little while ago, I posted here a snippet that would add the current git branch (when applicable) into your prompt's display. This snippet used git branch directly, which turned out to be quite slow when entering a git repository in a new shell session, especially large repositories like kernel trees.

Salvaging from Bash's completion for git, a new snippet was put together. Albeit much larger, it is way faster since it directly relies on the files present in the .git/ directory. Here it is, as included in my ~/.zshprompt file:

# For the git branch name in the prompt
function git_ps1 {
  if which git &> /dev/null; then
    local g="$(git rev-parse --git-dir 2>/dev/null)"
    if [ -n "$g" ]; then
      local r
      local b
      if [ -d "$g/rebase-apply" ]; then
        if test -f "$g/rebase-apply/rebasing"; then
          r="|rebase"
        elif test -f "$g/rebase-apply/applying"; then
          r="|am"
        else
          r="|am/rebase"
        fi
        b="$(git symbolic-ref HEAD 2>/dev/null)"
      elif [ -f "$g/rebase-merge/interactive" ]; then
        r="|rebase-i"
        b="$(cat "$g/rebase-merge/head-name")"
      elif [ -d "$g/rebase-merge" ]; then
        r="|rebase-m"
        b="$(cat "$g/rebase-merge/head-name")"
      elif [ -f "$g/MERGE_HEAD" ]; then
        r="|merging"
        b="$(git symbolic-ref HEAD 2>/dev/null)"
      else
        if [ -f "$g/BISECT_LOG" ]; then
         r="|bisecting"
        fi
        if ! b="$(git symbolic-ref HEAD 2>/dev/null)"; then
          if ! b="$(git describe --exact-match HEAD 2>/dev/null)"; then
            b="$(cut -c1-7 "$g/HEAD")..."
          fi
        fi
      fi

      printf "%s" "(${b##refs/heads/}$r)"
    fi
  else
    printf ""
  fi
}

You can then simply add $(git_ps1) to your PROMPT variable definition.

# · Aucun commentaire

Ajouter un commentaire

Pseudo :
Commentaire :


Antispam: 5 + 3 ?
Créez-vous un compte pour en être débarrassé !
URL :
Email :
Gravatars activés.
Se souvenir de moi