Merge branch 'jc/lstat'
[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)
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);
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 print_ref_item(struct ref_item *item, int maxwidth, int verbose,
286                            int abbrev, int current)
287 {
288         char c;
289         int color;
290         struct commit *commit;
291
292         switch (item->kind) {
293         case REF_LOCAL_BRANCH:
294                 color = COLOR_BRANCH_LOCAL;
295                 break;
296         case REF_REMOTE_BRANCH:
297                 color = COLOR_BRANCH_REMOTE;
298                 break;
299         default:
300                 color = COLOR_BRANCH_PLAIN;
301                 break;
302         }
303
304         c = ' ';
305         if (current) {
306                 c = '*';
307                 color = COLOR_BRANCH_CURRENT;
308         }
309
310         if (verbose) {
311                 struct strbuf subject;
312                 const char *sub = " **** invalid ref ****";
313
314                 strbuf_init(&subject, 0);
315
316                 commit = lookup_commit(item->sha1);
317                 if (commit && !parse_commit(commit)) {
318                         pretty_print_commit(CMIT_FMT_ONELINE, commit,
319                                             &subject, 0, NULL, NULL, 0, 0);
320                         sub = subject.buf;
321                 }
322                 printf("%c %s%-*s%s %s %s\n", c, branch_get_color(color),
323                        maxwidth, item->name,
324                        branch_get_color(COLOR_BRANCH_RESET),
325                        find_unique_abbrev(item->sha1, abbrev), sub);
326                 strbuf_release(&subject);
327         } else {
328                 printf("%c %s%s%s\n", c, branch_get_color(color), item->name,
329                        branch_get_color(COLOR_BRANCH_RESET));
330         }
331 }
332
333 static void print_ref_list(int kinds, int detached, int verbose, int abbrev, struct commit_list *with_commit)
334 {
335         int i;
336         struct ref_list ref_list;
337
338         memset(&ref_list, 0, sizeof(ref_list));
339         ref_list.kinds = kinds;
340         ref_list.with_commit = with_commit;
341         for_each_ref(append_ref, &ref_list);
342
343         qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
344
345         detached = (detached && (kinds & REF_LOCAL_BRANCH));
346         if (detached && has_commit(head_sha1, with_commit)) {
347                 struct ref_item item;
348                 item.name = xstrdup("(no branch)");
349                 item.kind = REF_LOCAL_BRANCH;
350                 hashcpy(item.sha1, head_sha1);
351                 if (strlen(item.name) > ref_list.maxwidth)
352                               ref_list.maxwidth = strlen(item.name);
353                 print_ref_item(&item, ref_list.maxwidth, verbose, abbrev, 1);
354                 free(item.name);
355         }
356
357         for (i = 0; i < ref_list.index; i++) {
358                 int current = !detached &&
359                         (ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
360                         !strcmp(ref_list.list[i].name, head);
361                 print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
362                                abbrev, current);
363         }
364
365         free_ref_list(&ref_list);
366 }
367
368 static void rename_branch(const char *oldname, const char *newname, int force)
369 {
370         char oldref[PATH_MAX], newref[PATH_MAX], logmsg[PATH_MAX*2 + 100];
371         unsigned char sha1[20];
372         char oldsection[PATH_MAX], newsection[PATH_MAX];
373
374         if (!oldname)
375                 die("cannot rename the current branch while not on any.");
376
377         if (snprintf(oldref, sizeof(oldref), "refs/heads/%s", oldname) > sizeof(oldref))
378                 die("Old branchname too long");
379
380         if (check_ref_format(oldref))
381                 die("Invalid branch name: %s", oldref);
382
383         if (snprintf(newref, sizeof(newref), "refs/heads/%s", newname) > sizeof(newref))
384                 die("New branchname too long");
385
386         if (check_ref_format(newref))
387                 die("Invalid branch name: %s", newref);
388
389         if (resolve_ref(newref, sha1, 1, NULL) && !force)
390                 die("A branch named '%s' already exists.", newname);
391
392         snprintf(logmsg, sizeof(logmsg), "Branch: renamed %s to %s",
393                  oldref, newref);
394
395         if (rename_ref(oldref, newref, logmsg))
396                 die("Branch rename failed");
397
398         /* no need to pass logmsg here as HEAD didn't really move */
399         if (!strcmp(oldname, head) && create_symref("HEAD", newref, NULL))
400                 die("Branch renamed to %s, but HEAD is not updated!", newname);
401
402         snprintf(oldsection, sizeof(oldsection), "branch.%s", oldref + 11);
403         snprintf(newsection, sizeof(newsection), "branch.%s", newref + 11);
404         if (git_config_rename_section(oldsection, newsection) < 0)
405                 die("Branch is renamed, but update of config-file failed");
406 }
407
408 static int opt_parse_with_commit(const struct option *opt, const char *arg, int unset)
409 {
410         unsigned char sha1[20];
411         struct commit *commit;
412
413         if (!arg)
414                 return -1;
415         if (get_sha1(arg, sha1))
416                 die("malformed object name %s", arg);
417         commit = lookup_commit_reference(sha1);
418         if (!commit)
419                 die("no such commit %s", arg);
420         commit_list_insert(commit, opt->value);
421         return 0;
422 }
423
424 int cmd_branch(int argc, const char **argv, const char *prefix)
425 {
426         int delete = 0, rename = 0, force_create = 0;
427         int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
428         int reflog = 0;
429         enum branch_track track;
430         int kinds = REF_LOCAL_BRANCH;
431         struct commit_list *with_commit = NULL;
432
433         struct option options[] = {
434                 OPT_GROUP("Generic options"),
435                 OPT__VERBOSE(&verbose),
436                 OPT_SET_INT( 0 , "track",  &track, "set up tracking mode (see git-pull(1))",
437                         BRANCH_TRACK_EXPLICIT),
438                 OPT_BOOLEAN( 0 , "color",  &branch_use_color, "use colored output"),
439                 OPT_SET_INT('r', NULL,     &kinds, "act on remote-tracking branches",
440                         REF_REMOTE_BRANCH),
441                 OPT_CALLBACK(0, "contains", &with_commit, "commit",
442                              "print only branches that contain the commit",
443                              opt_parse_with_commit),
444                 {
445                         OPTION_CALLBACK, 0, "with", &with_commit, "commit",
446                         "print only branches that contain the commit",
447                         PARSE_OPT_HIDDEN, opt_parse_with_commit,
448                 },
449                 OPT__ABBREV(&abbrev),
450
451                 OPT_GROUP("Specific git-branch actions:"),
452                 OPT_SET_INT('a', NULL, &kinds, "list both remote-tracking and local branches",
453                         REF_REMOTE_BRANCH | REF_LOCAL_BRANCH),
454                 OPT_BIT('d', NULL, &delete, "delete fully merged branch", 1),
455                 OPT_BIT('D', NULL, &delete, "delete branch (even if not merged)", 2),
456                 OPT_BIT('m', NULL, &rename, "move/rename a branch and its reflog", 1),
457                 OPT_BIT('M', NULL, &rename, "move/rename a branch, even if target exists", 2),
458                 OPT_BOOLEAN('l', NULL, &reflog, "create the branch's reflog"),
459                 OPT_BOOLEAN('f', NULL, &force_create, "force creation (when already exists)"),
460                 OPT_SET_INT(0, "merged", &mergefilter, "list only merged branches", 1),
461                 OPT_END(),
462         };
463
464         git_config(git_branch_config);
465
466         if (branch_use_color == -1)
467                 branch_use_color = git_use_color_default;
468
469         track = git_branch_track;
470         argc = parse_options(argc, argv, options, builtin_branch_usage, 0);
471         if (!!delete + !!rename + !!force_create > 1)
472                 usage_with_options(builtin_branch_usage, options);
473
474         head = resolve_ref("HEAD", head_sha1, 0, NULL);
475         if (!head)
476                 die("Failed to resolve HEAD as a valid ref.");
477         head = xstrdup(head);
478         if (!strcmp(head, "HEAD")) {
479                 detached = 1;
480         } else {
481                 if (prefixcmp(head, "refs/heads/"))
482                         die("HEAD not found below refs/heads!");
483                 head += 11;
484         }
485
486         if (delete)
487                 return delete_branches(argc, argv, delete > 1, kinds);
488         else if (argc == 0)
489                 print_ref_list(kinds, detached, verbose, abbrev, with_commit);
490         else if (rename && (argc == 1))
491                 rename_branch(head, argv[0], rename > 1);
492         else if (rename && (argc == 2))
493                 rename_branch(argv[0], argv[1], rename > 1);
494         else if (argc <= 2)
495                 create_branch(head, argv[0], (argc == 2) ? argv[1] : head,
496                               force_create, reflog, track);
497         else
498                 usage_with_options(builtin_branch_usage, options);
499
500         return 0;
501 }