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 */
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"
16 static const char * const builtin_branch_usage[] = {
17 "git-branch [options] [-r | -a]",
18 "git-branch [options] [-l] [-f] <branchname> [<start-point>]",
19 "git-branch [options] [-r] (-d | -D) <branchname>",
20 "git-branch [options] (-m | -M) [<oldbranch>] <newbranch>",
21 NULL
22 };
24 #define REF_UNKNOWN_TYPE 0x00
25 #define REF_LOCAL_BRANCH 0x01
26 #define REF_REMOTE_BRANCH 0x02
27 #define REF_TAG 0x04
29 static const char *head;
30 static unsigned char head_sha1[20];
32 static int branch_track = 1;
34 static int branch_use_color;
35 static char branch_colors[][COLOR_MAXLEN] = {
36 "\033[m", /* reset */
37 "", /* PLAIN (normal) */
38 "\033[31m", /* REMOTE (red) */
39 "", /* LOCAL (normal) */
40 "\033[32m", /* CURRENT (green) */
41 };
42 enum color_branch {
43 COLOR_BRANCH_RESET = 0,
44 COLOR_BRANCH_PLAIN = 1,
45 COLOR_BRANCH_REMOTE = 2,
46 COLOR_BRANCH_LOCAL = 3,
47 COLOR_BRANCH_CURRENT = 4,
48 };
50 static int parse_branch_color_slot(const char *var, int ofs)
51 {
52 if (!strcasecmp(var+ofs, "plain"))
53 return COLOR_BRANCH_PLAIN;
54 if (!strcasecmp(var+ofs, "reset"))
55 return COLOR_BRANCH_RESET;
56 if (!strcasecmp(var+ofs, "remote"))
57 return COLOR_BRANCH_REMOTE;
58 if (!strcasecmp(var+ofs, "local"))
59 return COLOR_BRANCH_LOCAL;
60 if (!strcasecmp(var+ofs, "current"))
61 return COLOR_BRANCH_CURRENT;
62 die("bad config variable '%s'", var);
63 }
65 static int git_branch_config(const char *var, const char *value)
66 {
67 if (!strcmp(var, "color.branch")) {
68 branch_use_color = git_config_colorbool(var, value, -1);
69 return 0;
70 }
71 if (!prefixcmp(var, "color.branch.")) {
72 int slot = parse_branch_color_slot(var, 13);
73 if (!value)
74 return config_error_nonbool(var);
75 color_parse(value, var, branch_colors[slot]);
76 return 0;
77 }
78 if (!strcmp(var, "branch.autosetupmerge")) {
79 branch_track = git_config_bool(var, value);
80 return 0;
81 }
82 return git_default_config(var, value);
83 }
85 static const char *branch_get_color(enum color_branch ix)
86 {
87 if (branch_use_color)
88 return branch_colors[ix];
89 return "";
90 }
92 static int delete_branches(int argc, const char **argv, int force, int kinds)
93 {
94 struct commit *rev, *head_rev = head_rev;
95 unsigned char sha1[20];
96 char *name = NULL;
97 const char *fmt, *remote;
98 char section[PATH_MAX];
99 int i;
100 int ret = 0;
102 switch (kinds) {
103 case REF_REMOTE_BRANCH:
104 fmt = "refs/remotes/%s";
105 remote = "remote ";
106 force = 1;
107 break;
108 case REF_LOCAL_BRANCH:
109 fmt = "refs/heads/%s";
110 remote = "";
111 break;
112 default:
113 die("cannot use -a with -d");
114 }
116 if (!force) {
117 head_rev = lookup_commit_reference(head_sha1);
118 if (!head_rev)
119 die("Couldn't look up commit object for HEAD");
120 }
121 for (i = 0; i < argc; i++) {
122 if (kinds == REF_LOCAL_BRANCH && !strcmp(head, argv[i])) {
123 error("Cannot delete the branch '%s' "
124 "which you are currently on.", argv[i]);
125 ret = 1;
126 continue;
127 }
129 if (name)
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;
138 }
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;
145 }
147 /* This checks whether the merge bases of branch and
148 * HEAD contains branch -- which means that the HEAD
149 * contains everything in both.
150 */
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;
160 }
162 if (delete_ref(name, sha1)) {
163 error("Error deleting %sbranch '%s'", remote,
164 argv[i]);
165 ret = 1;
166 } else {
167 printf("Deleted %sbranch %s.\n", remote, argv[i]);
168 snprintf(section, sizeof(section), "branch.%s",
169 argv[i]);
170 if (git_config_rename_section(section, NULL) < 0)
171 warning("Update of config-file failed");
172 }
173 }
175 if (name)
176 free(name);
178 return(ret);
179 }
181 struct ref_item {
182 char *name;
183 unsigned int kind;
184 unsigned char sha1[20];
185 };
187 struct ref_list {
188 int index, alloc, maxwidth;
189 struct ref_item *list;
190 struct commit_list *with_commit;
191 int kinds;
192 };
194 static int has_commit(const unsigned char *sha1, struct commit_list *with_commit)
195 {
196 struct commit *commit;
198 if (!with_commit)
199 return 1;
200 commit = lookup_commit_reference_gently(sha1, 1);
201 if (!commit)
202 return 0;
203 while (with_commit) {
204 struct commit *other;
206 other = with_commit->item;
207 with_commit = with_commit->next;
208 if (in_merge_bases(other, &commit, 1))
209 return 1;
210 }
211 return 0;
212 }
214 static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
215 {
216 struct ref_list *ref_list = (struct ref_list*)(cb_data);
217 struct ref_item *newitem;
218 int kind = REF_UNKNOWN_TYPE;
219 int len;
221 /* Detect kind */
222 if (!prefixcmp(refname, "refs/heads/")) {
223 kind = REF_LOCAL_BRANCH;
224 refname += 11;
225 } else if (!prefixcmp(refname, "refs/remotes/")) {
226 kind = REF_REMOTE_BRANCH;
227 refname += 13;
228 } else if (!prefixcmp(refname, "refs/tags/")) {
229 kind = REF_TAG;
230 refname += 10;
231 }
233 /* Filter with with_commit if specified */
234 if (!has_commit(sha1, ref_list->with_commit))
235 return 0;
237 /* Don't add types the caller doesn't want */
238 if ((kind & ref_list->kinds) == 0)
239 return 0;
241 /* Resize buffer */
242 if (ref_list->index >= ref_list->alloc) {
243 ref_list->alloc = alloc_nr(ref_list->alloc);
244 ref_list->list = xrealloc(ref_list->list,
245 ref_list->alloc * sizeof(struct ref_item));
246 }
248 /* Record the new item */
249 newitem = &(ref_list->list[ref_list->index++]);
250 newitem->name = xstrdup(refname);
251 newitem->kind = kind;
252 hashcpy(newitem->sha1, sha1);
253 len = strlen(newitem->name);
254 if (len > ref_list->maxwidth)
255 ref_list->maxwidth = len;
257 return 0;
258 }
260 static void free_ref_list(struct ref_list *ref_list)
261 {
262 int i;
264 for (i = 0; i < ref_list->index; i++)
265 free(ref_list->list[i].name);
266 free(ref_list->list);
267 }
269 static int ref_cmp(const void *r1, const void *r2)
270 {
271 struct ref_item *c1 = (struct ref_item *)(r1);
272 struct ref_item *c2 = (struct ref_item *)(r2);
274 if (c1->kind != c2->kind)
275 return c1->kind - c2->kind;
276 return strcmp(c1->name, c2->name);
277 }
279 static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
280 int abbrev, int current)
281 {
282 char c;
283 int color;
284 struct commit *commit;
286 switch (item->kind) {
287 case REF_LOCAL_BRANCH:
288 color = COLOR_BRANCH_LOCAL;
289 break;
290 case REF_REMOTE_BRANCH:
291 color = COLOR_BRANCH_REMOTE;
292 break;
293 default:
294 color = COLOR_BRANCH_PLAIN;
295 break;
296 }
298 c = ' ';
299 if (current) {
300 c = '*';
301 color = COLOR_BRANCH_CURRENT;
302 }
304 if (verbose) {
305 struct strbuf subject;
306 const char *sub = " **** invalid ref ****";
308 strbuf_init(&subject, 0);
310 commit = lookup_commit(item->sha1);
311 if (commit && !parse_commit(commit)) {
312 pretty_print_commit(CMIT_FMT_ONELINE, commit,
313 &subject, 0, NULL, NULL, 0, 0);
314 sub = subject.buf;
315 }
316 printf("%c %s%-*s%s %s %s\n", c, branch_get_color(color),
317 maxwidth, item->name,
318 branch_get_color(COLOR_BRANCH_RESET),
319 find_unique_abbrev(item->sha1, abbrev), sub);
320 strbuf_release(&subject);
321 } else {
322 printf("%c %s%s%s\n", c, branch_get_color(color), item->name,
323 branch_get_color(COLOR_BRANCH_RESET));
324 }
325 }
327 static void print_ref_list(int kinds, int detached, int verbose, int abbrev, struct commit_list *with_commit)
328 {
329 int i;
330 struct ref_list ref_list;
332 memset(&ref_list, 0, sizeof(ref_list));
333 ref_list.kinds = kinds;
334 ref_list.with_commit = with_commit;
335 for_each_ref(append_ref, &ref_list);
337 qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
339 detached = (detached && (kinds & REF_LOCAL_BRANCH));
340 if (detached && has_commit(head_sha1, with_commit)) {
341 struct ref_item item;
342 item.name = xstrdup("(no branch)");
343 item.kind = REF_LOCAL_BRANCH;
344 hashcpy(item.sha1, head_sha1);
345 if (strlen(item.name) > ref_list.maxwidth)
346 ref_list.maxwidth = strlen(item.name);
347 print_ref_item(&item, ref_list.maxwidth, verbose, abbrev, 1);
348 free(item.name);
349 }
351 for (i = 0; i < ref_list.index; i++) {
352 int current = !detached &&
353 (ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
354 !strcmp(ref_list.list[i].name, head);
355 print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
356 abbrev, current);
357 }
359 free_ref_list(&ref_list);
360 }
362 struct tracking {
363 struct refspec spec;
364 char *src;
365 const char *remote;
366 int matches;
367 };
369 static int find_tracked_branch(struct remote *remote, void *priv)
370 {
371 struct tracking *tracking = priv;
373 if (!remote_find_tracking(remote, &tracking->spec)) {
374 if (++tracking->matches == 1) {
375 tracking->src = tracking->spec.src;
376 tracking->remote = remote->name;
377 } else {
378 free(tracking->spec.src);
379 if (tracking->src) {
380 free(tracking->src);
381 tracking->src = NULL;
382 }
383 }
384 tracking->spec.src = NULL;
385 }
387 return 0;
388 }
391 /*
392 * This is called when new_ref is branched off of orig_ref, and tries
393 * to infer the settings for branch.<new_ref>.{remote,merge} from the
394 * config.
395 */
396 static int setup_tracking(const char *new_ref, const char *orig_ref)
397 {
398 char key[1024];
399 struct tracking tracking;
401 if (strlen(new_ref) > 1024 - 7 - 7 - 1)
402 return error("Tracking not set up: name too long: %s",
403 new_ref);
405 memset(&tracking, 0, sizeof(tracking));
406 tracking.spec.dst = (char *)orig_ref;
407 if (for_each_remote(find_tracked_branch, &tracking) ||
408 !tracking.matches)
409 return 1;
411 if (tracking.matches > 1)
412 return error("Not tracking: ambiguous information for ref %s",
413 orig_ref);
415 if (tracking.matches == 1) {
416 sprintf(key, "branch.%s.remote", new_ref);
417 git_config_set(key, tracking.remote ? tracking.remote : ".");
418 sprintf(key, "branch.%s.merge", new_ref);
419 git_config_set(key, tracking.src);
420 free(tracking.src);
421 printf("Branch %s set up to track remote branch %s.\n",
422 new_ref, orig_ref);
423 }
425 return 0;
426 }
428 static void create_branch(const char *name, const char *start_name,
429 int force, int reflog, int track)
430 {
431 struct ref_lock *lock;
432 struct commit *commit;
433 unsigned char sha1[20];
434 char *real_ref, ref[PATH_MAX], msg[PATH_MAX + 20];
435 int forcing = 0;
437 snprintf(ref, sizeof ref, "refs/heads/%s", name);
438 if (check_ref_format(ref))
439 die("'%s' is not a valid branch name.", name);
441 if (resolve_ref(ref, sha1, 1, NULL)) {
442 if (!force)
443 die("A branch named '%s' already exists.", name);
444 else if (!is_bare_repository() && !strcmp(head, name))
445 die("Cannot force update the current branch.");
446 forcing = 1;
447 }
449 real_ref = NULL;
450 if (get_sha1(start_name, sha1))
451 die("Not a valid object name: '%s'.", start_name);
453 switch (dwim_ref(start_name, strlen(start_name), sha1, &real_ref)) {
454 case 0:
455 /* Not branching from any existing branch */
456 real_ref = NULL;
457 break;
458 case 1:
459 /* Unique completion -- good */
460 break;
461 default:
462 die("Ambiguous object name: '%s'.", start_name);
463 break;
464 }
466 if ((commit = lookup_commit_reference(sha1)) == NULL)
467 die("Not a valid branch point: '%s'.", start_name);
468 hashcpy(sha1, commit->object.sha1);
470 lock = lock_any_ref_for_update(ref, NULL, 0);
471 if (!lock)
472 die("Failed to lock ref for update: %s.", strerror(errno));
474 if (reflog)
475 log_all_ref_updates = 1;
477 if (forcing)
478 snprintf(msg, sizeof msg, "branch: Reset from %s",
479 start_name);
480 else
481 snprintf(msg, sizeof msg, "branch: Created from %s",
482 start_name);
484 /* When branching off a remote branch, set up so that git-pull
485 automatically merges from there. So far, this is only done for
486 remotes registered via .git/config. */
487 if (real_ref && track)
488 setup_tracking(name, real_ref);
490 if (write_ref_sha1(lock, sha1, msg) < 0)
491 die("Failed to write ref: %s.", strerror(errno));
493 if (real_ref)
494 free(real_ref);
495 }
497 static void rename_branch(const char *oldname, const char *newname, int force)
498 {
499 char oldref[PATH_MAX], newref[PATH_MAX], logmsg[PATH_MAX*2 + 100];
500 unsigned char sha1[20];
501 char oldsection[PATH_MAX], newsection[PATH_MAX];
503 if (!oldname)
504 die("cannot rename the current branch while not on any.");
506 if (snprintf(oldref, sizeof(oldref), "refs/heads/%s", oldname) > sizeof(oldref))
507 die("Old branchname too long");
509 if (check_ref_format(oldref))
510 die("Invalid branch name: %s", oldref);
512 if (snprintf(newref, sizeof(newref), "refs/heads/%s", newname) > sizeof(newref))
513 die("New branchname too long");
515 if (check_ref_format(newref))
516 die("Invalid branch name: %s", newref);
518 if (resolve_ref(newref, sha1, 1, NULL) && !force)
519 die("A branch named '%s' already exists.", newname);
521 snprintf(logmsg, sizeof(logmsg), "Branch: renamed %s to %s",
522 oldref, newref);
524 if (rename_ref(oldref, newref, logmsg))
525 die("Branch rename failed");
527 /* no need to pass logmsg here as HEAD didn't really move */
528 if (!strcmp(oldname, head) && create_symref("HEAD", newref, NULL))
529 die("Branch renamed to %s, but HEAD is not updated!", newname);
531 snprintf(oldsection, sizeof(oldsection), "branch.%s", oldref + 11);
532 snprintf(newsection, sizeof(newsection), "branch.%s", newref + 11);
533 if (git_config_rename_section(oldsection, newsection) < 0)
534 die("Branch is renamed, but update of config-file failed");
535 }
537 static int opt_parse_with_commit(const struct option *opt, const char *arg, int unset)
538 {
539 unsigned char sha1[20];
540 struct commit *commit;
542 if (!arg)
543 return -1;
544 if (get_sha1(arg, sha1))
545 die("malformed object name %s", arg);
546 commit = lookup_commit_reference(sha1);
547 if (!commit)
548 die("no such commit %s", arg);
549 commit_list_insert(commit, opt->value);
550 return 0;
551 }
553 int cmd_branch(int argc, const char **argv, const char *prefix)
554 {
555 int delete = 0, rename = 0, force_create = 0;
556 int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
557 int reflog = 0, track;
558 int kinds = REF_LOCAL_BRANCH;
559 struct commit_list *with_commit = NULL;
561 struct option options[] = {
562 OPT_GROUP("Generic options"),
563 OPT__VERBOSE(&verbose),
564 OPT_BOOLEAN( 0 , "track", &track, "set up tracking mode (see git-pull(1))"),
565 OPT_BOOLEAN( 0 , "color", &branch_use_color, "use colored output"),
566 OPT_SET_INT('r', NULL, &kinds, "act on remote-tracking branches",
567 REF_REMOTE_BRANCH),
568 OPT_CALLBACK(0, "contains", &with_commit, "commit",
569 "print only branches that contain the commit",
570 opt_parse_with_commit),
571 {
572 OPTION_CALLBACK, 0, "with", &with_commit, "commit",
573 "print only branches that contain the commit",
574 PARSE_OPT_HIDDEN, opt_parse_with_commit,
575 },
576 OPT__ABBREV(&abbrev),
578 OPT_GROUP("Specific git-branch actions:"),
579 OPT_SET_INT('a', NULL, &kinds, "list both remote-tracking and local branches",
580 REF_REMOTE_BRANCH | REF_LOCAL_BRANCH),
581 OPT_BIT('d', NULL, &delete, "delete fully merged branch", 1),
582 OPT_BIT('D', NULL, &delete, "delete branch (even if not merged)", 2),
583 OPT_BIT('m', NULL, &rename, "move/rename a branch and its reflog", 1),
584 OPT_BIT('M', NULL, &rename, "move/rename a branch, even if target exists", 2),
585 OPT_BOOLEAN('l', NULL, &reflog, "create the branch's reflog"),
586 OPT_BOOLEAN('f', NULL, &force_create, "force creation (when already exists)"),
587 OPT_END(),
588 };
590 git_config(git_branch_config);
591 track = branch_track;
592 argc = parse_options(argc, argv, options, builtin_branch_usage, 0);
593 if (!!delete + !!rename + !!force_create > 1)
594 usage_with_options(builtin_branch_usage, options);
596 head = resolve_ref("HEAD", head_sha1, 0, NULL);
597 if (!head)
598 die("Failed to resolve HEAD as a valid ref.");
599 head = xstrdup(head);
600 if (!strcmp(head, "HEAD")) {
601 detached = 1;
602 } else {
603 if (prefixcmp(head, "refs/heads/"))
604 die("HEAD not found below refs/heads!");
605 head += 11;
606 }
608 if (delete)
609 return delete_branches(argc, argv, delete > 1, kinds);
610 else if (argc == 0)
611 print_ref_list(kinds, detached, verbose, abbrev, with_commit);
612 else if (rename && (argc == 1))
613 rename_branch(head, argv[0], rename > 1);
614 else if (rename && (argc == 2))
615 rename_branch(argv[0], argv[1], rename > 1);
616 else if (argc <= 2)
617 create_branch(argv[0], (argc == 2) ? argv[1] : head,
618 force_create, reflog, track);
619 else
620 usage_with_options(builtin_branch_usage, options);
622 return 0;
623 }