Avoid segfault with 'git branch' when the HEAD is detached
[alt-git.git] / builtin-branch.c
blob6106a1abd5d5a001a44d06a66bc0ea2e47f5247d
1 /*
2 * Builtin "git branch"
4 * Copyright (c) 2006 Kristian Høgsberg <krh@redhat.com>
5 * Based on git-branch.sh by Junio C Hamano.
6 */
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"
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
27 #define REF_LOCAL_BRANCH 0x01
28 #define REF_REMOTE_BRANCH 0x02
30 static const char *head;
31 static unsigned char head_sha1[20];
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) */
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,
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];
56 static int parse_branch_color_slot(const char *var, int ofs)
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);
71 static int git_branch_config(const char *var, const char *value, void *cb)
73 if (!strcmp(var, "color.branch")) {
74 branch_use_color = git_config_colorbool(var, value, -1);
75 return 0;
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;
84 return git_color_default_config(var, value, cb);
87 static const char *branch_get_color(enum color_branch ix)
89 if (branch_use_color > 0)
90 return branch_colors[ix];
91 return "";
94 static int delete_branches(int argc, const char **argv, int force, int kinds)
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;
103 switch (kinds) {
104 case REF_REMOTE_BRANCH:
105 fmt = "refs/remotes/%s";
106 remote = "remote ";
107 force = 1;
108 break;
109 case REF_LOCAL_BRANCH:
110 fmt = "refs/heads/%s";
111 remote = "";
112 break;
113 default:
114 die("cannot use -a with -d");
117 if (!force) {
118 head_rev = lookup_commit_reference(head_sha1);
119 if (!head_rev)
120 die("Couldn't look up commit object for HEAD");
122 for (i = 0; i < argc; i++) {
123 if (kinds == REF_LOCAL_BRANCH && !strcmp(head, argv[i])) {
124 error("Cannot delete the branch '%s' "
125 "which you are currently on.", argv[i]);
126 ret = 1;
127 continue;
130 free(name);
132 name = xstrdup(mkpath(fmt, argv[i]));
133 if (!resolve_ref(name, sha1, 1, NULL)) {
134 error("%sbranch '%s' not found.",
135 remote, argv[i]);
136 ret = 1;
137 continue;
140 rev = lookup_commit_reference(sha1);
141 if (!rev) {
142 error("Couldn't look up commit object for '%s'", name);
143 ret = 1;
144 continue;
147 /* This checks whether the merge bases of branch and
148 * HEAD contains branch -- which means that the HEAD
149 * contains everything in both.
152 if (!force &&
153 !in_merge_bases(rev, &head_rev, 1)) {
154 error("The branch '%s' is not an ancestor of "
155 "your current HEAD.\n"
156 "If you are sure you want to delete it, "
157 "run 'git branch -D %s'.", argv[i], argv[i]);
158 ret = 1;
159 continue;
162 if (delete_ref(name, sha1, 0)) {
163 error("Error deleting %sbranch '%s'", remote,
164 argv[i]);
165 ret = 1;
166 } else {
167 struct strbuf buf = STRBUF_INIT;
168 printf("Deleted %sbranch %s (%s).\n", remote, argv[i],
169 find_unique_abbrev(sha1, DEFAULT_ABBREV));
170 strbuf_addf(&buf, "branch.%s", argv[i]);
171 if (git_config_rename_section(buf.buf, NULL) < 0)
172 warning("Update of config-file failed");
173 strbuf_release(&buf);
177 free(name);
179 return(ret);
182 struct ref_item {
183 char *name;
184 char *dest;
185 unsigned int kind, len;
186 struct commit *commit;
189 struct ref_list {
190 struct rev_info revs;
191 int index, alloc, maxwidth;
192 struct ref_item *list;
193 struct commit_list *with_commit;
194 int kinds;
197 static char *resolve_symref(const char *src, const char *prefix)
199 unsigned char sha1[20];
200 int flag;
201 const char *dst, *cp;
203 dst = resolve_ref(src, sha1, 0, &flag);
204 if (!(dst && (flag & REF_ISSYMREF)))
205 return NULL;
206 if (prefix && (cp = skip_prefix(dst, prefix)))
207 dst = cp;
208 return xstrdup(dst);
211 static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
213 struct ref_list *ref_list = (struct ref_list*)(cb_data);
214 struct ref_item *newitem;
215 struct commit *commit;
216 int kind, i;
217 const char *prefix, *orig_refname = refname;
219 static struct {
220 int kind;
221 const char *prefix;
222 int pfxlen;
223 } ref_kind[] = {
224 { REF_LOCAL_BRANCH, "refs/heads/", 11 },
225 { REF_REMOTE_BRANCH, "refs/remotes/", 13 },
228 /* Detect kind */
229 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
230 prefix = ref_kind[i].prefix;
231 if (strncmp(refname, prefix, ref_kind[i].pfxlen))
232 continue;
233 kind = ref_kind[i].kind;
234 refname += ref_kind[i].pfxlen;
235 break;
237 if (ARRAY_SIZE(ref_kind) <= i)
238 return 0;
240 commit = lookup_commit_reference_gently(sha1, 1);
241 if (!commit)
242 return error("branch '%s' does not point at a commit", refname);
244 /* Filter with with_commit if specified */
245 if (!is_descendant_of(commit, ref_list->with_commit))
246 return 0;
248 /* Don't add types the caller doesn't want */
249 if ((kind & ref_list->kinds) == 0)
250 return 0;
252 if (merge_filter != NO_FILTER)
253 add_pending_object(&ref_list->revs,
254 (struct object *)commit, refname);
256 /* Resize buffer */
257 if (ref_list->index >= ref_list->alloc) {
258 ref_list->alloc = alloc_nr(ref_list->alloc);
259 ref_list->list = xrealloc(ref_list->list,
260 ref_list->alloc * sizeof(struct ref_item));
263 /* Record the new item */
264 newitem = &(ref_list->list[ref_list->index++]);
265 newitem->name = xstrdup(refname);
266 newitem->kind = kind;
267 newitem->commit = commit;
268 newitem->len = strlen(refname);
269 newitem->dest = resolve_symref(orig_refname, prefix);
270 /* adjust for "remotes/" */
271 if (newitem->kind == REF_REMOTE_BRANCH &&
272 ref_list->kinds != REF_REMOTE_BRANCH)
273 newitem->len += 8;
274 if (newitem->len > ref_list->maxwidth)
275 ref_list->maxwidth = newitem->len;
277 return 0;
280 static void free_ref_list(struct ref_list *ref_list)
282 int i;
284 for (i = 0; i < ref_list->index; i++) {
285 free(ref_list->list[i].name);
286 free(ref_list->list[i].dest);
288 free(ref_list->list);
291 static int ref_cmp(const void *r1, const void *r2)
293 struct ref_item *c1 = (struct ref_item *)(r1);
294 struct ref_item *c2 = (struct ref_item *)(r2);
296 if (c1->kind != c2->kind)
297 return c1->kind - c2->kind;
298 return strcmp(c1->name, c2->name);
301 static void fill_tracking_info(struct strbuf *stat, const char *branch_name)
303 int ours, theirs;
304 struct branch *branch = branch_get(branch_name);
306 if (!stat_tracking_info(branch, &ours, &theirs) || (!ours && !theirs))
307 return;
308 if (!ours)
309 strbuf_addf(stat, "[behind %d] ", theirs);
310 else if (!theirs)
311 strbuf_addf(stat, "[ahead %d] ", ours);
312 else
313 strbuf_addf(stat, "[ahead %d, behind %d] ", ours, theirs);
316 static int matches_merge_filter(struct commit *commit)
318 int is_merged;
320 if (merge_filter == NO_FILTER)
321 return 1;
323 is_merged = !!(commit->object.flags & UNINTERESTING);
324 return (is_merged == (merge_filter == SHOW_MERGED));
327 static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
328 int abbrev, int current, char *prefix)
330 char c;
331 int color;
332 struct commit *commit = item->commit;
333 struct strbuf out = STRBUF_INIT, name = STRBUF_INIT;
335 if (!matches_merge_filter(commit))
336 return;
338 switch (item->kind) {
339 case REF_LOCAL_BRANCH:
340 color = COLOR_BRANCH_LOCAL;
341 break;
342 case REF_REMOTE_BRANCH:
343 color = COLOR_BRANCH_REMOTE;
344 break;
345 default:
346 color = COLOR_BRANCH_PLAIN;
347 break;
350 c = ' ';
351 if (current) {
352 c = '*';
353 color = COLOR_BRANCH_CURRENT;
356 strbuf_addf(&name, "%s%s", prefix, item->name);
357 if (verbose)
358 strbuf_addf(&out, "%c %s%-*s%s", c, branch_get_color(color),
359 maxwidth, name.buf,
360 branch_get_color(COLOR_BRANCH_RESET));
361 else
362 strbuf_addf(&out, "%c %s%s%s", c, branch_get_color(color),
363 name.buf, branch_get_color(COLOR_BRANCH_RESET));
365 if (item->dest)
366 strbuf_addf(&out, " -> %s", item->dest);
367 else if (verbose) {
368 struct strbuf subject = STRBUF_INIT, stat = STRBUF_INIT;
369 const char *sub = " **** invalid ref ****";
371 commit = item->commit;
372 if (commit && !parse_commit(commit)) {
373 pretty_print_commit(CMIT_FMT_ONELINE, commit,
374 &subject, 0, NULL, NULL, 0, 0);
375 sub = subject.buf;
378 if (item->kind == REF_LOCAL_BRANCH)
379 fill_tracking_info(&stat, item->name);
381 strbuf_addf(&out, " %s %s%s",
382 find_unique_abbrev(item->commit->object.sha1, abbrev),
383 stat.buf, sub);
384 strbuf_release(&stat);
385 strbuf_release(&subject);
387 printf("%s\n", out.buf);
388 strbuf_release(&name);
389 strbuf_release(&out);
392 static int calc_maxwidth(struct ref_list *refs)
394 int i, w = 0;
395 for (i = 0; i < refs->index; i++) {
396 if (!matches_merge_filter(refs->list[i].commit))
397 continue;
398 if (refs->list[i].len > w)
399 w = refs->list[i].len;
401 return w;
404 static void print_ref_list(int kinds, int detached, int verbose, int abbrev, struct commit_list *with_commit)
406 int i;
407 struct ref_list ref_list;
408 struct commit *head_commit = lookup_commit_reference_gently(head_sha1, 1);
410 memset(&ref_list, 0, sizeof(ref_list));
411 ref_list.kinds = kinds;
412 ref_list.with_commit = with_commit;
413 if (merge_filter != NO_FILTER)
414 init_revisions(&ref_list.revs, NULL);
415 for_each_ref(append_ref, &ref_list);
416 if (merge_filter != NO_FILTER) {
417 struct commit *filter;
418 filter = lookup_commit_reference_gently(merge_filter_ref, 0);
419 filter->object.flags |= UNINTERESTING;
420 add_pending_object(&ref_list.revs,
421 (struct object *) filter, "");
422 ref_list.revs.limited = 1;
423 prepare_revision_walk(&ref_list.revs);
424 if (verbose)
425 ref_list.maxwidth = calc_maxwidth(&ref_list);
428 qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
430 detached = (detached && (kinds & REF_LOCAL_BRANCH));
431 if (detached && head_commit &&
432 is_descendant_of(head_commit, with_commit)) {
433 struct ref_item item;
434 item.name = xstrdup("(no branch)");
435 item.len = strlen(item.name);
436 item.kind = REF_LOCAL_BRANCH;
437 item.dest = NULL;
438 item.commit = head_commit;
439 if (strlen(item.name) > ref_list.maxwidth)
440 ref_list.maxwidth = strlen(item.name);
441 print_ref_item(&item, ref_list.maxwidth, verbose, abbrev, 1, "");
442 free(item.name);
445 for (i = 0; i < ref_list.index; i++) {
446 int current = !detached &&
447 (ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
448 !strcmp(ref_list.list[i].name, head);
449 char *prefix = (kinds != REF_REMOTE_BRANCH &&
450 ref_list.list[i].kind == REF_REMOTE_BRANCH)
451 ? "remotes/" : "";
452 print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
453 abbrev, current, prefix);
456 free_ref_list(&ref_list);
459 static void rename_branch(const char *oldname, const char *newname, int force)
461 struct strbuf oldref = STRBUF_INIT, newref = STRBUF_INIT, logmsg = STRBUF_INIT;
462 unsigned char sha1[20];
463 struct strbuf oldsection = STRBUF_INIT, newsection = STRBUF_INIT;
465 if (!oldname)
466 die("cannot rename the current branch while not on any.");
468 strbuf_addf(&oldref, "refs/heads/%s", oldname);
470 if (check_ref_format(oldref.buf))
471 die("Invalid branch name: %s", oldref.buf);
473 strbuf_addf(&newref, "refs/heads/%s", newname);
475 if (check_ref_format(newref.buf))
476 die("Invalid branch name: %s", newref.buf);
478 if (resolve_ref(newref.buf, sha1, 1, NULL) && !force)
479 die("A branch named '%s' already exists.", newname);
481 strbuf_addf(&logmsg, "Branch: renamed %s to %s",
482 oldref.buf, newref.buf);
484 if (rename_ref(oldref.buf, newref.buf, logmsg.buf))
485 die("Branch rename failed");
486 strbuf_release(&logmsg);
488 /* no need to pass logmsg here as HEAD didn't really move */
489 if (!strcmp(oldname, head) && create_symref("HEAD", newref.buf, NULL))
490 die("Branch renamed to %s, but HEAD is not updated!", newname);
492 strbuf_addf(&oldsection, "branch.%s", oldref.buf + 11);
493 strbuf_release(&oldref);
494 strbuf_addf(&newsection, "branch.%s", newref.buf + 11);
495 strbuf_release(&newref);
496 if (git_config_rename_section(oldsection.buf, newsection.buf) < 0)
497 die("Branch is renamed, but update of config-file failed");
498 strbuf_release(&oldsection);
499 strbuf_release(&newsection);
502 static int opt_parse_merge_filter(const struct option *opt, const char *arg, int unset)
504 merge_filter = ((opt->long_name[0] == 'n')
505 ? SHOW_NOT_MERGED
506 : SHOW_MERGED);
507 if (unset)
508 merge_filter = SHOW_NOT_MERGED; /* b/c for --no-merged */
509 if (!arg)
510 arg = "HEAD";
511 if (get_sha1(arg, merge_filter_ref))
512 die("malformed object name %s", arg);
513 return 0;
516 int cmd_branch(int argc, const char **argv, const char *prefix)
518 int delete = 0, rename = 0, force_create = 0;
519 int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
520 int reflog = 0;
521 enum branch_track track;
522 int kinds = REF_LOCAL_BRANCH;
523 struct commit_list *with_commit = NULL;
525 struct option options[] = {
526 OPT_GROUP("Generic options"),
527 OPT__VERBOSE(&verbose),
528 OPT_SET_INT( 0 , "track", &track, "set up tracking mode (see git-pull(1))",
529 BRANCH_TRACK_EXPLICIT),
530 OPT_BOOLEAN( 0 , "color", &branch_use_color, "use colored output"),
531 OPT_SET_INT('r', NULL, &kinds, "act on remote-tracking branches",
532 REF_REMOTE_BRANCH),
534 OPTION_CALLBACK, 0, "contains", &with_commit, "commit",
535 "print only branches that contain the commit",
536 PARSE_OPT_LASTARG_DEFAULT,
537 parse_opt_with_commit, (intptr_t)"HEAD",
540 OPTION_CALLBACK, 0, "with", &with_commit, "commit",
541 "print only branches that contain the commit",
542 PARSE_OPT_HIDDEN | PARSE_OPT_LASTARG_DEFAULT,
543 parse_opt_with_commit, (intptr_t) "HEAD",
545 OPT__ABBREV(&abbrev),
547 OPT_GROUP("Specific git-branch actions:"),
548 OPT_SET_INT('a', NULL, &kinds, "list both remote-tracking and local branches",
549 REF_REMOTE_BRANCH | REF_LOCAL_BRANCH),
550 OPT_BIT('d', NULL, &delete, "delete fully merged branch", 1),
551 OPT_BIT('D', NULL, &delete, "delete branch (even if not merged)", 2),
552 OPT_BIT('m', NULL, &rename, "move/rename a branch and its reflog", 1),
553 OPT_BIT('M', NULL, &rename, "move/rename a branch, even if target exists", 2),
554 OPT_BOOLEAN('l', NULL, &reflog, "create the branch's reflog"),
555 OPT_BOOLEAN('f', NULL, &force_create, "force creation (when already exists)"),
557 OPTION_CALLBACK, 0, "no-merged", &merge_filter_ref,
558 "commit", "print only not merged branches",
559 PARSE_OPT_LASTARG_DEFAULT | PARSE_OPT_NONEG,
560 opt_parse_merge_filter, (intptr_t) "HEAD",
563 OPTION_CALLBACK, 0, "merged", &merge_filter_ref,
564 "commit", "print only merged branches",
565 PARSE_OPT_LASTARG_DEFAULT | PARSE_OPT_NONEG,
566 opt_parse_merge_filter, (intptr_t) "HEAD",
568 OPT_END(),
571 git_config(git_branch_config, NULL);
573 if (branch_use_color == -1)
574 branch_use_color = git_use_color_default;
576 track = git_branch_track;
578 head = resolve_ref("HEAD", head_sha1, 0, NULL);
579 if (!head)
580 die("Failed to resolve HEAD as a valid ref.");
581 head = xstrdup(head);
582 if (!strcmp(head, "HEAD")) {
583 detached = 1;
584 } else {
585 if (prefixcmp(head, "refs/heads/"))
586 die("HEAD not found below refs/heads!");
587 head += 11;
589 hashcpy(merge_filter_ref, head_sha1);
591 argc = parse_options(argc, argv, options, builtin_branch_usage, 0);
592 if (!!delete + !!rename + !!force_create > 1)
593 usage_with_options(builtin_branch_usage, options);
595 if (delete)
596 return delete_branches(argc, argv, delete > 1, kinds);
597 else if (argc == 0)
598 print_ref_list(kinds, detached, verbose, abbrev, with_commit);
599 else if (rename && (argc == 1))
600 rename_branch(head, argv[0], rename > 1);
601 else if (rename && (argc == 2))
602 rename_branch(argv[0], argv[1], rename > 1);
603 else if (argc <= 2)
604 create_branch(head, argv[0], (argc == 2) ? argv[1] : head,
605 force_create, reflog, track);
606 else
607 usage_with_options(builtin_branch_usage, options);
609 return 0;