summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMichael Allen <michael@michaelallen.io>2015-02-18 09:12:06 +0000
committerMichael Allen <michael@michaelallen.io>2015-02-18 11:53:36 +0000
commit937a5452e2e7cebe195855e7360331345bb242a2 (patch)
treea9cfb3bb6c6d33d51eeb02d311843f276cda374a
parent01538d46bac4d2607ad01d04548085f6918ba4d0 (diff)
downloadgit-sonar-937a5452e2e7cebe195855e7360331345bb242a2.tar.gz
git-sonar-937a5452e2e7cebe195855e7360331345bb242a2.zip
handle detached heads cleanly
-rwxr-xr-xgit-base.sh29
-rwxr-xr-xtest-branches.sh44
2 files changed, 69 insertions, 4 deletions
diff --git a/git-base.sh b/git-base.sh
index 18d3dec..d1687da 100755
--- a/git-base.sh
+++ b/git-base.sh
@@ -98,10 +98,33 @@ fetch() {
debug_print $debug "Finished fetch"
}
+commit_short_sha() {
+ if is_repo; then
+ echo "$(git rev-parse --short HEAD)"
+ fi
+}
+
branch_name() {
if is_repo; then
- local localBranch="$(git symbolic-ref --short HEAD)"
- echo $localBranch
+ name="$(git symbolic-ref --short HEAD 2>/dev/null)"
+ retcode="$?"
+ if [[ "$retcode" == "0" ]]; then
+ echo "$name"
+ else
+ return 1
+ fi
+ fi
+}
+
+branch_ref() {
+ if is_repo; then
+ echo "$(branch_name || commit_short_sha)"
+ fi
+}
+
+readable_branch_name() {
+ if is_repo; then
+ echo "$(branch_name || echo "detached@$(commit_short_sha)")"
fi
}
@@ -115,7 +138,7 @@ is_tracking_remote() {
remote_branch_name() {
if is_repo; then
- local remoteBranch="$(git for-each-ref --format='%(upstream:short)' | grep "$(branch_name)")"
+ local remoteBranch="$(git for-each-ref --format='%(upstream:short)' refs/heads | grep "$(branch_name)")"
if [[ -n $remoteBranch ]]; then
echo $remoteBranch
return 0
diff --git a/test-branches.sh b/test-branches.sh
index ddf442c..4ed7957 100755
--- a/test-branches.sh
+++ b/test-branches.sh
@@ -12,7 +12,7 @@ cd_to_tmp() {
rm_tmp() {
cd $scriptDir
- rm -r "$tmpfile"
+ rm -rf /tmp/git-prompt-tests*
}
test_branch_name_in_repo() {
@@ -36,4 +36,46 @@ test_branch_name_not_in_repo() {
rm_tmp
}
+test_detached_from_branch() {
+ cd_to_tmp
+ git init --quiet
+ assertEquals "master" "$(branch_name)"
+
+ touch README
+ git add .
+ git commit -m "initial commit" --quiet
+
+ touch foo
+ git add .
+ git commit -m "foo" --quiet
+
+ git checkout --quiet HEAD^ >/dev/null
+ sha="$(commit_short_sha)"
+
+ assertNotEquals "master" "$(branch_name)"
+ assertEquals "$sha" "$(branch_ref)"
+ assertEquals "detached@$sha" "$(readable_branch_name)"
+
+ rm_tmp
+}
+
+test_branch_name_returns_error() {
+ cd_to_tmp
+ git init --quiet
+
+ touch README
+ git add .
+ git commit -m "initial commit" --quiet
+
+ touch foo
+ git add .
+ git commit -m "foo" --quiet
+
+ git checkout --quiet HEAD^ >/dev/null
+
+ retcode="$(branch_name; echo $?)"
+ assertEquals "1" "$retcode"
+ rm_tmp
+}
+
. ./shunit/shunit2