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