Skip to content

Instantly share code, notes, and snippets.

@sffej
Forked from Ragnoroct/__fastgit_ps1.sh
Created January 18, 2023 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sffej/4566641b97b8e765eb58cf4e187d0836 to your computer and use it in GitHub Desktop.
Save sffej/4566641b97b8e765eb58cf4e187d0836 to your computer and use it in GitHub Desktop.
Blazing fast simple git branch name for ps1
# Copyright (c) 2019 Will Bender. All rights reserved.
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
# Very fast __git_ps1 implementation
# Inspired by https://gist.github.com/wolever/6525437
# Mainly this is useful for Windows users stuck on msys, cygwin, or slower wsl 1.0 because git/fs operations are just slower
# Caching can be added by using export but PROMPT_COMMAND is necessary since $() is a subshell and cannot modify parent state.
# Linux: time __ps1_ps1 (~7ms)
# Windows msys2: time __git_ps1 (~100ms)
# Windows msys2: time git rev-parse --abbrev-ref HEAD 2> /dev/null (~86ms)
# Windows msys2: time __fastgit_ps1 (~1-3ms)
# Simple PS1 without colors using format arg. Feel free to use PROMPT_COMMAND
export PS1="\u@\h \w \$(__fastgit_ps1 '[%s] ')$ "
# 100% pure Bash (no forking) function to determine the name of the current git branch
function __fastgit_ps1 () {
local headfile head branch
local dir="$PWD"
while [ -n "$dir" ]; do
if [ -e "$dir/.git/HEAD" ]; then
headfile="$dir/.git/HEAD"
break
fi
dir="${dir%/*}"
done
if [ -e "$headfile" ]; then
read -r head < "$headfile" || return
case "$head" in
ref:*) branch="${head##*/}" ;;
"") branch="" ;;
*) branch="${head:0:7}" ;; #Detached head. You can change the format for this too.
esac
fi
if [ -z "$branch" ]; then
return 0
fi
if [ -z "$1" ]; then
# Default format
printf "(%s) " "$branch"
else
# Use passed format string
printf "$1" "$branch"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment