Skip to content

Instantly share code, notes, and snippets.

@jn0
Created September 25, 2020 13:29
Show Gist options
  • Save jn0/9ae5911e308aa95613a2d6da0f425065 to your computer and use it in GitHub Desktop.
Save jn0/9ae5911e308aa95613a2d6da0f425065 to your computer and use it in GitHub Desktop.
bashrc feature to avoid wrong edits
# Usage: source it from ~/.bashrc before unsetting color_prompt
# it will notify you when you're about to crack a git repo at wrong branch...
_is_git() {
local wd=`pwd`
while [ -n "$wd" -a "$wd" != '/' ]; do
[ -d "$wd/.git/." ] && { echo "$wd"; return 0; }
wd="$(dirname "$wd")"
done
return 1
}
_git_warn() {
local color=no; [ "$1" = color ] && color=yes
local git=''
if git=$(_is_git); then
local branch=$(git branch --list --no-color | awk '$1=="*"{print $2;exit}')
[ -z "$branch" ] && { echo '[!]'; return; }
local status=$(git status --porcelain | wc -l)
if echo "$branch" | grep -q \\.; then
local -i n=$(echo "$branch" | tr '.' '\n' | wc -l)
branch="…$(echo -n "$branch" | cut -d. -f$n)"
fi
case "$branch" in
test|prod)
if [ "$color" = yes ]; then
branch=$'\033''[0;1;31m'"$branch"$'\033''[00m'$'\033''[01;34m'
else
branch="!!${branch}!!"
fi;;
esac
[ "$status" = 0 ] || branch+=":${status}"
echo "[$branch]"
fi
}
if [ "$color_prompt" = yes ]; then
PS1="${PS1/'\w'/'\[\033[01;34m\]\w$(_git_warn color)\[\033[00m\]'}"
else
PS1="${PS1/'\w'/'\w$(_git_warn)'}"
fi
# EOF #
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment