Merge branch 'fc/master' into travis-ci
[git] / builtin / branch.c
1 /*
2  * Builtin "git branch"
3  *
4  * Copyright (c) 2006 Kristian Høgsberg <krh@redhat.com>
5  * Based on git-branch.sh by Junio C Hamano.
6  */
7
8 #include "cache.h"
9 #include "color.h"
10 #include "refs.h"
11 #include "commit.h"
12 #include "builtin.h"
13 #include "remote.h"
14 #include "parse-options.h"
15 #include "branch.h"
16 #include "diff.h"
17 #include "revision.h"
18 #include "string-list.h"
19 #include "column.h"
20 #include "utf8.h"
21 #include "wt-status.h"
22
23 static const char * const builtin_branch_usage[] = {
24         N_("git branch [options] [-r | -a] [--merged | --no-merged]"),
25         N_("git branch [options] [-l] [-f] <branchname> [<start-point>]"),
26         N_("git branch [options] [-r] (-d | -D) <branchname>..."),
27         N_("git branch [options] (-m | -M) [<oldbranch>] <newbranch>"),
28         NULL
29 };
30
31 #define REF_LOCAL_BRANCH    0x01
32 #define REF_REMOTE_BRANCH   0x02
33
34 static const char *head;
35 static unsigned char head_sha1[20];
36
37 static int branch_use_color = -1;
38 static char branch_colors[][COLOR_MAXLEN] = {
39         GIT_COLOR_RESET,
40         GIT_COLOR_NORMAL,       /* PLAIN */
41         GIT_COLOR_RED,          /* REMOTE */
42         GIT_COLOR_NORMAL,       /* LOCAL */
43         GIT_COLOR_GREEN,        /* CURRENT */
44         GIT_COLOR_BLUE,         /* UPSTREAM */
45         GIT_COLOR_YELLOW,       /* PUBLISH */
46 };
47 enum color_branch {
48         BRANCH_COLOR_RESET = 0,
49         BRANCH_COLOR_PLAIN = 1,
50         BRANCH_COLOR_REMOTE = 2,
51         BRANCH_COLOR_LOCAL = 3,
52         BRANCH_COLOR_CURRENT = 4,
53         BRANCH_COLOR_UPSTREAM = 5,
54         BRANCH_COLOR_PUBLISH = 6
55 };
56
57 static enum merge_filter {
58         NO_FILTER = 0,
59         SHOW_NOT_MERGED,
60         SHOW_MERGED
61 } merge_filter;
62 static unsigned char merge_filter_ref[20];
63
64 static struct string_list output = STRING_LIST_INIT_DUP;
65 static unsigned int colopts;
66
67 static int parse_branch_color_slot(const char *var, int ofs)
68 {
69         if (!strcasecmp(var+ofs, "plain"))
70                 return BRANCH_COLOR_PLAIN;
71         if (!strcasecmp(var+ofs, "reset"))
72                 return BRANCH_COLOR_RESET;
73         if (!strcasecmp(var+ofs, "remote"))
74                 return BRANCH_COLOR_REMOTE;
75         if (!strcasecmp(var+ofs, "local"))
76                 return BRANCH_COLOR_LOCAL;
77         if (!strcasecmp(var+ofs, "current"))
78                 return BRANCH_COLOR_CURRENT;
79         if (!strcasecmp(var+ofs, "upstream"))
80                 return BRANCH_COLOR_UPSTREAM;
81         if (!strcasecmp(var+ofs, "publish"))
82                 return BRANCH_COLOR_PUBLISH;
83         return -1;
84 }
85
86 static int git_branch_config(const char *var, const char *value, void *cb)
87 {
88         if (starts_with(var, "column."))
89                 return git_column_config(var, value, "branch", &colopts);
90         if (!strcmp(var, "color.branch")) {
91                 branch_use_color = git_config_colorbool(var, value);
92                 return 0;
93         }
94         if (starts_with(var, "color.branch.")) {
95                 int slot = parse_branch_color_slot(var, 13);
96                 if (slot < 0)
97                         return 0;
98                 if (!value)
99                         return config_error_nonbool(var);
100                 color_parse(value, var, branch_colors[slot]);
101                 return 0;
102         }
103         return git_color_default_config(var, value, cb);
104 }
105
106 static const char *branch_get_color(enum color_branch ix)
107 {
108         if (want_color(branch_use_color))
109                 return branch_colors[ix];
110         return "";
111 }
112
113 static int branch_merged(int kind, const char *name,
114                          struct commit *rev, struct commit *head_rev)
115 {
116         /*
117          * This checks whether the merge bases of branch and HEAD (or
118          * the other branch this branch builds upon) contains the
119          * branch, which means that the branch has already been merged
120          * safely to HEAD (or the other branch).
121          */
122         struct commit *reference_rev = NULL;
123         const char *reference_name = NULL;
124         void *reference_name_to_free = NULL;
125         int merged;
126
127         if (kind == REF_LOCAL_BRANCH) {
128                 struct branch *branch = branch_get(name);
129                 unsigned char sha1[20];
130
131                 if (branch &&
132                     branch->merge &&
133                     branch->merge[0] &&
134                     branch->merge[0]->dst &&
135                     (reference_name = reference_name_to_free =
136                      resolve_refdup(branch->merge[0]->dst, sha1, 1, NULL)) != NULL)
137                         reference_rev = lookup_commit_reference(sha1);
138         }
139         if (!reference_rev)
140                 reference_rev = head_rev;
141
142         merged = in_merge_bases(rev, reference_rev);
143
144         /*
145          * After the safety valve is fully redefined to "check with
146          * upstream, if any, otherwise with HEAD", we should just
147          * return the result of the in_merge_bases() above without
148          * any of the following code, but during the transition period,
149          * a gentle reminder is in order.
150          */
151         if ((head_rev != reference_rev) &&
152             in_merge_bases(rev, head_rev) != merged) {
153                 if (merged)
154                         warning(_("deleting branch '%s' that has been merged to\n"
155                                 "         '%s', but not yet merged to HEAD."),
156                                 name, reference_name);
157                 else
158                         warning(_("not deleting branch '%s' that is not yet merged to\n"
159                                 "         '%s', even though it is merged to HEAD."),
160                                 name, reference_name);
161         }
162         free(reference_name_to_free);
163         return merged;
164 }
165
166 static int check_branch_commit(const char *branchname, const char *refname,
167                                unsigned char *sha1, struct commit *head_rev,
168                                int kinds, int force)
169 {
170         struct commit *rev = lookup_commit_reference(sha1);
171         if (!rev) {
172                 error(_("Couldn't look up commit object for '%s'"), refname);
173                 return -1;
174         }
175         if (!force && !branch_merged(kinds, branchname, rev, head_rev)) {
176                 error(_("The branch '%s' is not fully merged.\n"
177                       "If you are sure you want to delete it, "
178                       "run 'git branch -D %s'."), branchname, branchname);
179                 return -1;
180         }
181         return 0;
182 }
183
184 static void delete_branch_config(const char *branchname)
185 {
186         struct strbuf buf = STRBUF_INIT;
187         strbuf_addf(&buf, "branch.%s", branchname);
188         if (git_config_rename_section(buf.buf, NULL) < 0)
189                 warning(_("Update of config-file failed"));
190         strbuf_release(&buf);
191 }
192
193 static int delete_branches(int argc, const char **argv, int force, int kinds,
194                            int quiet)
195 {
196         struct commit *head_rev = NULL;
197         unsigned char sha1[20];
198         char *name = NULL;
199         const char *fmt;
200         int i;
201         int ret = 0;
202         int remote_branch = 0;
203         struct strbuf bname = STRBUF_INIT;
204
205         switch (kinds) {
206         case REF_REMOTE_BRANCH:
207                 fmt = "refs/remotes/%s";
208                 /* For subsequent UI messages */
209                 remote_branch = 1;
210
211                 force = 1;
212                 break;
213         case REF_LOCAL_BRANCH:
214                 fmt = "refs/heads/%s";
215                 break;
216         default:
217                 die(_("cannot use -a with -d"));
218         }
219
220         if (!force) {
221                 head_rev = lookup_commit_reference(head_sha1);
222                 if (!head_rev)
223                         die(_("Couldn't look up commit object for HEAD"));
224         }
225         for (i = 0; i < argc; i++, strbuf_release(&bname)) {
226                 const char *target;
227                 int flags = 0;
228
229                 strbuf_branchname(&bname, argv[i]);
230                 if (kinds == REF_LOCAL_BRANCH && !strcmp(head, bname.buf)) {
231                         error(_("Cannot delete the branch '%s' "
232                               "which you are currently on."), bname.buf);
233                         ret = 1;
234                         continue;
235                 }
236
237                 free(name);
238
239                 name = mkpathdup(fmt, bname.buf);
240                 target = resolve_ref_unsafe(name, sha1, 0, &flags);
241                 if (!target ||
242                     (!(flags & REF_ISSYMREF) && is_null_sha1(sha1))) {
243                         error(remote_branch
244                               ? _("remote branch '%s' not found.")
245                               : _("branch '%s' not found."), bname.buf);
246                         ret = 1;
247                         continue;
248                 }
249
250                 if (!(flags & REF_ISSYMREF) &&
251                     check_branch_commit(bname.buf, name, sha1, head_rev, kinds,
252                                         force)) {
253                         ret = 1;
254                         continue;
255                 }
256
257                 if (delete_ref(name, sha1, REF_NODEREF)) {
258                         error(remote_branch
259                               ? _("Error deleting remote branch '%s'")
260                               : _("Error deleting branch '%s'"),
261                               bname.buf);
262                         ret = 1;
263                         continue;
264                 }
265                 if (!quiet) {
266                         printf(remote_branch
267                                ? _("Deleted remote branch %s (was %s).\n")
268                                : _("Deleted branch %s (was %s).\n"),
269                                bname.buf,
270                                (flags & REF_ISSYMREF)
271                                ? target
272                                : find_unique_abbrev(sha1, DEFAULT_ABBREV));
273                 }
274                 delete_branch_config(bname.buf);
275         }
276
277         free(name);
278
279         return(ret);
280 }
281
282 struct ref_item {
283         char *name;
284         char *dest;
285         unsigned int kind, width;
286         struct commit *commit;
287 };
288
289 struct ref_list {
290         struct rev_info revs;
291         int index, alloc, maxwidth, verbose, abbrev;
292         struct ref_item *list;
293         struct commit_list *with_commit;
294         int kinds;
295 };
296
297 static char *resolve_symref(const char *src, const char *prefix)
298 {
299         unsigned char sha1[20];
300         int flag;
301         const char *dst, *cp;
302
303         dst = resolve_ref_unsafe(src, sha1, 0, &flag);
304         if (!(dst && (flag & REF_ISSYMREF)))
305                 return NULL;
306         if (prefix && (cp = skip_prefix(dst, prefix)))
307                 dst = cp;
308         return xstrdup(dst);
309 }
310
311 struct append_ref_cb {
312         struct ref_list *ref_list;
313         const char **pattern;
314         int ret;
315 };
316
317 static int match_patterns(const char **pattern, const char *refname)
318 {
319         if (!*pattern)
320                 return 1; /* no pattern always matches */
321         while (*pattern) {
322                 if (!fnmatch(*pattern, refname, 0))
323                         return 1;
324                 pattern++;
325         }
326         return 0;
327 }
328
329 static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
330 {
331         struct append_ref_cb *cb = (struct append_ref_cb *)(cb_data);
332         struct ref_list *ref_list = cb->ref_list;
333         struct ref_item *newitem;
334         struct commit *commit;
335         int kind, i;
336         const char *prefix, *orig_refname = refname;
337
338         static struct {
339                 int kind;
340                 const char *prefix;
341                 int pfxlen;
342         } ref_kind[] = {
343                 { REF_LOCAL_BRANCH, "refs/heads/", 11 },
344                 { REF_REMOTE_BRANCH, "refs/remotes/", 13 },
345         };
346
347         /* Detect kind */
348         for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
349                 prefix = ref_kind[i].prefix;
350                 if (strncmp(refname, prefix, ref_kind[i].pfxlen))
351                         continue;
352                 kind = ref_kind[i].kind;
353                 refname += ref_kind[i].pfxlen;
354                 break;
355         }
356         if (ARRAY_SIZE(ref_kind) <= i)
357                 return 0;
358
359         /* Don't add types the caller doesn't want */
360         if ((kind & ref_list->kinds) == 0)
361                 return 0;
362
363         if (!match_patterns(cb->pattern, refname))
364                 return 0;
365
366         commit = NULL;
367         if (ref_list->verbose || ref_list->with_commit || merge_filter != NO_FILTER) {
368                 commit = lookup_commit_reference_gently(sha1, 1);
369                 if (!commit) {
370                         cb->ret = error(_("branch '%s' does not point at a commit"), refname);
371                         return 0;
372                 }
373
374                 /* Filter with with_commit if specified */
375                 if (!is_descendant_of(commit, ref_list->with_commit))
376                         return 0;
377
378                 if (merge_filter != NO_FILTER)
379                         add_pending_object(&ref_list->revs,
380                                            (struct object *)commit, refname);
381         }
382
383         ALLOC_GROW(ref_list->list, ref_list->index + 1, ref_list->alloc);
384
385         /* Record the new item */
386         newitem = &(ref_list->list[ref_list->index++]);
387         newitem->name = xstrdup(refname);
388         newitem->kind = kind;
389         newitem->commit = commit;
390         newitem->width = utf8_strwidth(refname);
391         newitem->dest = resolve_symref(orig_refname, prefix);
392         /* adjust for "remotes/" */
393         if (newitem->kind == REF_REMOTE_BRANCH &&
394             ref_list->kinds != REF_REMOTE_BRANCH)
395                 newitem->width += 8;
396         if (newitem->width > ref_list->maxwidth)
397                 ref_list->maxwidth = newitem->width;
398
399         return 0;
400 }
401
402 static void free_ref_list(struct ref_list *ref_list)
403 {
404         int i;
405
406         for (i = 0; i < ref_list->index; i++) {
407                 free(ref_list->list[i].name);
408                 free(ref_list->list[i].dest);
409         }
410         free(ref_list->list);
411 }
412
413 static int ref_cmp(const void *r1, const void *r2)
414 {
415         struct ref_item *c1 = (struct ref_item *)(r1);
416         struct ref_item *c2 = (struct ref_item *)(r2);
417
418         if (c1->kind != c2->kind)
419                 return c1->kind - c2->kind;
420         return strcmp(c1->name, c2->name);
421 }
422
423 static void fill_tracking_info(struct strbuf *stat, const char *branch_name,
424                 int show_tracking)
425 {
426         int ours, theirs;
427         char *ref = NULL;
428         struct branch *branch = branch_get(branch_name);
429         struct strbuf fancy = STRBUF_INIT;
430         int upstream_is_gone = 0;
431
432         if (!branch)
433                 return;
434
435         if (show_tracking) {
436                 switch (stat_tracking_info(branch, &ours, &theirs)) {
437                 case 0:
438                         /* no base */
439                         return;
440                 case -1:
441                         /* with "gone" base */
442                         upstream_is_gone = 1;
443                         break;
444                 default:
445                         /* with base */
446                         break;
447                 }
448         } else {
449                 ours = theirs = 0;
450         }
451
452         if (branch->merge && branch->merge[0] && branch->merge[0]->dst) {
453                 ref = shorten_unambiguous_ref(branch->merge[0]->dst, 0);
454                 if (want_color(branch_use_color))
455                         strbuf_addf(&fancy, "%s%s%s",
456                                         branch_get_color(BRANCH_COLOR_UPSTREAM),
457                                         ref, branch_get_color(BRANCH_COLOR_RESET));
458                 else
459                         strbuf_addstr(&fancy, ref);
460         }
461         if (branch->push.dst) {
462                 ref = shorten_unambiguous_ref(branch->push.dst, 0);
463                 if (fancy.len)
464                         strbuf_addstr(&fancy, ", ");
465                 if (want_color(branch_use_color))
466                         strbuf_addf(&fancy, "%s%s%s",
467                                         branch_get_color(BRANCH_COLOR_PUBLISH),
468                                         ref, branch_get_color(BRANCH_COLOR_RESET));
469                 else
470                         strbuf_addstr(&fancy, ref);
471         }
472         if (!fancy.len)
473                 return;
474
475         if (upstream_is_gone)
476                 strbuf_addf(stat, _("[%s: gone]"), fancy.buf);
477         else if (!ours && !theirs)
478                 strbuf_addf(stat, _("[%s]"), fancy.buf);
479         else if (!ours)
480                 strbuf_addf(stat, _("[%s: behind %d]"), fancy.buf, theirs);
481         else if (!theirs)
482                 strbuf_addf(stat, _("[%s: ahead %d]"), fancy.buf, ours);
483         else
484                 strbuf_addf(stat, _("[%s: ahead %d, behind %d]"),
485                             fancy.buf, ours, theirs);
486
487         strbuf_release(&fancy);
488         strbuf_addch(stat, ' ');
489         free(ref);
490 }
491
492 static int matches_merge_filter(struct commit *commit)
493 {
494         int is_merged;
495
496         if (merge_filter == NO_FILTER)
497                 return 1;
498
499         is_merged = !!(commit->object.flags & UNINTERESTING);
500         return (is_merged == (merge_filter == SHOW_MERGED));
501 }
502
503 static void add_verbose_info(struct strbuf *out, struct ref_item *item,
504                              int verbose, int abbrev)
505 {
506         struct strbuf subject = STRBUF_INIT, stat = STRBUF_INIT;
507         const char *sub = _(" **** invalid ref ****");
508         struct commit *commit = item->commit;
509
510         if (!parse_commit(commit)) {
511                 pp_commit_easy(CMIT_FMT_ONELINE, commit, &subject);
512                 sub = subject.buf;
513         }
514
515         if (item->kind == REF_LOCAL_BRANCH)
516                 fill_tracking_info(&stat, item->name, verbose > 1);
517
518         strbuf_addf(out, " %s %s%s",
519                 find_unique_abbrev(item->commit->object.sha1, abbrev),
520                 stat.buf, sub);
521         strbuf_release(&stat);
522         strbuf_release(&subject);
523 }
524
525 static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
526                            int abbrev, int current, char *prefix)
527 {
528         char c;
529         int color;
530         struct commit *commit = item->commit;
531         struct strbuf out = STRBUF_INIT, name = STRBUF_INIT;
532
533         if (!matches_merge_filter(commit))
534                 return;
535
536         switch (item->kind) {
537         case REF_LOCAL_BRANCH:
538                 color = BRANCH_COLOR_LOCAL;
539                 break;
540         case REF_REMOTE_BRANCH:
541                 color = BRANCH_COLOR_REMOTE;
542                 break;
543         default:
544                 color = BRANCH_COLOR_PLAIN;
545                 break;
546         }
547
548         c = ' ';
549         if (current) {
550                 c = '*';
551                 color = BRANCH_COLOR_CURRENT;
552         }
553
554         strbuf_addf(&name, "%s%s", prefix, item->name);
555         if (verbose) {
556                 int utf8_compensation = strlen(name.buf) - utf8_strwidth(name.buf);
557                 strbuf_addf(&out, "%c %s%-*s%s", c, branch_get_color(color),
558                             maxwidth + utf8_compensation, name.buf,
559                             branch_get_color(BRANCH_COLOR_RESET));
560         } else
561                 strbuf_addf(&out, "%c %s%s%s", c, branch_get_color(color),
562                             name.buf, branch_get_color(BRANCH_COLOR_RESET));
563
564         if (item->dest)
565                 strbuf_addf(&out, " -> %s", item->dest);
566         else if (verbose)
567                 /* " f7c0c00 [ahead 58, behind 197] vcs-svn: drop obj_pool.h" */
568                 add_verbose_info(&out, item, verbose, abbrev);
569         if (column_active(colopts)) {
570                 assert(!verbose && "--column and --verbose are incompatible");
571                 string_list_append(&output, out.buf);
572         } else {
573                 printf("%s\n", out.buf);
574         }
575         strbuf_release(&name);
576         strbuf_release(&out);
577 }
578
579 static int calc_maxwidth(struct ref_list *refs)
580 {
581         int i, w = 0;
582         for (i = 0; i < refs->index; i++) {
583                 if (!matches_merge_filter(refs->list[i].commit))
584                         continue;
585                 if (refs->list[i].width > w)
586                         w = refs->list[i].width;
587         }
588         return w;
589 }
590
591 static char *get_head_description(void)
592 {
593         struct strbuf desc = STRBUF_INIT;
594         struct wt_status_state state;
595         memset(&state, 0, sizeof(state));
596         wt_status_get_state(&state, 1);
597         if (state.rebase_in_progress ||
598             state.rebase_interactive_in_progress)
599                 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
600                             state.branch);
601         else if (state.bisect_in_progress)
602                 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
603                             state.branch);
604         else if (state.detached_from)
605                 strbuf_addf(&desc, _("(detached from %s)"),
606                             state.detached_from);
607         else
608                 strbuf_addstr(&desc, _("(no branch)"));
609         free(state.branch);
610         free(state.onto);
611         free(state.detached_from);
612         return strbuf_detach(&desc, NULL);
613 }
614
615 static void show_detached(struct ref_list *ref_list)
616 {
617         struct commit *head_commit = lookup_commit_reference_gently(head_sha1, 1);
618
619         if (head_commit && is_descendant_of(head_commit, ref_list->with_commit)) {
620                 struct ref_item item;
621                 item.name = get_head_description();
622                 item.width = utf8_strwidth(item.name);
623                 item.kind = REF_LOCAL_BRANCH;
624                 item.dest = NULL;
625                 item.commit = head_commit;
626                 if (item.width > ref_list->maxwidth)
627                         ref_list->maxwidth = item.width;
628                 print_ref_item(&item, ref_list->maxwidth, ref_list->verbose, ref_list->abbrev, 1, "");
629                 free(item.name);
630         }
631 }
632
633 static int print_ref_list(int kinds, int detached, int verbose, int abbrev, struct commit_list *with_commit, const char **pattern)
634 {
635         int i;
636         struct append_ref_cb cb;
637         struct ref_list ref_list;
638
639         memset(&ref_list, 0, sizeof(ref_list));
640         ref_list.kinds = kinds;
641         ref_list.verbose = verbose;
642         ref_list.abbrev = abbrev;
643         ref_list.with_commit = with_commit;
644         if (merge_filter != NO_FILTER)
645                 init_revisions(&ref_list.revs, NULL);
646         cb.ref_list = &ref_list;
647         cb.pattern = pattern;
648         cb.ret = 0;
649         for_each_rawref(append_ref, &cb);
650         if (merge_filter != NO_FILTER) {
651                 struct commit *filter;
652                 filter = lookup_commit_reference_gently(merge_filter_ref, 0);
653                 if (!filter)
654                         die(_("object '%s' does not point to a commit"),
655                             sha1_to_hex(merge_filter_ref));
656
657                 filter->object.flags |= UNINTERESTING;
658                 add_pending_object(&ref_list.revs,
659                                    (struct object *) filter, "");
660                 ref_list.revs.limited = 1;
661                 prepare_revision_walk(&ref_list.revs);
662                 if (verbose)
663                         ref_list.maxwidth = calc_maxwidth(&ref_list);
664         }
665
666         qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
667
668         detached = (detached && (kinds & REF_LOCAL_BRANCH));
669         if (detached && match_patterns(pattern, "HEAD"))
670                 show_detached(&ref_list);
671
672         for (i = 0; i < ref_list.index; i++) {
673                 int current = !detached &&
674                         (ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
675                         !strcmp(ref_list.list[i].name, head);
676                 char *prefix = (kinds != REF_REMOTE_BRANCH &&
677                                 ref_list.list[i].kind == REF_REMOTE_BRANCH)
678                                 ? "remotes/" : "";
679                 print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
680                                abbrev, current, prefix);
681         }
682
683         free_ref_list(&ref_list);
684
685         if (cb.ret)
686                 error(_("some refs could not be read"));
687
688         return cb.ret;
689 }
690
691 static void rename_branch(const char *oldname, const char *newname, int force)
692 {
693         struct strbuf oldref = STRBUF_INIT, newref = STRBUF_INIT, logmsg = STRBUF_INIT;
694         struct strbuf oldsection = STRBUF_INIT, newsection = STRBUF_INIT;
695         int recovery = 0;
696         int clobber_head_ok;
697
698         if (!oldname)
699                 die(_("cannot rename the current branch while not on any."));
700
701         if (strbuf_check_branch_ref(&oldref, oldname)) {
702                 /*
703                  * Bad name --- this could be an attempt to rename a
704                  * ref that we used to allow to be created by accident.
705                  */
706                 if (ref_exists(oldref.buf))
707                         recovery = 1;
708                 else
709                         die(_("Invalid branch name: '%s'"), oldname);
710         }
711
712         /*
713          * A command like "git branch -M currentbranch currentbranch" cannot
714          * cause the worktree to become inconsistent with HEAD, so allow it.
715          */
716         clobber_head_ok = !strcmp(oldname, newname);
717
718         validate_new_branchname(newname, &newref, force, clobber_head_ok);
719
720         strbuf_addf(&logmsg, "Branch: renamed %s to %s",
721                  oldref.buf, newref.buf);
722
723         if (rename_ref(oldref.buf, newref.buf, logmsg.buf))
724                 die(_("Branch rename failed"));
725         strbuf_release(&logmsg);
726
727         if (recovery)
728                 warning(_("Renamed a misnamed branch '%s' away"), oldref.buf + 11);
729
730         /* no need to pass logmsg here as HEAD didn't really move */
731         if (!strcmp(oldname, head) && create_symref("HEAD", newref.buf, NULL))
732                 die(_("Branch renamed to %s, but HEAD is not updated!"), newname);
733
734         strbuf_addf(&oldsection, "branch.%s", oldref.buf + 11);
735         strbuf_release(&oldref);
736         strbuf_addf(&newsection, "branch.%s", newref.buf + 11);
737         strbuf_release(&newref);
738         if (git_config_rename_section(oldsection.buf, newsection.buf) < 0)
739                 die(_("Branch is renamed, but update of config-file failed"));
740         strbuf_release(&oldsection);
741         strbuf_release(&newsection);
742 }
743
744 static int opt_parse_merge_filter(const struct option *opt, const char *arg, int unset)
745 {
746         merge_filter = ((opt->long_name[0] == 'n')
747                         ? SHOW_NOT_MERGED
748                         : SHOW_MERGED);
749         if (unset)
750                 merge_filter = SHOW_NOT_MERGED; /* b/c for --no-merged */
751         if (!arg)
752                 arg = "HEAD";
753         if (get_sha1(arg, merge_filter_ref))
754                 die(_("malformed object name %s"), arg);
755         return 0;
756 }
757
758 static const char edit_description[] = "BRANCH_DESCRIPTION";
759
760 static int edit_branch_description(const char *branch_name)
761 {
762         FILE *fp;
763         int status;
764         struct strbuf buf = STRBUF_INIT;
765         struct strbuf name = STRBUF_INIT;
766
767         read_branch_desc(&buf, branch_name);
768         if (!buf.len || buf.buf[buf.len-1] != '\n')
769                 strbuf_addch(&buf, '\n');
770         strbuf_commented_addf(&buf,
771                     "Please edit the description for the branch\n"
772                     "  %s\n"
773                     "Lines starting with '%c' will be stripped.\n",
774                     branch_name, comment_line_char);
775         fp = fopen(git_path(edit_description), "w");
776         if ((fwrite(buf.buf, 1, buf.len, fp) < buf.len) || fclose(fp)) {
777                 strbuf_release(&buf);
778                 return error(_("could not write branch description template: %s"),
779                              strerror(errno));
780         }
781         strbuf_reset(&buf);
782         if (launch_editor(git_path(edit_description), &buf, NULL)) {
783                 strbuf_release(&buf);
784                 return -1;
785         }
786         stripspace(&buf, 1);
787
788         strbuf_addf(&name, "branch.%s.description", branch_name);
789         status = git_config_set(name.buf, buf.len ? buf.buf : NULL);
790         strbuf_release(&name);
791         strbuf_release(&buf);
792
793         return status;
794 }
795
796 int cmd_branch(int argc, const char **argv, const char *prefix)
797 {
798         int delete = 0, rename = 0, force_create = 0, list = 0;
799         int verbose = 0, abbrev = -1, detached = 0;
800         int reflog = 0, edit_description = 0;
801         int quiet = 0, unset_upstream = 0, unset_publish = 0;
802         const char *new_upstream = NULL, *publish = NULL;
803         enum branch_track track;
804         int kinds = REF_LOCAL_BRANCH;
805         struct commit_list *with_commit = NULL;
806
807         struct option options[] = {
808                 OPT_GROUP(N_("Generic options")),
809                 OPT__VERBOSE(&verbose,
810                         N_("show hash and subject, give twice for upstream branch")),
811                 OPT__QUIET(&quiet, N_("suppress informational messages")),
812                 OPT_SET_INT('t', "track",  &track, N_("set up tracking mode (see git-pull(1))"),
813                         BRANCH_TRACK_EXPLICIT),
814                 OPT_SET_INT( 0, "set-upstream",  &track, N_("change upstream info"),
815                         BRANCH_TRACK_OVERRIDE),
816                 OPT_STRING('u', "set-upstream-to", &new_upstream, "upstream", "change the upstream info"),
817                 OPT_STRING('p', "set-publish-to", &publish, "publish", "change the publish info"),
818                 OPT_BOOL(0, "unset-upstream", &unset_upstream, "Unset the upstream info"),
819                 OPT_BOOL(0, "unset-publish", &unset_publish, "Unset the publish info"),
820                 OPT__COLOR(&branch_use_color, N_("use colored output")),
821                 OPT_SET_INT('r', "remotes",     &kinds, N_("act on remote-tracking branches"),
822                         REF_REMOTE_BRANCH),
823                 {
824                         OPTION_CALLBACK, 0, "contains", &with_commit, N_("commit"),
825                         N_("print only branches that contain the commit"),
826                         PARSE_OPT_LASTARG_DEFAULT,
827                         parse_opt_with_commit, (intptr_t)"HEAD",
828                 },
829                 {
830                         OPTION_CALLBACK, 0, "with", &with_commit, N_("commit"),
831                         N_("print only branches that contain the commit"),
832                         PARSE_OPT_HIDDEN | PARSE_OPT_LASTARG_DEFAULT,
833                         parse_opt_with_commit, (intptr_t) "HEAD",
834                 },
835                 OPT__ABBREV(&abbrev),
836
837                 OPT_GROUP(N_("Specific git-branch actions:")),
838                 OPT_SET_INT('a', "all", &kinds, N_("list both remote-tracking and local branches"),
839                         REF_REMOTE_BRANCH | REF_LOCAL_BRANCH),
840                 OPT_BIT('d', "delete", &delete, N_("delete fully merged branch"), 1),
841                 OPT_BIT('D', NULL, &delete, N_("delete branch (even if not merged)"), 2),
842                 OPT_BIT('m', "move", &rename, N_("move/rename a branch and its reflog"), 1),
843                 OPT_BIT('M', NULL, &rename, N_("move/rename a branch, even if target exists"), 2),
844                 OPT_BOOL(0, "list", &list, N_("list branch names")),
845                 OPT_BOOL('l', "create-reflog", &reflog, N_("create the branch's reflog")),
846                 OPT_BOOL(0, "edit-description", &edit_description,
847                          N_("edit the description for the branch")),
848                 OPT__FORCE(&force_create, N_("force creation (when already exists)")),
849                 {
850                         OPTION_CALLBACK, 0, "no-merged", &merge_filter_ref,
851                         N_("commit"), N_("print only not merged branches"),
852                         PARSE_OPT_LASTARG_DEFAULT | PARSE_OPT_NONEG,
853                         opt_parse_merge_filter, (intptr_t) "HEAD",
854                 },
855                 {
856                         OPTION_CALLBACK, 0, "merged", &merge_filter_ref,
857                         N_("commit"), N_("print only merged branches"),
858                         PARSE_OPT_LASTARG_DEFAULT | PARSE_OPT_NONEG,
859                         opt_parse_merge_filter, (intptr_t) "HEAD",
860                 },
861                 OPT_COLUMN(0, "column", &colopts, N_("list branches in columns")),
862                 OPT_END(),
863         };
864
865         if (argc == 2 && !strcmp(argv[1], "-h"))
866                 usage_with_options(builtin_branch_usage, options);
867
868         git_config(git_branch_config, NULL);
869
870         track = git_branch_track;
871
872         head = resolve_refdup("HEAD", head_sha1, 0, NULL);
873         if (!head)
874                 die(_("Failed to resolve HEAD as a valid ref."));
875         if (!strcmp(head, "HEAD")) {
876                 detached = 1;
877         } else {
878                 if (!starts_with(head, "refs/heads/"))
879                         die(_("HEAD not found below refs/heads!"));
880                 head += 11;
881         }
882         hashcpy(merge_filter_ref, head_sha1);
883
884
885         argc = parse_options(argc, argv, prefix, options, builtin_branch_usage,
886                              0);
887
888         if (!delete && !rename && !edit_description && !new_upstream && !publish &&
889             !unset_upstream && !unset_publish && argc == 0)
890                 list = 1;
891
892         if (with_commit || merge_filter != NO_FILTER)
893                 list = 1;
894
895         if (!!delete + !!rename + !!force_create + !!new_upstream + !!publish +
896             list + unset_upstream + unset_publish > 1)
897                 usage_with_options(builtin_branch_usage, options);
898
899         if (abbrev == -1)
900                 abbrev = DEFAULT_ABBREV;
901         finalize_colopts(&colopts, -1);
902         if (verbose) {
903                 if (explicitly_enable_column(colopts))
904                         die(_("--column and --verbose are incompatible"));
905                 colopts = 0;
906         }
907
908         if (delete) {
909                 if (!argc)
910                         die(_("branch name required"));
911                 return delete_branches(argc, argv, delete > 1, kinds, quiet);
912         } else if (list) {
913                 int ret = print_ref_list(kinds, detached, verbose, abbrev,
914                                          with_commit, argv);
915                 print_columns(&output, colopts, NULL);
916                 string_list_clear(&output, 0);
917                 return ret;
918         }
919         else if (edit_description) {
920                 const char *branch_name;
921                 struct strbuf branch_ref = STRBUF_INIT;
922
923                 if (!argc) {
924                         if (detached)
925                                 die(_("Cannot give description to detached HEAD"));
926                         branch_name = head;
927                 } else if (argc == 1)
928                         branch_name = argv[0];
929                 else
930                         die(_("cannot edit description of more than one branch"));
931
932                 strbuf_addf(&branch_ref, "refs/heads/%s", branch_name);
933                 if (!ref_exists(branch_ref.buf)) {
934                         strbuf_release(&branch_ref);
935
936                         if (!argc)
937                                 return error(_("No commit on branch '%s' yet."),
938                                              branch_name);
939                         else
940                                 return error(_("No branch named '%s'."),
941                                              branch_name);
942                 }
943                 strbuf_release(&branch_ref);
944
945                 if (edit_branch_description(branch_name))
946                         return 1;
947         } else if (rename) {
948                 if (!argc)
949                         die(_("branch name required"));
950                 else if (argc == 1)
951                         rename_branch(head, argv[0], rename > 1);
952                 else if (argc == 2)
953                         rename_branch(argv[0], argv[1], rename > 1);
954                 else
955                         die(_("too many branches for a rename operation"));
956         } else if (new_upstream) {
957                 struct branch *branch = branch_get(argv[0]);
958
959                 if (argc > 1)
960                         die(_("too many branches to set new upstream"));
961
962                 if (!branch) {
963                         if (!argc || !strcmp(argv[0], "HEAD"))
964                                 die(_("could not set upstream of HEAD to %s when "
965                                       "it does not point to any branch."),
966                                     new_upstream);
967                         die(_("no such branch '%s'"), argv[0]);
968                 }
969
970                 if (!ref_exists(branch->refname))
971                         die(_("branch '%s' does not exist"), branch->name);
972
973                 /*
974                  * create_branch takes care of setting up the tracking
975                  * info and making sure new_upstream is correct
976                  */
977                 create_branch(head, branch->name, new_upstream, 0, 0, 0, quiet, BRANCH_TRACK_OVERRIDE);
978         } else if (unset_upstream) {
979                 struct branch *branch = branch_get(argv[0]);
980                 struct strbuf buf = STRBUF_INIT;
981
982                 if (argc > 1)
983                         die(_("too many branches to unset upstream"));
984
985                 if (!branch) {
986                         if (!argc || !strcmp(argv[0], "HEAD"))
987                                 die(_("could not unset upstream of HEAD when "
988                                       "it does not point to any branch."));
989                         die(_("no such branch '%s'"), argv[0]);
990                 }
991
992                 if (!branch_has_merge_config(branch))
993                         die(_("Branch '%s' has no upstream information"), branch->name);
994
995                 strbuf_addf(&buf, "branch.%s.remote", branch->name);
996                 git_config_set_multivar(buf.buf, NULL, NULL, 1);
997                 strbuf_reset(&buf);
998                 strbuf_addf(&buf, "branch.%s.merge", branch->name);
999                 git_config_set_multivar(buf.buf, NULL, NULL, 1);
1000                 strbuf_release(&buf);
1001         } else if (publish) {
1002                 struct branch *branch = branch_get(argv[0]);
1003                 char *real_ref = NULL;
1004                 unsigned char sha1[20];
1005
1006                 if (argc > 1)
1007                         die(_("too many branches to set new publish branch"));
1008
1009                 if (!branch) {
1010                         if (!argc || !strcmp(argv[0], "HEAD"))
1011                                 die(_("could not set publish branch of HEAD when "
1012                                       "it does not point to any branch."));
1013                         die(_("no such branch '%s'"), argv[0]);
1014                 }
1015
1016                 if (!ref_exists(branch->refname))
1017                         die(_("branch '%s' does not exist"), branch->name);
1018
1019                 if (dwim_ref(publish, strlen(publish), sha1, &real_ref) != 1 ||
1020                                 setup_publish(branch->name, real_ref))
1021                         die(_("Cannot setup publish branch to '%s'."), publish);
1022         } else if (unset_publish) {
1023                 struct branch *branch = branch_get(argv[0]);
1024                 struct strbuf buf = STRBUF_INIT;
1025
1026                 if (argc > 1)
1027                         die(_("too many branches to unset publish branch"));
1028
1029                 if (!branch) {
1030                         if (!argc || !strcmp(argv[0], "HEAD"))
1031                                 die(_("could not unset publish branch of HEAD when "
1032                                       "it does not point to any branch."));
1033                         die(_("no such branch '%s'"), argv[0]);
1034                 }
1035
1036                 if (!branch->push_name)
1037                         die(_("Branch '%s' has no publish information"), branch->name);
1038
1039                 strbuf_addf(&buf, "branch.%s.pushremote", branch->name);
1040                 git_config_set_multivar(buf.buf, NULL, NULL, 1);
1041                 strbuf_reset(&buf);
1042                 strbuf_addf(&buf, "branch.%s.push", branch->name);
1043                 git_config_set_multivar(buf.buf, NULL, NULL, 1);
1044                 strbuf_release(&buf);
1045         } else if (argc > 0 && argc <= 2) {
1046                 struct branch *branch = branch_get(argv[0]);
1047                 int branch_existed = 0, remote_tracking = 0;
1048                 struct strbuf buf = STRBUF_INIT;
1049
1050                 if (!strcmp(argv[0], "HEAD"))
1051                         die(_("it does not make sense to create 'HEAD' manually"));
1052
1053                 if (!branch)
1054                         die(_("no such branch '%s'"), argv[0]);
1055
1056                 if (kinds != REF_LOCAL_BRANCH)
1057                         die(_("-a and -r options to 'git branch' do not make sense with a branch name"));
1058
1059                 if (track == BRANCH_TRACK_OVERRIDE)
1060                         fprintf(stderr, _("The --set-upstream flag is deprecated and will be removed. Consider using --track or --set-upstream-to\n"));
1061
1062                 strbuf_addf(&buf, "refs/remotes/%s", branch->name);
1063                 remote_tracking = ref_exists(buf.buf);
1064                 strbuf_release(&buf);
1065
1066                 branch_existed = ref_exists(branch->refname);
1067                 create_branch(head, argv[0], (argc == 2) ? argv[1] : head,
1068                               force_create, reflog, 0, quiet, track);
1069
1070                 /*
1071                  * We only show the instructions if the user gave us
1072                  * one branch which doesn't exist locally, but is the
1073                  * name of a remote-tracking branch.
1074                  */
1075                 if (argc == 1 && track == BRANCH_TRACK_OVERRIDE &&
1076                     !branch_existed && remote_tracking) {
1077                         fprintf(stderr, _("\nIf you wanted to make '%s' track '%s', do this:\n\n"), head, branch->name);
1078                         fprintf(stderr, _("    git branch -d %s\n"), branch->name);
1079                         fprintf(stderr, _("    git branch --set-upstream-to %s\n"), branch->name);
1080                 }
1081
1082         } else
1083                 usage_with_options(builtin_branch_usage, options);
1084
1085         return 0;
1086 }