git-checkout: handle local changes sanely when detaching HEAD
When switching branches, we usually first try read-tree to make sure that we do not lose the local changes and then updated the HEAD using update-ref. However, we detached and updated HEAD before these checks, which was quite bad in a repository with local changes. Signed-off-by: Junio C Hamano <junkio@cox.net>
Junio C Hamano committed
Jan 9, 2007 at 20:39 UTC
bfbbb8f8cf8250718ffd028efe179557d29ae72d
1 file changed
+25
-11
git-checkout.sh
+25
-11
@@ -150,21 +150,18 @@ fi
150
# correct, it feels somewhat funny. More importantly, we do not
151
# want "git checkout" nor "git checkout -f" to detach HEAD.
152
153
+detached=
154
+detach_warn=
155
+
156
if test -z "$branch$newbranch" && test "$new" != "$old"
157
then
155
- # NEEDSWORK: we would want to have a command here
156
- # that allows us to detach the HEAD atomically. Perhaps
157
- # something like "git update-ref --detach HEAD $new"
158
- echo "$new" >"$GIT_DIR/HEAD.new" &&
159
- mv "$GIT_DIR/HEAD.new" "$GIT_DIR/HEAD" || die "Cannot detach HEAD"
160
-
158
+ detached="$new"
159
if test -n "$oldbranch"
160
then
163
- echo >&2 "warning: you are not on ANY branch anymore.
161
+ detach_warn="warning: you are not on ANY branch anymore.
162
If you meant to create a new branch from the commit, you need -b to
163
associate a new branch with the wanted checkout. Example:
166
- git checkout -b <new_branch_name> $arg
167
-"
164
+ git checkout -b <new_branch_name> $arg"
165
fi
166
elif test -z "$oldbranch" && test -n "$branch"
167
then
@@ -258,8 +255,25 @@ if [ "$?" -eq 0 ]; then
255
git-update-ref -m "checkout: Created from $new_name" "refs/heads/$newbranch" $new || exit
256
branch="$newbranch"
257
fi
261
- [ "$branch" ] &&
262
- GIT_DIR="$GIT_DIR" git-symbolic-ref HEAD "refs/heads/$branch"
258
+ if test -n "$branch"
259
+ then
260
+ GIT_DIR="$GIT_DIR" git-symbolic-ref HEAD "refs/heads/$branch"
261
+ elif test -n "$detached"
262
+ then
263
+ # NEEDSWORK: we would want a command to detach the HEAD
264
+ # atomically, instead of this handcrafted command sequence.
265
+ # Perhaps:
266
+ # git update-ref --detach HEAD $new
267
+ # or something like that...
268
+ #
269
+ echo "$detached" >"$GIT_DIR/HEAD.new" &&
270
+ mv "$GIT_DIR/HEAD.new" "$GIT_DIR/HEAD" ||
271
+ die "Cannot detach HEAD"
272
+ if test -n "$detach_warn"
273
+ then
274
+ echo >&2 "$detach_warn"
275
+ fi
276
+ fi
277
rm -f "$GIT_DIR/MERGE_HEAD"
278
else
279
exit 1