Merge branch 'origin'
[git/jnareb-git.git] / builtin-branch.c
blobda480519d7a1e7fb51d94c393ded3fe64840ee8b
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"
14 static const char builtin_branch_usage[] =
15 "git-branch [-r] (-d | -D) <branchname> | [--track | --no-track] [-l] [-f] <branchname> [<start-point>] | (-m | -M) [<oldbranch>] <newbranch> | [--color | --no-color] [-r | -a] [-v [--abbrev=<length> | --no-abbrev]]";
17 #define REF_UNKNOWN_TYPE 0x00
18 #define REF_LOCAL_BRANCH 0x01
19 #define REF_REMOTE_BRANCH 0x02
20 #define REF_TAG 0x04
22 static const char *head;
23 static unsigned char head_sha1[20];
25 static int branch_track_remotes;
27 static int branch_use_color;
28 static char branch_colors[][COLOR_MAXLEN] = {
29 "\033[m", /* reset */
30 "", /* PLAIN (normal) */
31 "\033[31m", /* REMOTE (red) */
32 "", /* LOCAL (normal) */
33 "\033[32m", /* CURRENT (green) */
35 enum color_branch {
36 COLOR_BRANCH_RESET = 0,
37 COLOR_BRANCH_PLAIN = 1,
38 COLOR_BRANCH_REMOTE = 2,
39 COLOR_BRANCH_LOCAL = 3,
40 COLOR_BRANCH_CURRENT = 4,
43 static int parse_branch_color_slot(const char *var, int ofs)
45 if (!strcasecmp(var+ofs, "plain"))
46 return COLOR_BRANCH_PLAIN;
47 if (!strcasecmp(var+ofs, "reset"))
48 return COLOR_BRANCH_RESET;
49 if (!strcasecmp(var+ofs, "remote"))
50 return COLOR_BRANCH_REMOTE;
51 if (!strcasecmp(var+ofs, "local"))
52 return COLOR_BRANCH_LOCAL;
53 if (!strcasecmp(var+ofs, "current"))
54 return COLOR_BRANCH_CURRENT;
55 die("bad config variable '%s'", var);
58 static int git_branch_config(const char *var, const char *value)
60 if (!strcmp(var, "color.branch")) {
61 branch_use_color = git_config_colorbool(var, value);
62 return 0;
64 if (!prefixcmp(var, "color.branch.")) {
65 int slot = parse_branch_color_slot(var, 13);
66 color_parse(value, var, branch_colors[slot]);
67 return 0;
69 if (!strcmp(var, "branch.autosetupmerge"))
70 branch_track_remotes = git_config_bool(var, value);
72 return git_default_config(var, value);
75 static const char *branch_get_color(enum color_branch ix)
77 if (branch_use_color)
78 return branch_colors[ix];
79 return "";
82 static int delete_branches(int argc, const char **argv, int force, int kinds)
84 struct commit *rev, *head_rev = head_rev;
85 unsigned char sha1[20];
86 char *name = NULL;
87 const char *fmt, *remote;
88 int i;
89 int ret = 0;
91 switch (kinds) {
92 case REF_REMOTE_BRANCH:
93 fmt = "refs/remotes/%s";
94 remote = "remote ";
95 force = 1;
96 break;
97 case REF_LOCAL_BRANCH:
98 fmt = "refs/heads/%s";
99 remote = "";
100 break;
101 default:
102 die("cannot use -a with -d");
105 if (!force) {
106 head_rev = lookup_commit_reference(head_sha1);
107 if (!head_rev)
108 die("Couldn't look up commit object for HEAD");
110 for (i = 0; i < argc; i++) {
111 if (kinds == REF_LOCAL_BRANCH && !strcmp(head, argv[i])) {
112 error("Cannot delete the branch '%s' "
113 "which you are currently on.", argv[i]);
114 ret = 1;
115 continue;
118 if (name)
119 free(name);
121 name = xstrdup(mkpath(fmt, argv[i]));
122 if (!resolve_ref(name, sha1, 1, NULL)) {
123 error("%sbranch '%s' not found.",
124 remote, argv[i]);
125 ret = 1;
126 continue;
129 rev = lookup_commit_reference(sha1);
130 if (!rev) {
131 error("Couldn't look up commit object for '%s'", name);
132 ret = 1;
133 continue;
136 /* This checks whether the merge bases of branch and
137 * HEAD contains branch -- which means that the HEAD
138 * contains everything in both.
141 if (!force &&
142 !in_merge_bases(rev, &head_rev, 1)) {
143 error("The branch '%s' is not a strict subset of "
144 "your current HEAD.\n"
145 "If you are sure you want to delete it, "
146 "run 'git branch -D %s'.", argv[i], argv[i]);
147 ret = 1;
148 continue;
151 if (delete_ref(name, sha1)) {
152 error("Error deleting %sbranch '%s'", remote,
153 argv[i]);
154 ret = 1;
155 } else
156 printf("Deleted %sbranch %s.\n", remote, argv[i]);
160 if (name)
161 free(name);
163 return(ret);
166 struct ref_item {
167 char *name;
168 unsigned int kind;
169 unsigned char sha1[20];
172 struct ref_list {
173 int index, alloc, maxwidth;
174 struct ref_item *list;
175 int kinds;
178 static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
180 struct ref_list *ref_list = (struct ref_list*)(cb_data);
181 struct ref_item *newitem;
182 int kind = REF_UNKNOWN_TYPE;
183 int len;
185 /* Detect kind */
186 if (!prefixcmp(refname, "refs/heads/")) {
187 kind = REF_LOCAL_BRANCH;
188 refname += 11;
189 } else if (!prefixcmp(refname, "refs/remotes/")) {
190 kind = REF_REMOTE_BRANCH;
191 refname += 13;
192 } else if (!prefixcmp(refname, "refs/tags/")) {
193 kind = REF_TAG;
194 refname += 10;
197 /* Don't add types the caller doesn't want */
198 if ((kind & ref_list->kinds) == 0)
199 return 0;
201 /* Resize buffer */
202 if (ref_list->index >= ref_list->alloc) {
203 ref_list->alloc = alloc_nr(ref_list->alloc);
204 ref_list->list = xrealloc(ref_list->list,
205 ref_list->alloc * sizeof(struct ref_item));
208 /* Record the new item */
209 newitem = &(ref_list->list[ref_list->index++]);
210 newitem->name = xstrdup(refname);
211 newitem->kind = kind;
212 hashcpy(newitem->sha1, sha1);
213 len = strlen(newitem->name);
214 if (len > ref_list->maxwidth)
215 ref_list->maxwidth = len;
217 return 0;
220 static void free_ref_list(struct ref_list *ref_list)
222 int i;
224 for (i = 0; i < ref_list->index; i++)
225 free(ref_list->list[i].name);
226 free(ref_list->list);
229 static int ref_cmp(const void *r1, const void *r2)
231 struct ref_item *c1 = (struct ref_item *)(r1);
232 struct ref_item *c2 = (struct ref_item *)(r2);
234 if (c1->kind != c2->kind)
235 return c1->kind - c2->kind;
236 return strcmp(c1->name, c2->name);
239 static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
240 int abbrev, int current)
242 char c;
243 int color;
244 struct commit *commit;
245 char subject[256];
247 switch (item->kind) {
248 case REF_LOCAL_BRANCH:
249 color = COLOR_BRANCH_LOCAL;
250 break;
251 case REF_REMOTE_BRANCH:
252 color = COLOR_BRANCH_REMOTE;
253 break;
254 default:
255 color = COLOR_BRANCH_PLAIN;
256 break;
259 c = ' ';
260 if (current) {
261 c = '*';
262 color = COLOR_BRANCH_CURRENT;
265 if (verbose) {
266 commit = lookup_commit(item->sha1);
267 if (commit && !parse_commit(commit))
268 pretty_print_commit(CMIT_FMT_ONELINE, commit, ~0,
269 subject, sizeof(subject), 0,
270 NULL, NULL, 0);
271 else
272 strcpy(subject, " **** invalid ref ****");
273 printf("%c %s%-*s%s %s %s\n", c, branch_get_color(color),
274 maxwidth, item->name,
275 branch_get_color(COLOR_BRANCH_RESET),
276 find_unique_abbrev(item->sha1, abbrev), subject);
277 } else {
278 printf("%c %s%s%s\n", c, branch_get_color(color), item->name,
279 branch_get_color(COLOR_BRANCH_RESET));
283 static void print_ref_list(int kinds, int detached, int verbose, int abbrev)
285 int i;
286 struct ref_list ref_list;
288 memset(&ref_list, 0, sizeof(ref_list));
289 ref_list.kinds = kinds;
290 for_each_ref(append_ref, &ref_list);
292 qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
294 detached = (detached && (kinds & REF_LOCAL_BRANCH));
295 if (detached) {
296 struct ref_item item;
297 item.name = xstrdup("(no branch)");
298 item.kind = REF_LOCAL_BRANCH;
299 hashcpy(item.sha1, head_sha1);
300 if (strlen(item.name) > ref_list.maxwidth)
301 ref_list.maxwidth = strlen(item.name);
302 print_ref_item(&item, ref_list.maxwidth, verbose, abbrev, 1);
303 free(item.name);
306 for (i = 0; i < ref_list.index; i++) {
307 int current = !detached &&
308 (ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
309 !strcmp(ref_list.list[i].name, head);
310 print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
311 abbrev, current);
314 free_ref_list(&ref_list);
317 static char *config_repo;
318 static char *config_remote;
319 static const char *start_ref;
321 static int get_remote_branch_name(const char *value)
323 const char *colon;
324 const char *end;
326 if (*value == '+')
327 value++;
329 colon = strchr(value, ':');
330 if (!colon)
331 return 0;
333 end = value + strlen(value);
336 * Try an exact match first. I.e. handle the case where the
337 * value is "$anything:refs/foo/bar/baz" and start_ref is exactly
338 * "refs/foo/bar/baz". Then the name at the remote is $anything.
340 if (!strcmp(colon + 1, start_ref)) {
341 /* Truncate the value before the colon. */
342 nfasprintf(&config_repo, "%.*s", colon - value, value);
343 return 1;
347 * Is this a wildcard match?
349 if ((end - 2 <= value) || end[-2] != '/' || end[-1] != '*' ||
350 (colon - 2 <= value) || colon[-2] != '/' || colon[-1] != '*')
351 return 0;
354 * Value is "refs/foo/bar/<asterisk>:refs/baz/boa/<asterisk>"
355 * and start_ref begins with "refs/baz/boa/"; the name at the
356 * remote is refs/foo/bar/ with the remaining part of the
357 * start_ref. The length of the prefix on the RHS is (end -
358 * colon - 2), including the slash immediately before the
359 * asterisk.
361 if ((strlen(start_ref) < end - colon - 2) ||
362 memcmp(start_ref, colon + 1, end - colon - 2))
363 return 0; /* does not match prefix */
365 /* Replace the asterisk with the remote branch name. */
366 nfasprintf(&config_repo, "%.*s%s",
367 (colon - 1) - value, value,
368 start_ref + (end - colon - 2));
369 return 1;
372 static int get_remote_config(const char *key, const char *value)
374 const char *var;
375 if (prefixcmp(key, "remote."))
376 return 0;
378 var = strrchr(key, '.');
379 if (var == key + 6 || strcmp(var, ".fetch"))
380 return 0;
382 * Ok, we are looking at key == "remote.$foo.fetch";
384 if (get_remote_branch_name(value))
385 nfasprintf(&config_remote, "%.*s", var - (key + 7), key + 7);
387 return 0;
390 static void set_branch_merge(const char *name, const char *config_remote,
391 const char *config_repo)
393 char key[1024];
394 if (sizeof(key) <=
395 snprintf(key, sizeof(key), "branch.%s.remote", name))
396 die("what a long branch name you have!");
397 git_config_set(key, config_remote);
400 * We do not have to check if we have enough space for
401 * the 'merge' key, since it's shorter than the
402 * previous 'remote' key, which we already checked.
404 snprintf(key, sizeof(key), "branch.%s.merge", name);
405 git_config_set(key, config_repo);
408 static void set_branch_defaults(const char *name, const char *real_ref)
411 * name is the name of new branch under refs/heads;
412 * real_ref is typically refs/remotes/$foo/$bar, where
413 * $foo is the remote name (there typically are no slashes)
414 * and $bar is the branch name we map from the remote
415 * (it could have slashes).
417 start_ref = real_ref;
418 git_config(get_remote_config);
419 if (!config_repo && !config_remote &&
420 !prefixcmp(real_ref, "refs/heads/")) {
421 set_branch_merge(name, ".", real_ref);
422 printf("Branch %s set up to track local branch %s.\n",
423 name, real_ref);
426 if (config_repo && config_remote) {
427 set_branch_merge(name, config_remote, config_repo);
428 printf("Branch %s set up to track remote branch %s.\n",
429 name, real_ref);
432 if (config_repo)
433 free(config_repo);
434 if (config_remote)
435 free(config_remote);
438 static void create_branch(const char *name, const char *start_name,
439 int force, int reflog, int track)
441 struct ref_lock *lock;
442 struct commit *commit;
443 unsigned char sha1[20];
444 char *real_ref, ref[PATH_MAX], msg[PATH_MAX + 20];
445 int forcing = 0;
447 snprintf(ref, sizeof ref, "refs/heads/%s", name);
448 if (check_ref_format(ref))
449 die("'%s' is not a valid branch name.", name);
451 if (resolve_ref(ref, sha1, 1, NULL)) {
452 if (!force)
453 die("A branch named '%s' already exists.", name);
454 else if (!is_bare_repository() && !strcmp(head, name))
455 die("Cannot force update the current branch.");
456 forcing = 1;
459 real_ref = NULL;
460 if (get_sha1(start_name, sha1))
461 die("Not a valid object name: '%s'.", start_name);
463 switch (dwim_ref(start_name, strlen(start_name), sha1, &real_ref)) {
464 case 0:
465 /* Not branching from any existing branch */
466 real_ref = NULL;
467 break;
468 case 1:
469 /* Unique completion -- good */
470 break;
471 default:
472 die("Ambiguous object name: '%s'.", start_name);
473 break;
476 if ((commit = lookup_commit_reference(sha1)) == NULL)
477 die("Not a valid branch point: '%s'.", start_name);
478 hashcpy(sha1, commit->object.sha1);
480 lock = lock_any_ref_for_update(ref, NULL, 0);
481 if (!lock)
482 die("Failed to lock ref for update: %s.", strerror(errno));
484 if (reflog)
485 log_all_ref_updates = 1;
487 if (forcing)
488 snprintf(msg, sizeof msg, "branch: Reset from %s",
489 start_name);
490 else
491 snprintf(msg, sizeof msg, "branch: Created from %s",
492 start_name);
494 /* When branching off a remote branch, set up so that git-pull
495 automatically merges from there. So far, this is only done for
496 remotes registered via .git/config. */
497 if (real_ref && track)
498 set_branch_defaults(name, real_ref);
500 if (write_ref_sha1(lock, sha1, msg) < 0)
501 die("Failed to write ref: %s.", strerror(errno));
503 if (real_ref)
504 free(real_ref);
507 static void rename_branch(const char *oldname, const char *newname, int force)
509 char oldref[PATH_MAX], newref[PATH_MAX], logmsg[PATH_MAX*2 + 100];
510 unsigned char sha1[20];
511 char oldsection[PATH_MAX], newsection[PATH_MAX];
513 if (!oldname)
514 die("cannot rename the current branch while not on any.");
516 if (snprintf(oldref, sizeof(oldref), "refs/heads/%s", oldname) > sizeof(oldref))
517 die("Old branchname too long");
519 if (check_ref_format(oldref))
520 die("Invalid branch name: %s", oldref);
522 if (snprintf(newref, sizeof(newref), "refs/heads/%s", newname) > sizeof(newref))
523 die("New branchname too long");
525 if (check_ref_format(newref))
526 die("Invalid branch name: %s", newref);
528 if (resolve_ref(newref, sha1, 1, NULL) && !force)
529 die("A branch named '%s' already exists.", newname);
531 snprintf(logmsg, sizeof(logmsg), "Branch: renamed %s to %s",
532 oldref, newref);
534 if (rename_ref(oldref, newref, logmsg))
535 die("Branch rename failed");
537 /* no need to pass logmsg here as HEAD didn't really move */
538 if (!strcmp(oldname, head) && create_symref("HEAD", newref, NULL))
539 die("Branch renamed to %s, but HEAD is not updated!", newname);
541 snprintf(oldsection, sizeof(oldsection), "branch.%s", oldref + 11);
542 snprintf(newsection, sizeof(newsection), "branch.%s", newref + 11);
543 if (git_config_rename_section(oldsection, newsection) < 0)
544 die("Branch is renamed, but update of config-file failed");
547 int cmd_branch(int argc, const char **argv, const char *prefix)
549 int delete = 0, force_delete = 0, force_create = 0;
550 int rename = 0, force_rename = 0;
551 int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
552 int reflog = 0, track;
553 int kinds = REF_LOCAL_BRANCH;
554 int i;
556 git_config(git_branch_config);
557 track = branch_track_remotes;
559 for (i = 1; i < argc; i++) {
560 const char *arg = argv[i];
562 if (arg[0] != '-')
563 break;
564 if (!strcmp(arg, "--")) {
565 i++;
566 break;
568 if (!strcmp(arg, "--track")) {
569 track = 1;
570 continue;
572 if (!strcmp(arg, "--no-track")) {
573 track = 0;
574 continue;
576 if (!strcmp(arg, "-d")) {
577 delete = 1;
578 continue;
580 if (!strcmp(arg, "-D")) {
581 delete = 1;
582 force_delete = 1;
583 continue;
585 if (!strcmp(arg, "-f")) {
586 force_create = 1;
587 continue;
589 if (!strcmp(arg, "-m")) {
590 rename = 1;
591 continue;
593 if (!strcmp(arg, "-M")) {
594 rename = 1;
595 force_rename = 1;
596 continue;
598 if (!strcmp(arg, "-r")) {
599 kinds = REF_REMOTE_BRANCH;
600 continue;
602 if (!strcmp(arg, "-a")) {
603 kinds = REF_REMOTE_BRANCH | REF_LOCAL_BRANCH;
604 continue;
606 if (!strcmp(arg, "-l")) {
607 reflog = 1;
608 continue;
610 if (!prefixcmp(arg, "--no-abbrev")) {
611 abbrev = 0;
612 continue;
614 if (!prefixcmp(arg, "--abbrev=")) {
615 abbrev = strtoul(arg + 9, NULL, 10);
616 if (abbrev < MINIMUM_ABBREV)
617 abbrev = MINIMUM_ABBREV;
618 else if (abbrev > 40)
619 abbrev = 40;
620 continue;
622 if (!strcmp(arg, "-v")) {
623 verbose = 1;
624 continue;
626 if (!strcmp(arg, "--color")) {
627 branch_use_color = 1;
628 continue;
630 if (!strcmp(arg, "--no-color")) {
631 branch_use_color = 0;
632 continue;
634 usage(builtin_branch_usage);
637 if ((delete && rename) || (delete && force_create) ||
638 (rename && force_create))
639 usage(builtin_branch_usage);
641 head = resolve_ref("HEAD", head_sha1, 0, NULL);
642 if (!head)
643 die("Failed to resolve HEAD as a valid ref.");
644 head = xstrdup(head);
645 if (!strcmp(head, "HEAD")) {
646 detached = 1;
648 else {
649 if (prefixcmp(head, "refs/heads/"))
650 die("HEAD not found below refs/heads!");
651 head += 11;
654 if (delete)
655 return delete_branches(argc - i, argv + i, force_delete, kinds);
656 else if (i == argc)
657 print_ref_list(kinds, detached, verbose, abbrev);
658 else if (rename && (i == argc - 1))
659 rename_branch(head, argv[i], force_rename);
660 else if (rename && (i == argc - 2))
661 rename_branch(argv[i], argv[i + 1], force_rename);
662 else if (i == argc - 1 || i == argc - 2)
663 create_branch(argv[i], (i == argc - 2) ? argv[i+1] : head,
664 force_create, reflog, track);
665 else
666 usage(builtin_branch_usage);
668 return 0;