From e5dd864adfeb8b0176b31a132e972d7f7beff32a Mon Sep 17 00:00:00 2001
From: Ted Pavlic <ted@tedpavlic.com>
Date: Wed, 11 Feb 2009 13:03:25 -0500
Subject: [PATCH] completion: Better __git_ps1 support when not in working
 directory

If .git/HEAD is not readable, __git_ps1 does nothing.

If --is-in-git-dir, __git_ps1 returns " (GIT_DIR!)" as a cautionary
note. The previous behavior would show the branch name (and would
optionally attempt to determine the dirtyState of the directory, which
was impossible because a "git diff" was used).

If --is-in-work-tree, __git_ps1 returns the branch name. Additionally,
if showDirtyState is on, the dirty state is displayed.

Signed-off-by: Ted Pavlic <ted@tedpavlic.com>
Acked-by: Shawn O. Pearce <spearce@spearce.org>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
---
 contrib/completion/git-completion.bash | 36 ++++++++++++++++----------
 1 file changed, 22 insertions(+), 14 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index c61576fcafc..aa8eec24d98 100755
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -108,7 +108,9 @@ __git_ps1 ()
 			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")..."
+					if [ -r "$g/HEAD" ]; then
+						b="$(cut -c1-7 "$g/HEAD")..."
+					fi
 				fi
 			fi
 		fi
@@ -116,23 +118,29 @@ __git_ps1 ()
 		local w
 		local i
 
-		if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ]; then
-			if [ "$(git config --bool bash.showDirtyState)" != "false" ]; then
-				git diff --no-ext-diff --ignore-submodules \
-					--quiet --exit-code || w="*"
-				if git rev-parse --quiet --verify HEAD >/dev/null; then
-					git diff-index --cached --quiet \
-						--ignore-submodules HEAD -- || i="+"
-				else
-					i="#"
+		if [ "true" = "$(git rev-parse --is-inside-git-dir 2>/dev/null)" ]; then
+			b="GIT_DIR!"
+		elif [ "true" = "$(git rev-parse --is-inside-work-tree 2>/dev/null)" ]; then
+			if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ]; then
+				if [ "$(git config --bool bash.showDirtyState)" != "false" ]; then
+					git diff --no-ext-diff --ignore-submodules \
+						--quiet --exit-code || w="*"
+					if git rev-parse --quiet --verify HEAD >/dev/null; then
+						git diff-index --cached --quiet \
+							--ignore-submodules HEAD -- || i="+"
+					else
+						i="#"
+					fi
 				fi
 			fi
 		fi
 
-		if [ -n "${1-}" ]; then
-			printf "$1" "${b##refs/heads/}$w$i$r"
-		else
-			printf " (%s)" "${b##refs/heads/}$w$i$r"
+		if [ -n "$b" ]; then
+			if [ -n "${1-}" ]; then
+				printf "$1" "${b##refs/heads/}$w$i$r"
+			else
+				printf " (%s)" "${b##refs/heads/}$w$i$r"
+			fi
 		fi
 	fi
 }