Optimize `git status` for shell prompt

38 Views Asked by At

Recently I wrote my own shell prompt like this:

git_status() {
  if git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
    local untracked=0
    local modified=0
    local modified_updated=0
    local new_added=0
    local deleted=0
    local deleted_updated=0
    local renamed_updated=0

    local status_items=$(git status --porcelain)
    if [ -n "$status_items" ]; then
      while IFS= read -r item; do
        case "${item:0:2}" in
          "??") ((untracked++));;
          "MM") ((modified++)); ((modified_updated++));;
          " M") ((modified++));;
          "M ") ((modified_updated++));;
          "A ") ((new_added++));;
          " D") ((deleted++));;
          "D ") ((deleted_updated++));;
          "R ") ((renamed_updated++));;
        esac
      done <<< "$status_items"

      local result=""
      local index=""
      local workdir=""

      if [ "$untracked" -ne 0 ]; then
        workdir+="${untracked}?"
      fi
      if [ "$modified" -ne 0 ]; then
        workdir+="${modified}*"
      fi
      if [ "$modified_updated" -ne 0 ]; then
        index+="${modified_updated}*"
      fi
      if [ "$new_added" -ne 0 ]; then
        index+="${new_added}+"
      fi
      if [ "$deleted" -ne 0 ]; then
        workdir+="${deleted}x"
      fi
      if [ "$deleted_updated" -ne 0 ]; then
        index+="${deleted_updated}x"
      fi
      if [ "$renamed_updated" -ne 0 ]; then
        index+="${renamed_updated}^"
      fi

      if [ -z "$index" ]; then
        index=",,Ծ"
      fi
      if [ -z "$workdir" ]; then
        index="Ծ,,"
      fi

      result="${index}ω${workdir}"

      echo "$result"
    else
      echo ""
    fi
  else
    echo ""
  fi
}

thy_prompt() {
    result="┌─[\u@\h]─[\w]"

    if [ -n "$(git_status)" ]; then
        result+="─[$(git_status)]"
    fi

    result+="─[\t]─[$?]\n└─> λ "
    PS1="$result"
    # echo "$result"
}

PROMPT_COMMAND=thy_prompt

However, it came out that the command git status --porcelain had dragged down the perfomance of shell prompt building. I can feel the delay of the building process, which impacted my user experience.

I'd like to know if there's any way to improve the performance of git status or the building process, like synchronization or something else.

I've noticed that p10k's git status has excellent performance, and I'm wondering if there's a way to use it in the shell prompt I'm writing myself. I don't want to use a plugin, because I'm writing this to make it easier for me to use the shell in a network-less environment.

0

There are 0 best solutions below