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