Teach the "@{-1} syntax to "git branch"
[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
19 static const char * const builtin_branch_usage[] = {
20         "git branch [options] [-r | -a] [--merged | --no-merged]",
21         "git branch [options] [-l] [-f] <branchname> [<start-point>]",
22         "git branch [options] [-r] (-d | -D) <branchname>",
23         "git branch [options] (-m | -M) [<oldbranch>] <newbranch>",
24         NULL
25 };
26
27 #define REF_LOCAL_BRANCH    0x01
28 #define REF_REMOTE_BRANCH   0x02
29
30 static const char *head;
31 static unsigned char head_sha1[20];
32
33 static int branch_use_color = -1;
34 static char branch_colors[][COLOR_MAXLEN] = {
35         "\033[m",       /* reset */
36         "",             /* PLAIN (normal) */
37         "\033[31m",     /* REMOTE (red) */
38         "",             /* LOCAL (normal) */
39         "\033[32m",     /* CURRENT (green) */
40 };
41 enum color_branch {
42         COLOR_BRANCH_RESET = 0,
43         COLOR_BRANCH_PLAIN = 1,
44         COLOR_BRANCH_REMOTE = 2,
45         COLOR_BRANCH_LOCAL = 3,
46         COLOR_BRANCH_CURRENT = 4,
47 };
48
49 static enum merge_filter {
50         NO_FILTER = 0,
51         SHOW_NOT_MERGED,
52         SHOW_MERGED,
53 } merge_filter;
54 static unsigned char merge_filter_ref[20];
55
56 static int parse_branch_color_slot(const char *var, int ofs)
57 {
58         if (!strcasecmp(var+ofs, "plain"))
59                 return COLOR_BRANCH_PLAIN;
60         if (!strcasecmp(var+ofs, "reset"))
61                 return COLOR_BRANCH_RESET;
62         if (!strcasecmp(var+ofs, "remote"))
63                 return COLOR_BRANCH_REMOTE;
64         if (!strcasecmp(var+ofs, "local"))
65                 return COLOR_BRANCH_LOCAL;
66         if (!strcasecmp(var+ofs, "current"))
67                 return COLOR_BRANCH_CURRENT;
68         die("bad config variable '%s'", var);
69 }
70
71 static int git_branch_config(const char *var, const char *value, void *cb)
72 {
73         if (!strcmp(var, "color.branch")) {
74                 branch_use_color = git_config_colorbool(var, value, -1);
75                 return 0;
76         }
77         if (!prefixcmp(var, "color.branch.")) {
78                 int slot = parse_branch_color_slot(var, 13);
79                 if (!value)
80                         return config_error_nonbool(var);
81                 color_parse(value, var, branch_colors[slot]);
82                 return 0;
83         }
84         return git_color_default_config(var, value, cb);
85 }
86
87 static const char *branch_get_color(enum color_branch ix)
88 {
89         if (branch_use_color > 0)
90                 return branch_colors[ix];
91         return "";
92 }
93
94 static int delete_branches(int argc, const char **argv, int force, int kinds)
95 {
96         struct commit *rev, *head_rev = head_rev;
97         unsigned char sha1[20];
98         char *name = NULL;
99         const char *fmt, *remote;
100         int i;
101         int ret = 0;
102         struct strbuf bname = STRBUF_INIT;
103
104         switch (kinds) {
105         case REF_REMOTE_BRANCH:
106                 fmt = "refs/remotes/%s";
107                 remote = "remote ";
108                 force = 1;
109                 break;
110         case REF_LOCAL_BRANCH:
111                 fmt = "refs/heads/%s";
112                 remote = "";
113                 break;
114         default:
115                 die("cannot use -a with -d");
116         }
117
118         if (!force) {
119                 head_rev = lookup_commit_reference(head_sha1);
120                 if (!head_rev)
121                         die("Couldn't look up commit object for HEAD");
122         }
123         for (i = 0; i < argc; i++, strbuf_release(&bname)) {
124                 int len = strlen(argv[i]);
125
126                 if (interpret_nth_last_branch(argv[i], &bname) != len)
127                         strbuf_add(&bname, argv[i], len);
128
129                 if (kinds == REF_LOCAL_BRANCH && !strcmp(head, bname.buf)) {
130                         error("Cannot delete the branch '%s' "
131                               "which you are currently on.", bname.buf);
132                         ret = 1;
133                         continue;
134                 }
135
136                 free(name);
137
138                 name = xstrdup(mkpath(fmt, bname.buf));
139                 if (!resolve_ref(name, sha1, 1, NULL)) {
140                         error("%sbranch '%s' not found.",
141                                         remote, bname.buf);
142                         ret = 1;
143                         continue;
144                 }
145
146                 rev = lookup_commit_reference(sha1);
147                 if (!rev) {
148                         error("Couldn't look up commit object for '%s'", name);
149                         ret = 1;
150                         continue;
151                 }
152
153                 /* This checks whether the merge bases of branch and
154                  * HEAD contains branch -- which means that the HEAD
155                  * contains everything in both.
156                  */
157
158                 if (!force &&
159                     !in_merge_bases(rev, &head_rev, 1)) {
160                         error("The branch '%s' is not an ancestor of "
161                               "your current HEAD.\n"
162                               "If you are sure you want to delete it, "
163                               "run 'git branch -D %s'.", bname.buf, bname.buf);
164                         ret = 1;
165                         continue;
166                 }
167
168                 if (delete_ref(name, sha1, 0)) {
169                         error("Error deleting %sbranch '%s'", remote,
170                               bname.buf);
171                         ret = 1;
172                 } else {
173                         struct strbuf buf = STRBUF_INIT;
174                         printf("Deleted %sbranch %s (%s).\n", remote,
175                                bname.buf,
176                                find_unique_abbrev(sha1, DEFAULT_ABBREV));
177                         strbuf_addf(&buf, "branch.%s", bname.buf);
178                         if (git_config_rename_section(buf.buf, NULL) < 0)
179                                 warning("Update of config-file failed");
180                         strbuf_release(&buf);
181                 }
182         }
183
184         free(name);
185
186         return(ret);
187 }
188
189 struct ref_item {
190         char *name;
191         unsigned int kind;
192         struct commit *commit;
193 };
194
195 struct ref_list {
196         struct rev_info revs;
197         int index, alloc, maxwidth;
198         struct ref_item *list;
199         struct commit_list *with_commit;
200         int kinds;
201 };
202
203 static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
204 {
205         struct ref_list *ref_list = (struct ref_list*)(cb_data);
206         struct ref_item *newitem;
207         struct commit *commit;
208         int kind;
209         int len;
210
211         /* Detect kind */
212         if (!prefixcmp(refname, "refs/heads/")) {
213                 kind = REF_LOCAL_BRANCH;
214                 refname += 11;
215         } else if (!prefixcmp(refname, "refs/remotes/")) {
216                 kind = REF_REMOTE_BRANCH;
217                 refname += 13;
218         } else
219                 return 0;
220
221         commit = lookup_commit_reference_gently(sha1, 1);
222         if (!commit)
223                 return error("branch '%s' does not point at a commit", refname);
224
225         /* Filter with with_commit if specified */
226         if (!is_descendant_of(commit, ref_list->with_commit))
227                 return 0;
228
229         /* Don't add types the caller doesn't want */
230         if ((kind & ref_list->kinds) == 0)
231                 return 0;
232
233         if (merge_filter != NO_FILTER)
234                 add_pending_object(&ref_list->revs,
235                                    (struct object *)commit, refname);
236
237         /* Resize buffer */
238         if (ref_list->index >= ref_list->alloc) {
239                 ref_list->alloc = alloc_nr(ref_list->alloc);
240                 ref_list->list = xrealloc(ref_list->list,
241                                 ref_list->alloc * sizeof(struct ref_item));
242         }
243
244         /* Record the new item */
245         newitem = &(ref_list->list[ref_list->index++]);
246         newitem->name = xstrdup(refname);
247         newitem->kind = kind;
248         newitem->commit = commit;
249         len = strlen(newitem->name);
250         if (len > ref_list->maxwidth)
251                 ref_list->maxwidth = len;
252
253         return 0;
254 }
255
256 static void free_ref_list(struct ref_list *ref_list)
257 {
258         int i;
259
260         for (i = 0; i < ref_list->index; i++)
261                 free(ref_list->list[i].name);
262         free(ref_list->list);
263 }
264
265 static int ref_cmp(const void *r1, const void *r2)
266 {
267         struct ref_item *c1 = (struct ref_item *)(r1);
268         struct ref_item *c2 = (struct ref_item *)(r2);
269
270         if (c1->kind != c2->kind)
271                 return c1->kind - c2->kind;
272         return strcmp(c1->name, c2->name);
273 }
274
275 static void fill_tracking_info(struct strbuf *stat, const char *branch_name)
276 {
277         int ours, theirs;
278         struct branch *branch = branch_get(branch_name);
279
280         if (!stat_tracking_info(branch, &ours, &theirs) || (!ours && !theirs))
281                 return;
282         if (!ours)
283                 strbuf_addf(stat, "[behind %d] ", theirs);
284         else if (!theirs)
285                 strbuf_addf(stat, "[ahead %d] ", ours);
286         else
287                 strbuf_addf(stat, "[ahead %d, behind %d] ", ours, theirs);
288 }
289
290 static int matches_merge_filter(struct commit *commit)
291 {
292         int is_merged;
293
294         if (merge_filter == NO_FILTER)
295                 return 1;
296
297         is_merged = !!(commit->object.flags & UNINTERESTING);
298         return (is_merged == (merge_filter == SHOW_MERGED));
299 }
300
301 static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
302                            int abbrev, int current)
303 {
304         char c;
305         int color;
306         struct commit *commit = item->commit;
307
308         if (!matches_merge_filter(commit))
309                 return;
310
311         switch (item->kind) {
312         case REF_LOCAL_BRANCH:
313                 color = COLOR_BRANCH_LOCAL;
314                 break;
315         case REF_REMOTE_BRANCH:
316                 color = COLOR_BRANCH_REMOTE;
317                 break;
318         default:
319                 color = COLOR_BRANCH_PLAIN;
320                 break;
321         }
322
323         c = ' ';
324         if (current) {
325                 c = '*';
326                 color = COLOR_BRANCH_CURRENT;
327         }
328
329         if (verbose) {
330                 struct strbuf subject = STRBUF_INIT, stat = STRBUF_INIT;
331                 const char *sub = " **** invalid ref ****";
332
333                 commit = item->commit;
334                 if (commit && !parse_commit(commit)) {
335                         pretty_print_commit(CMIT_FMT_ONELINE, commit,
336                                             &subject, 0, NULL, NULL, 0, 0);
337                         sub = subject.buf;
338                 }
339
340                 if (item->kind == REF_LOCAL_BRANCH)
341                         fill_tracking_info(&stat, item->name);
342
343                 printf("%c %s%-*s%s %s %s%s\n", c, branch_get_color(color),
344                        maxwidth, item->name,
345                        branch_get_color(COLOR_BRANCH_RESET),
346                        find_unique_abbrev(item->commit->object.sha1, abbrev),
347                        stat.buf, sub);
348                 strbuf_release(&stat);
349                 strbuf_release(&subject);
350         } else {
351                 printf("%c %s%s%s\n", c, branch_get_color(color), item->name,
352                        branch_get_color(COLOR_BRANCH_RESET));
353         }
354 }
355
356 static int calc_maxwidth(struct ref_list *refs)
357 {
358         int i, l, w = 0;
359         for (i = 0; i < refs->index; i++) {
360                 if (!matches_merge_filter(refs->list[i].commit))
361                         continue;
362                 l = strlen(refs->list[i].name);
363                 if (l > w)
364                         w = l;
365         }
366         return w;
367 }
368
369 static void print_ref_list(int kinds, int detached, int verbose, int abbrev, struct commit_list *with_commit)
370 {
371         int i;
372         struct ref_list ref_list;
373         struct commit *head_commit = lookup_commit_reference_gently(head_sha1, 1);
374
375         memset(&ref_list, 0, sizeof(ref_list));
376         ref_list.kinds = kinds;
377         ref_list.with_commit = with_commit;
378         if (merge_filter != NO_FILTER)
379                 init_revisions(&ref_list.revs, NULL);
380         for_each_ref(append_ref, &ref_list);
381         if (merge_filter != NO_FILTER) {
382                 struct commit *filter;
383                 filter = lookup_commit_reference_gently(merge_filter_ref, 0);
384                 filter->object.flags |= UNINTERESTING;
385                 add_pending_object(&ref_list.revs,
386                                    (struct object *) filter, "");
387                 ref_list.revs.limited = 1;
388                 prepare_revision_walk(&ref_list.revs);
389                 if (verbose)
390                         ref_list.maxwidth = calc_maxwidth(&ref_list);
391         }
392
393         qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
394
395         detached = (detached && (kinds & REF_LOCAL_BRANCH));
396         if (detached && head_commit &&
397             is_descendant_of(head_commit, with_commit)) {
398                 struct ref_item item;
399                 item.name = xstrdup("(no branch)");
400                 item.kind = REF_LOCAL_BRANCH;
401                 item.commit = head_commit;
402                 if (strlen(item.name) > ref_list.maxwidth)
403                         ref_list.maxwidth = strlen(item.name);
404                 print_ref_item(&item, ref_list.maxwidth, verbose, abbrev, 1);
405                 free(item.name);
406         }
407
408         for (i = 0; i < ref_list.index; i++) {
409                 int current = !detached &&
410                         (ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
411                         !strcmp(ref_list.list[i].name, head);
412                 print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
413                                abbrev, current);
414         }
415
416         free_ref_list(&ref_list);
417 }
418
419 static void rename_branch(const char *oldname, const char *newname, int force)
420 {
421         struct strbuf oldref = STRBUF_INIT, newref = STRBUF_INIT, logmsg = STRBUF_INIT;
422         unsigned char sha1[20];
423         struct strbuf oldsection = STRBUF_INIT, newsection = STRBUF_INIT;
424
425         if (!oldname)
426                 die("cannot rename the current branch while not on any.");
427
428         strbuf_addf(&oldref, "refs/heads/%s", oldname);
429
430         if (check_ref_format(oldref.buf))
431                 die("Invalid branch name: %s", oldref.buf);
432
433         strbuf_addf(&newref, "refs/heads/%s", newname);
434
435         if (check_ref_format(newref.buf))
436                 die("Invalid branch name: %s", newref.buf);
437
438         if (resolve_ref(newref.buf, sha1, 1, NULL) && !force)
439                 die("A branch named '%s' already exists.", newname);
440
441         strbuf_addf(&logmsg, "Branch: renamed %s to %s",
442                  oldref.buf, newref.buf);
443
444         if (rename_ref(oldref.buf, newref.buf, logmsg.buf))
445                 die("Branch rename failed");
446         strbuf_release(&logmsg);
447
448         /* no need to pass logmsg here as HEAD didn't really move */
449         if (!strcmp(oldname, head) && create_symref("HEAD", newref.buf, NULL))
450                 die("Branch renamed to %s, but HEAD is not updated!", newname);
451
452         strbuf_addf(&oldsection, "branch.%s", oldref.buf + 11);
453         strbuf_release(&oldref);
454         strbuf_addf(&newsection, "branch.%s", newref.buf + 11);
455         strbuf_release(&newref);
456         if (git_config_rename_section(oldsection.buf, newsection.buf) < 0)
457                 die("Branch is renamed, but update of config-file failed");
458         strbuf_release(&oldsection);
459         strbuf_release(&newsection);
460 }
461
462 static int opt_parse_merge_filter(const struct option *opt, const char *arg, int unset)
463 {
464         merge_filter = ((opt->long_name[0] == 'n')
465                         ? SHOW_NOT_MERGED
466                         : SHOW_MERGED);
467         if (unset)
468                 merge_filter = SHOW_NOT_MERGED; /* b/c for --no-merged */
469         if (!arg)
470                 arg = "HEAD";
471         if (get_sha1(arg, merge_filter_ref))
472                 die("malformed object name %s", arg);
473         return 0;
474 }
475
476 int cmd_branch(int argc, const char **argv, const char *prefix)
477 {
478         int delete = 0, rename = 0, force_create = 0;
479         int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
480         int reflog = 0;
481         enum branch_track track;
482         int kinds = REF_LOCAL_BRANCH;
483         struct commit_list *with_commit = NULL;
484
485         struct option options[] = {
486                 OPT_GROUP("Generic options"),
487                 OPT__VERBOSE(&verbose),
488                 OPT_SET_INT( 0 , "track",  &track, "set up tracking mode (see git-pull(1))",
489                         BRANCH_TRACK_EXPLICIT),
490                 OPT_BOOLEAN( 0 , "color",  &branch_use_color, "use colored output"),
491                 OPT_SET_INT('r', NULL,     &kinds, "act on remote-tracking branches",
492                         REF_REMOTE_BRANCH),
493                 {
494                         OPTION_CALLBACK, 0, "contains", &with_commit, "commit",
495                         "print only branches that contain the commit",
496                         PARSE_OPT_LASTARG_DEFAULT,
497                         parse_opt_with_commit, (intptr_t)"HEAD",
498                 },
499                 {
500                         OPTION_CALLBACK, 0, "with", &with_commit, "commit",
501                         "print only branches that contain the commit",
502                         PARSE_OPT_HIDDEN | PARSE_OPT_LASTARG_DEFAULT,
503                         parse_opt_with_commit, (intptr_t) "HEAD",
504                 },
505                 OPT__ABBREV(&abbrev),
506
507                 OPT_GROUP("Specific git-branch actions:"),
508                 OPT_SET_INT('a', NULL, &kinds, "list both remote-tracking and local branches",
509                         REF_REMOTE_BRANCH | REF_LOCAL_BRANCH),
510                 OPT_BIT('d', NULL, &delete, "delete fully merged branch", 1),
511                 OPT_BIT('D', NULL, &delete, "delete branch (even if not merged)", 2),
512                 OPT_BIT('m', NULL, &rename, "move/rename a branch and its reflog", 1),
513                 OPT_BIT('M', NULL, &rename, "move/rename a branch, even if target exists", 2),
514                 OPT_BOOLEAN('l', NULL, &reflog, "create the branch's reflog"),
515                 OPT_BOOLEAN('f', NULL, &force_create, "force creation (when already exists)"),
516                 {
517                         OPTION_CALLBACK, 0, "no-merged", &merge_filter_ref,
518                         "commit", "print only not merged branches",
519                         PARSE_OPT_LASTARG_DEFAULT | PARSE_OPT_NONEG,
520                         opt_parse_merge_filter, (intptr_t) "HEAD",
521                 },
522                 {
523                         OPTION_CALLBACK, 0, "merged", &merge_filter_ref,
524                         "commit", "print only merged branches",
525                         PARSE_OPT_LASTARG_DEFAULT | PARSE_OPT_NONEG,
526                         opt_parse_merge_filter, (intptr_t) "HEAD",
527                 },
528                 OPT_END(),
529         };
530
531         git_config(git_branch_config, NULL);
532
533         if (branch_use_color == -1)
534                 branch_use_color = git_use_color_default;
535
536         track = git_branch_track;
537
538         head = resolve_ref("HEAD", head_sha1, 0, NULL);
539         if (!head)
540                 die("Failed to resolve HEAD as a valid ref.");
541         head = xstrdup(head);
542         if (!strcmp(head, "HEAD")) {
543                 detached = 1;
544         } else {
545                 if (prefixcmp(head, "refs/heads/"))
546                         die("HEAD not found below refs/heads!");
547                 head += 11;
548         }
549         hashcpy(merge_filter_ref, head_sha1);
550
551         argc = parse_options(argc, argv, options, builtin_branch_usage, 0);
552         if (!!delete + !!rename + !!force_create > 1)
553                 usage_with_options(builtin_branch_usage, options);
554
555         if (delete)
556                 return delete_branches(argc, argv, delete > 1, kinds);
557         else if (argc == 0)
558                 print_ref_list(kinds, detached, verbose, abbrev, with_commit);
559         else if (rename && (argc == 1))
560                 rename_branch(head, argv[0], rename > 1);
561         else if (rename && (argc == 2))
562                 rename_branch(argv[0], argv[1], rename > 1);
563         else if (argc <= 2)
564                 create_branch(head, argv[0], (argc == 2) ? argv[1] : head,
565                               force_create, reflog, track);
566         else
567                 usage_with_options(builtin_branch_usage, options);
568
569         return 0;
570 }