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
14static 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]]";
16
17#define REF_UNKNOWN_TYPE 0x00
18#define REF_LOCAL_BRANCH 0x01
19#define REF_REMOTE_BRANCH 0x02
20#define REF_TAG 0x04
21
22static const char *head;
23static unsigned char head_sha1[20];
24
25static int branch_track_remotes;
26
27static int branch_use_color;
28static 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) */
34};
35enum 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,
41};
42
43static int parse_branch_color_slot(const char *var, int ofs)
44{
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);
56}
57
58int git_branch_config(const char *var, const char *value)
59{
60 if (!strcmp(var, "color.branch")) {
61 branch_use_color = git_config_colorbool(var, value);
62 return 0;
63 }
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;
68 }
69 if (!strcmp(var, "branch.autosetupmerge"))
70 branch_track_remotes = git_config_bool(var, value);
71
72 return git_default_config(var, value);
73}
74
75const char *branch_get_color(enum color_branch ix)
76{
77 if (branch_use_color)
78 return branch_colors[ix];
79 return "";
80}
81
82static int delete_branches(int argc, const char **argv, int force, int kinds)
83{
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;
90
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");
103 }
104
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");
109 }
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;
116 }
117
118 if (name)
119 free(name);
120
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;
127 }
128
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;
134 }
135
136 /* This checks whether the merge bases of branch and
137 * HEAD contains branch -- which means that the HEAD
138 * contains everything in both.
139 */
140
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;
149 }
150
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]);
157
158 }
159
160 if (name)
161 free(name);
162
163 return(ret);
164}
165
166struct ref_item {
167 char *name;
168 unsigned int kind;
169 unsigned char sha1[20];
170};
171
172struct ref_list {
173 int index, alloc, maxwidth;
174 struct ref_item *list;
175 int kinds;
176};
177
178static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
179{
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;
184
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;
195 }
196
197 /* Don't add types the caller doesn't want */
198 if ((kind & ref_list->kinds) == 0)
199 return 0;
200
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));
206 }
207
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;
216
217 return 0;
218}
219
220static void free_ref_list(struct ref_list *ref_list)
221{
222 int i;
223
224 for (i = 0; i < ref_list->index; i++)
225 free(ref_list->list[i].name);
226 free(ref_list->list);
227}
228
229static int ref_cmp(const void *r1, const void *r2)
230{
231 struct ref_item *c1 = (struct ref_item *)(r1);
232 struct ref_item *c2 = (struct ref_item *)(r2);
233
234 if (c1->kind != c2->kind)
235 return c1->kind - c2->kind;
236 return strcmp(c1->name, c2->name);
237}
238
239static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
240 int abbrev, int current)
241{
242 char c;
243 int color;
244 struct commit *commit;
245 char subject[256];
246
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;
257 }
258
259 c = ' ';
260 if (current) {
261 c = '*';
262 color = COLOR_BRANCH_CURRENT;
263 }
264
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));
280 }
281}
282
283static void print_ref_list(int kinds, int detached, int verbose, int abbrev)
284{
285 int i;
286 struct ref_list ref_list;
287
288 memset(&ref_list, 0, sizeof(ref_list));
289 ref_list.kinds = kinds;
290 for_each_ref(append_ref, &ref_list);
291
292 qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
293
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);
304 }
305
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);
312 }
313
314 free_ref_list(&ref_list);
315}
316
317static char *config_repo;
318static char *config_remote;
319static const char *start_ref;
320static int start_len;
321static int base_len;
322
323static int get_remote_branch_name(const char *value)
324{
325 const char *colon;
326 const char *end;
327
328 if (*value == '+')
329 value++;
330
331 colon = strchr(value, ':');
332 if (!colon)
333 return 0;
334
335 end = value + strlen(value);
336
337 /* Try an exact match first. */
338 if (!strcmp(colon + 1, start_ref)) {
339 /* Truncate the value before the colon. */
340 nfasprintf(&config_repo, "%.*s", colon - value, value);
341 return 1;
342 }
343
344 /* Try with a wildcard match now. */
345 if (end - value > 2 && end[-2] == '/' && end[-1] == '*' &&
346 colon - value > 2 && colon[-2] == '/' && colon[-1] == '*' &&
347 (end - 2) - (colon + 1) == base_len &&
348 !strncmp(colon + 1, start_ref, base_len)) {
349 /* Replace the star with the remote branch name. */
350 nfasprintf(&config_repo, "%.*s%s",
351 (colon - 2) - value, value,
352 start_ref + base_len);
353 return 1;
354 }
355
356 return 0;
357}
358
359static int get_remote_config(const char *key, const char *value)
360{
361 const char *var;
362 if (prefixcmp(key, "remote."))
363 return 0;
364
365 var = strrchr(key, '.');
366 if (var == key + 6)
367 return 0;
368
369 if (!strcmp(var, ".fetch") && get_remote_branch_name(value))
370 nfasprintf(&config_remote, "%.*s", var - (key + 7), key + 7);
371
372 return 0;
373}
374
375static void set_branch_defaults(const char *name, const char *real_ref)
376{
377 char key[1024];
378 const char *slash = strrchr(real_ref, '/');
379
380 if (!slash)
381 return;
382
383 start_ref = real_ref;
384 start_len = strlen(real_ref);
385 base_len = slash - real_ref;
386 git_config(get_remote_config);
387
388 if (config_repo && config_remote) {
389 if (sizeof(key) <=
390 snprintf(key, sizeof(key), "branch.%s.remote", name))
391 die("what a long branch name you have!");
392 git_config_set(key, config_remote);
393
394 /*
395 * We do not have to check if we have enough space for
396 * the 'merge' key, since it's shorter than the
397 * previous 'remote' key, which we already checked.
398 */
399 snprintf(key, sizeof(key), "branch.%s.merge", name);
400 git_config_set(key, config_repo);
401
402 printf("Branch %s set up to track remote branch %s.\n",
403 name, real_ref);
404 }
405
406 if (config_repo)
407 free(config_repo);
408 if (config_remote)
409 free(config_remote);
410}
411
412static void create_branch(const char *name, const char *start_name,
413 int force, int reflog, int track)
414{
415 struct ref_lock *lock;
416 struct commit *commit;
417 unsigned char sha1[20];
418 char *real_ref, ref[PATH_MAX], msg[PATH_MAX + 20];
419 int forcing = 0;
420
421 snprintf(ref, sizeof ref, "refs/heads/%s", name);
422 if (check_ref_format(ref))
423 die("'%s' is not a valid branch name.", name);
424
425 if (resolve_ref(ref, sha1, 1, NULL)) {
426 if (!force)
427 die("A branch named '%s' already exists.", name);
428 else if (!is_bare_repository() && !strcmp(head, name))
429 die("Cannot force update the current branch.");
430 forcing = 1;
431 }
432
433 real_ref = NULL;
434 if (get_sha1(start_name, sha1))
435 die("Not a valid object name: '%s'.", start_name);
436
437 switch (dwim_ref(start_name, strlen(start_name), sha1, &real_ref)) {
438 case 0:
439 /* Not branching from any existing branch */
440 real_ref = NULL;
441 break;
442 case 1:
443 /* Unique completion -- good */
444 break;
445 default:
446 die("Ambiguous object name: '%s'.", start_name);
447 break;
448 }
449
450 if ((commit = lookup_commit_reference(sha1)) == NULL)
451 die("Not a valid branch point: '%s'.", start_name);
452 hashcpy(sha1, commit->object.sha1);
453
454 lock = lock_any_ref_for_update(ref, NULL);
455 if (!lock)
456 die("Failed to lock ref for update: %s.", strerror(errno));
457
458 if (reflog)
459 log_all_ref_updates = 1;
460
461 if (forcing)
462 snprintf(msg, sizeof msg, "branch: Reset from %s",
463 start_name);
464 else
465 snprintf(msg, sizeof msg, "branch: Created from %s",
466 start_name);
467
468 /* When branching off a remote branch, set up so that git-pull
469 automatically merges from there. So far, this is only done for
470 remotes registered via .git/config. */
471 if (real_ref && track)
472 set_branch_defaults(name, real_ref);
473
474 if (write_ref_sha1(lock, sha1, msg) < 0)
475 die("Failed to write ref: %s.", strerror(errno));
476
477 if (real_ref)
478 free(real_ref);
479}
480
481static void rename_branch(const char *oldname, const char *newname, int force)
482{
483 char oldref[PATH_MAX], newref[PATH_MAX], logmsg[PATH_MAX*2 + 100];
484 unsigned char sha1[20];
485
486 if (!oldname)
487 die("cannot rename the current branch while not on any.");
488
489 if (snprintf(oldref, sizeof(oldref), "refs/heads/%s", oldname) > sizeof(oldref))
490 die("Old branchname too long");
491
492 if (check_ref_format(oldref))
493 die("Invalid branch name: %s", oldref);
494
495 if (snprintf(newref, sizeof(newref), "refs/heads/%s", newname) > sizeof(newref))
496 die("New branchname too long");
497
498 if (check_ref_format(newref))
499 die("Invalid branch name: %s", newref);
500
501 if (resolve_ref(newref, sha1, 1, NULL) && !force)
502 die("A branch named '%s' already exists.", newname);
503
504 snprintf(logmsg, sizeof(logmsg), "Branch: renamed %s to %s",
505 oldref, newref);
506
507 if (rename_ref(oldref, newref, logmsg))
508 die("Branch rename failed");
509
510 /* no need to pass logmsg here as HEAD didn't really move */
511 if (!strcmp(oldname, head) && create_symref("HEAD", newref, NULL))
512 die("Branch renamed to %s, but HEAD is not updated!", newname);
513}
514
515int cmd_branch(int argc, const char **argv, const char *prefix)
516{
517 int delete = 0, force_delete = 0, force_create = 0;
518 int rename = 0, force_rename = 0;
519 int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
520 int reflog = 0, track;
521 int kinds = REF_LOCAL_BRANCH;
522 int i;
523
524 git_config(git_branch_config);
525 track = branch_track_remotes;
526
527 for (i = 1; i < argc; i++) {
528 const char *arg = argv[i];
529
530 if (arg[0] != '-')
531 break;
532 if (!strcmp(arg, "--")) {
533 i++;
534 break;
535 }
536 if (!strcmp(arg, "--track")) {
537 track = 1;
538 continue;
539 }
540 if (!strcmp(arg, "--no-track")) {
541 track = 0;
542 continue;
543 }
544 if (!strcmp(arg, "-d")) {
545 delete = 1;
546 continue;
547 }
548 if (!strcmp(arg, "-D")) {
549 delete = 1;
550 force_delete = 1;
551 continue;
552 }
553 if (!strcmp(arg, "-f")) {
554 force_create = 1;
555 continue;
556 }
557 if (!strcmp(arg, "-m")) {
558 rename = 1;
559 continue;
560 }
561 if (!strcmp(arg, "-M")) {
562 rename = 1;
563 force_rename = 1;
564 continue;
565 }
566 if (!strcmp(arg, "-r")) {
567 kinds = REF_REMOTE_BRANCH;
568 continue;
569 }
570 if (!strcmp(arg, "-a")) {
571 kinds = REF_REMOTE_BRANCH | REF_LOCAL_BRANCH;
572 continue;
573 }
574 if (!strcmp(arg, "-l")) {
575 reflog = 1;
576 continue;
577 }
578 if (!prefixcmp(arg, "--no-abbrev")) {
579 abbrev = 0;
580 continue;
581 }
582 if (!prefixcmp(arg, "--abbrev=")) {
583 abbrev = strtoul(arg + 9, NULL, 10);
584 if (abbrev < MINIMUM_ABBREV)
585 abbrev = MINIMUM_ABBREV;
586 else if (abbrev > 40)
587 abbrev = 40;
588 continue;
589 }
590 if (!strcmp(arg, "-v")) {
591 verbose = 1;
592 continue;
593 }
594 if (!strcmp(arg, "--color")) {
595 branch_use_color = 1;
596 continue;
597 }
598 if (!strcmp(arg, "--no-color")) {
599 branch_use_color = 0;
600 continue;
601 }
602 usage(builtin_branch_usage);
603 }
604
605 if ((delete && rename) || (delete && force_create) ||
606 (rename && force_create))
607 usage(builtin_branch_usage);
608
609 head = xstrdup(resolve_ref("HEAD", head_sha1, 0, NULL));
610 if (!head)
611 die("Failed to resolve HEAD as a valid ref.");
612 if (!strcmp(head, "HEAD")) {
613 detached = 1;
614 }
615 else {
616 if (prefixcmp(head, "refs/heads/"))
617 die("HEAD not found below refs/heads!");
618 head += 11;
619 }
620
621 if (delete)
622 return delete_branches(argc - i, argv + i, force_delete, kinds);
623 else if (i == argc)
624 print_ref_list(kinds, detached, verbose, abbrev);
625 else if (rename && (i == argc - 1))
626 rename_branch(head, argv[i], force_rename);
627 else if (rename && (i == argc - 2))
628 rename_branch(argv[i], argv[i + 1], force_rename);
629 else if (i == argc - 1 || i == argc - 2)
630 create_branch(argv[i], (i == argc - 2) ? argv[i+1] : head,
631 force_create, reflog, track);
632 else
633 usage(builtin_branch_usage);
634
635 return 0;
636}