]> git.phdru.name Git - git-scripts.git/commitdiff
Feat: Fix detached `HEAD`
authorOleg Broytman <phd@phdru.name>
Mon, 3 Aug 2020 15:04:52 +0000 (18:04 +0300)
committerOleg Broytman <phd@phdru.name>
Mon, 3 Aug 2020 15:04:52 +0000 (18:04 +0300)
Fix detached `HEAD` by checking out the branch
(local or remote, if one exists) that points to the same commit.

detached-head/fix-detached-head [new file with mode: 0755]
detached-head/fix-detached-head-recursive [new file with mode: 0755]
detached-head/fix-detached-head-repos [new file with mode: 0755]

diff --git a/detached-head/fix-detached-head b/detached-head/fix-detached-head
new file mode 100755 (executable)
index 0000000..7be050a
--- /dev/null
@@ -0,0 +1,19 @@
+#! /usr/bin/env bash
+
+git symbolic-ref -q HEAD >/dev/null && exit
+
+pwd
+
+declare -a branches
+branches=(`git branch --points-at=HEAD | tail -n +2`)
+if [ "${#branches[*]}" -eq 0 ]; then
+   branches=(`git branch --points-at=HEAD -r | sed 's!^ *origin/!!'`)
+fi
+
+if [ "${#branches[*]}" -eq 0 ]; then
+   echo "Cannot find a branch" >&2
+elif [ "${#branches[*]}" -eq 1 ]; then
+   git checkout "${branches[0]}"
+else
+   echo "Too many branches" >&2
+fi
diff --git a/detached-head/fix-detached-head-recursive b/detached-head/fix-detached-head-recursive
new file mode 100755 (executable)
index 0000000..dbc501d
--- /dev/null
@@ -0,0 +1,4 @@
+#! /bin/sh
+
+prog_dir="`dirname \"$0\"`" &&
+exec "$prog_dir"/../run-recursive "$prog_dir"/fix-detached-head
diff --git a/detached-head/fix-detached-head-repos b/detached-head/fix-detached-head-repos
new file mode 100755 (executable)
index 0000000..f76c85d
--- /dev/null
@@ -0,0 +1,7 @@
+#! /bin/sh
+
+cd "`dirname \"$0\"`" &&
+prog_dir="`pwd`" &&
+export prog_dir
+
+exec "$prog_dir"/../run-repos "$prog_dir"/fix-detached-head-recursive