用AI模仿.git-prompt.sh写了个简化高性能版本.git-branch-prompt.sh

使用,

# {{ Define some colors first:
# infocmp xterm-256color >/dev/null 2>&1 && export TERM=xterm-256color
export MAGENTA="\033[1;31m"
export ORANGE="\033[1;33m"
export GREEN="\033[1;32m"
export PURPLE="\033[1;35m"
export WHITE="\033[1;37m"
export RESET="\033[m"
# }}

 if [ -x /usr/bin/git ]; then
    source "$HOME/.git-branch-prompt.sh"
    export PROMPT_COMMAND='history -a;__fast_git_ps1 "${MAGENTA}\u${RESET}@${ORANGE}\h${RESET}:${GREEN}\w${RESET}${PURPLE}" "${RESET}\n\$ "'
    export PS2="${ORANGE}->${RESET}"
else
    export PROMPT_COMMAND='history -a;'
fi

代码,

#!/usr/bin/env bash
# Ultra-simple Git prompt for Bash: branch + staged (+) + unstaged (*)
# Always recomputes on each prompt draw (still only 1 Git call).
# Usage:
#   export PROMPT_COMMAND='history -a;__fast_git_ps1 "<prefix>" "<suffix>" [format]'

__fast_git_ps1() {
  local prev_exit="$?"
  local pcmode=no ps1_start="" ps1_end="" printf_format=' (%s)'

  case "$#" in
    2|3)
      pcmode=yes
      ps1_start="$1"
      ps1_end="$2"
      printf_format="${3:-$printf_format}"
      PS1="$ps1_start$ps1_end"
      ;;
    0|1)
      printf_format="${1:-$printf_format}"
      ;;
    *)
      return "$prev_exit"
      ;;
  esac

  # Compute segment: branch + staged (+) + unstaged (*)
  local status
  status="$(git -c status.aheadBehind=false status \
              --porcelain=v2 --branch \
              --untracked-files=no \
              --ignore-submodules=all 2>/dev/null)" || {
    [[ "$pcmode" == yes ]] && return "$prev_exit"
    return "$prev_exit"
  }

  local branch="" staged="" unstaged=""
  while IFS= read -r line; do
    case "$line" in
      \#\ branch.head*)
        branch="${line##* }"
        ;;
      [12u]\ *)
        local x="${line:2:1}" y="${line:3:1}"
        [[ "$x" != "." ]] && staged="+"
        [[ "$y" != "." ]] && unstaged="*"
        [[ -n "$staged" && -n "$unstaged" ]] && break
        ;;
    esac
  done <<<"$status"

  if [[ "$branch" == "(detached)" ]]; then
    branch="$(git rev-parse --short HEAD 2>/dev/null)"
  fi

  local out
  printf -v out -- "$printf_format" "${branch}${staged}${unstaged}"

  if [[ "$pcmode" == yes ]]; then
    PS1="$ps1_start$out$ps1_end"
  else
    printf -- '%s' "$out"
  fi

  return "$prev_exit"
}

1 个赞