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