Add git-symbolic-ref
[git.git] / git-branch.sh
1 #!/bin/sh
2
3 . git-sh-setup || die "Not a git archive"
4
5 usage () {
6     echo >&2 "usage: $(basename $0)"' [-d <branch>] | [<branch> [start-point]]
7
8 If no arguments, show available branches and mark current branch with a star.
9 If one argument, create a new branch <branchname> based off of current HEAD.
10 If two arguments, create a new branch <branchname> based off of <start-point>.
11 '
12     exit 1
13 }
14
15 delete_branch () {
16     option="$1" branch_name="$2"
17     headref=$(GIT_DIR="$GIT_DIR" git-symbolic-ref HEAD |
18                sed -e 's|^refs/heads/||')
19     case ",$headref," in
20     ",$branch_name,")
21         die "Cannot delete the branch you are on." ;;
22     ,,)
23         die "What branch are you on anyway?" ;;
24     esac
25     branch=$(cat "$GIT_DIR/refs/heads/$branch_name") &&
26         branch=$(git-rev-parse --verify "$branch^0") ||
27             die "Seriously, what branch are you talking about?"
28     case "$option" in
29     -D)
30         ;;
31     *)
32         mbs=$(git-merge-base -a "$branch" HEAD | tr '\012' ' ')
33         case " $mbs " in
34         *' '$branch' '*)
35             # the merge base of branch and HEAD contains branch --
36             # which means that the HEAD contains everything in the HEAD.
37             ;;
38         *)
39             echo >&2 "The branch '$branch_name' is not a strict subset of your current HEAD.
40 If you are sure you want to delete it, run 'git branch -D $branch_name'."
41             exit 1
42             ;;
43         esac
44         ;;
45     esac
46     rm -f "$GIT_DIR/refs/heads/$branch_name"
47     echo "Deleted branch $branch_name."
48     exit 0
49 }
50
51 while case "$#,$1" in 0,*) break ;; *,-*) ;; *) break ;; esac
52 do
53         case "$1" in
54         -d | -D)
55                 delete_branch "$1" "$2"
56                 exit
57                 ;;
58         --)
59                 shift
60                 break
61                 ;;
62         -*)
63                 usage
64                 ;;
65         esac
66         shift
67 done
68
69 case "$#" in
70 0)
71         headref=$(GIT_DIR="$GIT_DIR" git-symbolic-ref HEAD |
72                   sed -e 's|^refs/heads/||')
73         git-rev-parse --symbolic --all |
74         sed -ne 's|^refs/heads/||p' |
75         sort |
76         while read ref
77         do
78                 if test "$headref" = "$ref"
79                 then
80                         pfx='*'
81                 else
82                         pfx=' '
83                 fi
84                 echo "$pfx $ref"
85         done
86         exit 0 ;;
87 1)
88         head=HEAD ;;
89 2)
90         head="$2^0" ;;
91 esac
92 branchname="$1"
93
94 rev=$(git-rev-parse --verify "$head") || exit
95
96 [ -e "$GIT_DIR/refs/heads/$branchname" ] && die "$branchname already exists"
97
98 echo $rev > "$GIT_DIR/refs/heads/$branchname"