Skip to content

Commit 91dcdfd

Browse files
author
Linus Torvalds
committed
Make "git checkout" create new branches on demand
In particular, if we check out something that isn't an old branch, it now requires a new branch-name to check the thing out into. So, for example: git checkout -b my-branch v2.6.12 will create the new branch "my-branch", and start it at v2.6.12, while git checkout master will just switch back to the master branch. Of course, if you want to create a new branch "my-branch" and _not_ check it out, you could have done so with just git-rev-parse v2.6.12^0 > .git/refs/heads/my-branch which I think I will codify as "git branch".
1 parent 714fff2 commit 91dcdfd

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

git-checkout-script

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,19 @@ old=$(git-rev-parse HEAD)
55
new=
66
force=
77
branch=
8+
newbranch=
89
while [ "$#" != "0" ]; do
910
arg="$1"
1011
shift
1112
case "$arg" in
13+
"-b")
14+
newbranch="$1"
15+
shift
16+
[ -z "$newbranch" ] &&
17+
die "git checkout: -b needs a branch name"
18+
[ -e "$GIT_DIR/refs/heads/$newbranch" ] &&
19+
die "git checkout: branch $newbranch already exists"
20+
;;
1221
"-f")
1322
force=1
1423
;;
@@ -32,6 +41,16 @@ while [ "$#" != "0" ]; do
3241
done
3342
[ -z "$new" ] && new=$old
3443

44+
#
45+
# If we don't have an old branch that we're switching to,
46+
# and we don't have a new branch name for the target we
47+
# are switching to, then we'd better just be checking out
48+
# what we already had
49+
#
50+
[ -z "$branch$newbranch" ] &&
51+
[ "$new" != "$old" ] &&
52+
die "git checkout: you need to specify a new branch name"
53+
3554
if [ "$force" ]
3655
then
3756
git-read-tree --reset $new &&
@@ -47,6 +66,10 @@ fi
4766
# be based on them, since we re-set the index)
4867
#
4968
if [ "$?" -eq 0 ]; then
69+
if [ "$newbranch" ]; then
70+
echo $new > "$GIT_DIR/refs/heads/$newbranch"
71+
branch="$newbranch"
72+
fi
5073
[ "$branch" ] && ln -sf "refs/heads/$branch" "$GIT_DIR/HEAD"
5174
rm -f "$GIT_DIR/MERGE_HEAD"
5275
fi

0 commit comments

Comments
 (0)