]> git.ipfire.org Git - thirdparty/git.git/blob - builtin-branch.c
Avoid unnecessary "if-before-free" tests.
[thirdparty/git.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
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 };
23
24 #define REF_UNKNOWN_TYPE 0x00
25 #define REF_LOCAL_BRANCH 0x01
26 #define REF_REMOTE_BRANCH 0x02
27 #define REF_TAG 0x04
28
29 static const char *head;
30 static unsigned char head_sha1[20];
31
32 static int branch_track = 1;
33
34 static int branch_use_color = -1;
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 };
49
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 }
64
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_color_default_config(var, value);
83 }
84
85 static const char *branch_get_color(enum color_branch ix)
86 {
87 if (branch_use_color > 0)
88 return branch_colors[ix];
89 return "";
90 }
91
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;
101
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 }
115
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 }
128
129 free(name);
130
131 name = xstrdup(mkpath(fmt, argv[i]));
132 if (!resolve_ref(name, sha1, 1, NULL)) {
133 error("%sbranch '%s' not found.",
134 remote, argv[i]);
135 ret = 1;
136 continue;
137 }
138
139 rev = lookup_commit_reference(sha1);
140 if (!rev) {
141 error("Couldn't look up commit object for '%s'", name);
142 ret = 1;
143 continue;
144 }
145
146 /* This checks whether the merge bases of branch and
147 * HEAD contains branch -- which means that the HEAD
148 * contains everything in both.
149 */
150
151 if (!force &&
152 !in_merge_bases(rev, &head_rev, 1)) {
153 error("The branch '%s' is not an ancestor of "
154 "your current HEAD.\n"
155 "If you are sure you want to delete it, "
156 "run 'git branch -D %s'.", argv[i], argv[i]);
157 ret = 1;
158 continue;
159 }
160
161 if (delete_ref(name, sha1)) {
162 error("Error deleting %sbranch '%s'", remote,
163 argv[i]);
164 ret = 1;
165 } else {
166 printf("Deleted %sbranch %s.\n", remote, argv[i]);
167 snprintf(section, sizeof(section), "branch.%s",
168 argv[i]);
169 if (git_config_rename_section(section, NULL) < 0)
170 warning("Update of config-file failed");
171 }
172 }
173
174 free(name);
175
176 return(ret);
177 }
178
179 struct ref_item {
180 char *name;
181 unsigned int kind;
182 unsigned char sha1[20];
183 };
184
185 struct ref_list {
186 int index, alloc, maxwidth;
187 struct ref_item *list;
188 struct commit_list *with_commit;
189 int kinds;
190 };
191
192 static int has_commit(const unsigned char *sha1, struct commit_list *with_commit)
193 {
194 struct commit *commit;
195
196 if (!with_commit)
197 return 1;
198 commit = lookup_commit_reference_gently(sha1, 1);
199 if (!commit)
200 return 0;
201 while (with_commit) {
202 struct commit *other;
203
204 other = with_commit->item;
205 with_commit = with_commit->next;
206 if (in_merge_bases(other, &commit, 1))
207 return 1;
208 }
209 return 0;
210 }
211
212 static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
213 {
214 struct ref_list *ref_list = (struct ref_list*)(cb_data);
215 struct ref_item *newitem;
216 int kind = REF_UNKNOWN_TYPE;
217 int len;
218
219 /* Detect kind */
220 if (!prefixcmp(refname, "refs/heads/")) {
221 kind = REF_LOCAL_BRANCH;
222 refname += 11;
223 } else if (!prefixcmp(refname, "refs/remotes/")) {
224 kind = REF_REMOTE_BRANCH;
225 refname += 13;
226 } else if (!prefixcmp(refname, "refs/tags/")) {
227 kind = REF_TAG;
228 refname += 10;
229 }
230
231 /* Filter with with_commit if specified */
232 if (!has_commit(sha1, ref_list->with_commit))
233 return 0;
234
235 /* Don't add types the caller doesn't want */
236 if ((kind & ref_list->kinds) == 0)
237 return 0;
238
239 /* Resize buffer */
240 if (ref_list->index >= ref_list->alloc) {
241 ref_list->alloc = alloc_nr(ref_list->alloc);
242 ref_list->list = xrealloc(ref_list->list,
243 ref_list->alloc * sizeof(struct ref_item));
244 }
245
246 /* Record the new item */
247 newitem = &(ref_list->list[ref_list->index++]);
248 newitem->name = xstrdup(refname);
249 newitem->kind = kind;
250 hashcpy(newitem->sha1, sha1);
251 len = strlen(newitem->name);
252 if (len > ref_list->maxwidth)
253 ref_list->maxwidth = len;
254
255 return 0;
256 }
257
258 static void free_ref_list(struct ref_list *ref_list)
259 {
260 int i;
261
262 for (i = 0; i < ref_list->index; i++)
263 free(ref_list->list[i].name);
264 free(ref_list->list);
265 }
266
267 static int ref_cmp(const void *r1, const void *r2)
268 {
269 struct ref_item *c1 = (struct ref_item *)(r1);
270 struct ref_item *c2 = (struct ref_item *)(r2);
271
272 if (c1->kind != c2->kind)
273 return c1->kind - c2->kind;
274 return strcmp(c1->name, c2->name);
275 }
276
277 static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
278 int abbrev, int current)
279 {
280 char c;
281 int color;
282 struct commit *commit;
283
284 switch (item->kind) {
285 case REF_LOCAL_BRANCH:
286 color = COLOR_BRANCH_LOCAL;
287 break;
288 case REF_REMOTE_BRANCH:
289 color = COLOR_BRANCH_REMOTE;
290 break;
291 default:
292 color = COLOR_BRANCH_PLAIN;
293 break;
294 }
295
296 c = ' ';
297 if (current) {
298 c = '*';
299 color = COLOR_BRANCH_CURRENT;
300 }
301
302 if (verbose) {
303 struct strbuf subject;
304 const char *sub = " **** invalid ref ****";
305
306 strbuf_init(&subject, 0);
307
308 commit = lookup_commit(item->sha1);
309 if (commit && !parse_commit(commit)) {
310 pretty_print_commit(CMIT_FMT_ONELINE, commit,
311 &subject, 0, NULL, NULL, 0, 0);
312 sub = subject.buf;
313 }
314 printf("%c %s%-*s%s %s %s\n", c, branch_get_color(color),
315 maxwidth, item->name,
316 branch_get_color(COLOR_BRANCH_RESET),
317 find_unique_abbrev(item->sha1, abbrev), sub);
318 strbuf_release(&subject);
319 } else {
320 printf("%c %s%s%s\n", c, branch_get_color(color), item->name,
321 branch_get_color(COLOR_BRANCH_RESET));
322 }
323 }
324
325 static void print_ref_list(int kinds, int detached, int verbose, int abbrev, struct commit_list *with_commit)
326 {
327 int i;
328 struct ref_list ref_list;
329
330 memset(&ref_list, 0, sizeof(ref_list));
331 ref_list.kinds = kinds;
332 ref_list.with_commit = with_commit;
333 for_each_ref(append_ref, &ref_list);
334
335 qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
336
337 detached = (detached && (kinds & REF_LOCAL_BRANCH));
338 if (detached && has_commit(head_sha1, with_commit)) {
339 struct ref_item item;
340 item.name = xstrdup("(no branch)");
341 item.kind = REF_LOCAL_BRANCH;
342 hashcpy(item.sha1, head_sha1);
343 if (strlen(item.name) > ref_list.maxwidth)
344 ref_list.maxwidth = strlen(item.name);
345 print_ref_item(&item, ref_list.maxwidth, verbose, abbrev, 1);
346 free(item.name);
347 }
348
349 for (i = 0; i < ref_list.index; i++) {
350 int current = !detached &&
351 (ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
352 !strcmp(ref_list.list[i].name, head);
353 print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
354 abbrev, current);
355 }
356
357 free_ref_list(&ref_list);
358 }
359
360 struct tracking {
361 struct refspec spec;
362 char *src;
363 const char *remote;
364 int matches;
365 };
366
367 static int find_tracked_branch(struct remote *remote, void *priv)
368 {
369 struct tracking *tracking = priv;
370
371 if (!remote_find_tracking(remote, &tracking->spec)) {
372 if (++tracking->matches == 1) {
373 tracking->src = tracking->spec.src;
374 tracking->remote = remote->name;
375 } else {
376 free(tracking->spec.src);
377 if (tracking->src) {
378 free(tracking->src);
379 tracking->src = NULL;
380 }
381 }
382 tracking->spec.src = NULL;
383 }
384
385 return 0;
386 }
387
388
389 /*
390 * This is called when new_ref is branched off of orig_ref, and tries
391 * to infer the settings for branch.<new_ref>.{remote,merge} from the
392 * config.
393 */
394 static int setup_tracking(const char *new_ref, const char *orig_ref)
395 {
396 char key[1024];
397 struct tracking tracking;
398
399 if (strlen(new_ref) > 1024 - 7 - 7 - 1)
400 return error("Tracking not set up: name too long: %s",
401 new_ref);
402
403 memset(&tracking, 0, sizeof(tracking));
404 tracking.spec.dst = (char *)orig_ref;
405 if (for_each_remote(find_tracked_branch, &tracking) ||
406 !tracking.matches)
407 return 1;
408
409 if (tracking.matches > 1)
410 return error("Not tracking: ambiguous information for ref %s",
411 orig_ref);
412
413 if (tracking.matches == 1) {
414 sprintf(key, "branch.%s.remote", new_ref);
415 git_config_set(key, tracking.remote ? tracking.remote : ".");
416 sprintf(key, "branch.%s.merge", new_ref);
417 git_config_set(key, tracking.src);
418 free(tracking.src);
419 printf("Branch %s set up to track remote branch %s.\n",
420 new_ref, orig_ref);
421 }
422
423 return 0;
424 }
425
426 static void create_branch(const char *name, const char *start_name,
427 int force, int reflog, int track)
428 {
429 struct ref_lock *lock;
430 struct commit *commit;
431 unsigned char sha1[20];
432 char *real_ref, ref[PATH_MAX], msg[PATH_MAX + 20];
433 int forcing = 0;
434
435 snprintf(ref, sizeof ref, "refs/heads/%s", name);
436 if (check_ref_format(ref))
437 die("'%s' is not a valid branch name.", name);
438
439 if (resolve_ref(ref, sha1, 1, NULL)) {
440 if (!force)
441 die("A branch named '%s' already exists.", name);
442 else if (!is_bare_repository() && !strcmp(head, name))
443 die("Cannot force update the current branch.");
444 forcing = 1;
445 }
446
447 real_ref = NULL;
448 if (get_sha1(start_name, sha1))
449 die("Not a valid object name: '%s'.", start_name);
450
451 switch (dwim_ref(start_name, strlen(start_name), sha1, &real_ref)) {
452 case 0:
453 /* Not branching from any existing branch */
454 real_ref = NULL;
455 break;
456 case 1:
457 /* Unique completion -- good */
458 break;
459 default:
460 die("Ambiguous object name: '%s'.", start_name);
461 break;
462 }
463
464 if ((commit = lookup_commit_reference(sha1)) == NULL)
465 die("Not a valid branch point: '%s'.", start_name);
466 hashcpy(sha1, commit->object.sha1);
467
468 lock = lock_any_ref_for_update(ref, NULL, 0);
469 if (!lock)
470 die("Failed to lock ref for update: %s.", strerror(errno));
471
472 if (reflog)
473 log_all_ref_updates = 1;
474
475 if (forcing)
476 snprintf(msg, sizeof msg, "branch: Reset from %s",
477 start_name);
478 else
479 snprintf(msg, sizeof msg, "branch: Created from %s",
480 start_name);
481
482 /* When branching off a remote branch, set up so that git-pull
483 automatically merges from there. So far, this is only done for
484 remotes registered via .git/config. */
485 if (real_ref && track)
486 setup_tracking(name, real_ref);
487
488 if (write_ref_sha1(lock, sha1, msg) < 0)
489 die("Failed to write ref: %s.", strerror(errno));
490
491 free(real_ref);
492 }
493
494 static void rename_branch(const char *oldname, const char *newname, int force)
495 {
496 char oldref[PATH_MAX], newref[PATH_MAX], logmsg[PATH_MAX*2 + 100];
497 unsigned char sha1[20];
498 char oldsection[PATH_MAX], newsection[PATH_MAX];
499
500 if (!oldname)
501 die("cannot rename the current branch while not on any.");
502
503 if (snprintf(oldref, sizeof(oldref), "refs/heads/%s", oldname) > sizeof(oldref))
504 die("Old branchname too long");
505
506 if (check_ref_format(oldref))
507 die("Invalid branch name: %s", oldref);
508
509 if (snprintf(newref, sizeof(newref), "refs/heads/%s", newname) > sizeof(newref))
510 die("New branchname too long");
511
512 if (check_ref_format(newref))
513 die("Invalid branch name: %s", newref);
514
515 if (resolve_ref(newref, sha1, 1, NULL) && !force)
516 die("A branch named '%s' already exists.", newname);
517
518 snprintf(logmsg, sizeof(logmsg), "Branch: renamed %s to %s",
519 oldref, newref);
520
521 if (rename_ref(oldref, newref, logmsg))
522 die("Branch rename failed");
523
524 /* no need to pass logmsg here as HEAD didn't really move */
525 if (!strcmp(oldname, head) && create_symref("HEAD", newref, NULL))
526 die("Branch renamed to %s, but HEAD is not updated!", newname);
527
528 snprintf(oldsection, sizeof(oldsection), "branch.%s", oldref + 11);
529 snprintf(newsection, sizeof(newsection), "branch.%s", newref + 11);
530 if (git_config_rename_section(oldsection, newsection) < 0)
531 die("Branch is renamed, but update of config-file failed");
532 }
533
534 static int opt_parse_with_commit(const struct option *opt, const char *arg, int unset)
535 {
536 unsigned char sha1[20];
537 struct commit *commit;
538
539 if (!arg)
540 return -1;
541 if (get_sha1(arg, sha1))
542 die("malformed object name %s", arg);
543 commit = lookup_commit_reference(sha1);
544 if (!commit)
545 die("no such commit %s", arg);
546 commit_list_insert(commit, opt->value);
547 return 0;
548 }
549
550 int cmd_branch(int argc, const char **argv, const char *prefix)
551 {
552 int delete = 0, rename = 0, force_create = 0;
553 int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
554 int reflog = 0, track;
555 int kinds = REF_LOCAL_BRANCH;
556 struct commit_list *with_commit = NULL;
557
558 struct option options[] = {
559 OPT_GROUP("Generic options"),
560 OPT__VERBOSE(&verbose),
561 OPT_BOOLEAN( 0 , "track", &track, "set up tracking mode (see git-pull(1))"),
562 OPT_BOOLEAN( 0 , "color", &branch_use_color, "use colored output"),
563 OPT_SET_INT('r', NULL, &kinds, "act on remote-tracking branches",
564 REF_REMOTE_BRANCH),
565 OPT_CALLBACK(0, "contains", &with_commit, "commit",
566 "print only branches that contain the commit",
567 opt_parse_with_commit),
568 {
569 OPTION_CALLBACK, 0, "with", &with_commit, "commit",
570 "print only branches that contain the commit",
571 PARSE_OPT_HIDDEN, opt_parse_with_commit,
572 },
573 OPT__ABBREV(&abbrev),
574
575 OPT_GROUP("Specific git-branch actions:"),
576 OPT_SET_INT('a', NULL, &kinds, "list both remote-tracking and local branches",
577 REF_REMOTE_BRANCH | REF_LOCAL_BRANCH),
578 OPT_BIT('d', NULL, &delete, "delete fully merged branch", 1),
579 OPT_BIT('D', NULL, &delete, "delete branch (even if not merged)", 2),
580 OPT_BIT('m', NULL, &rename, "move/rename a branch and its reflog", 1),
581 OPT_BIT('M', NULL, &rename, "move/rename a branch, even if target exists", 2),
582 OPT_BOOLEAN('l', NULL, &reflog, "create the branch's reflog"),
583 OPT_BOOLEAN('f', NULL, &force_create, "force creation (when already exists)"),
584 OPT_END(),
585 };
586
587 git_config(git_branch_config);
588
589 if (branch_use_color == -1)
590 branch_use_color = git_use_color_default;
591
592 track = branch_track;
593 argc = parse_options(argc, argv, options, builtin_branch_usage, 0);
594 if (!!delete + !!rename + !!force_create > 1)
595 usage_with_options(builtin_branch_usage, options);
596
597 head = resolve_ref("HEAD", head_sha1, 0, NULL);
598 if (!head)
599 die("Failed to resolve HEAD as a valid ref.");
600 head = xstrdup(head);
601 if (!strcmp(head, "HEAD")) {
602 detached = 1;
603 } else {
604 if (prefixcmp(head, "refs/heads/"))
605 die("HEAD not found below refs/heads!");
606 head += 11;
607 }
608
609 if (delete)
610 return delete_branches(argc, argv, delete > 1, kinds);
611 else if (argc == 0)
612 print_ref_list(kinds, detached, verbose, abbrev, with_commit);
613 else if (rename && (argc == 1))
614 rename_branch(head, argv[0], rename > 1);
615 else if (rename && (argc == 2))
616 rename_branch(argv[0], argv[1], rename > 1);
617 else if (argc <= 2)
618 create_branch(argv[0], (argc == 2) ? argv[1] : head,
619 force_create, reflog, track);
620 else
621 usage_with_options(builtin_branch_usage, options);
622
623 return 0;
624 }