]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/branch.c
a67a8334d5cec22124d76161c408e50a6be25c7d
[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 "config.h"
10 #include "color.h"
11 #include "refs.h"
12 #include "commit.h"
13 #include "builtin.h"
14 #include "gettext.h"
15 #include "remote.h"
16 #include "parse-options.h"
17 #include "branch.h"
18 #include "diff.h"
19 #include "revision.h"
20 #include "string-list.h"
21 #include "column.h"
22 #include "utf8.h"
23 #include "wt-status.h"
24 #include "ref-filter.h"
25 #include "worktree.h"
26 #include "help.h"
27 #include "commit-reach.h"
28
29 static const char * const builtin_branch_usage[] = {
30 N_("git branch [<options>] [-r | -a] [--merged] [--no-merged]"),
31 N_("git branch [<options>] [-f] [--recurse-submodules] <branch-name> [<start-point>]"),
32 N_("git branch [<options>] [-l] [<pattern>...]"),
33 N_("git branch [<options>] [-r] (-d | -D) <branch-name>..."),
34 N_("git branch [<options>] (-m | -M) [<old-branch>] <new-branch>"),
35 N_("git branch [<options>] (-c | -C) [<old-branch>] <new-branch>"),
36 N_("git branch [<options>] [-r | -a] [--points-at]"),
37 N_("git branch [<options>] [-r | -a] [--format]"),
38 NULL
39 };
40
41 static const char *head;
42 static struct object_id head_oid;
43 static int recurse_submodules = 0;
44 static int submodule_propagate_branches = 0;
45
46 static int branch_use_color = -1;
47 static char branch_colors[][COLOR_MAXLEN] = {
48 GIT_COLOR_RESET,
49 GIT_COLOR_NORMAL, /* PLAIN */
50 GIT_COLOR_RED, /* REMOTE */
51 GIT_COLOR_NORMAL, /* LOCAL */
52 GIT_COLOR_GREEN, /* CURRENT */
53 GIT_COLOR_BLUE, /* UPSTREAM */
54 GIT_COLOR_CYAN, /* WORKTREE */
55 };
56 enum color_branch {
57 BRANCH_COLOR_RESET = 0,
58 BRANCH_COLOR_PLAIN = 1,
59 BRANCH_COLOR_REMOTE = 2,
60 BRANCH_COLOR_LOCAL = 3,
61 BRANCH_COLOR_CURRENT = 4,
62 BRANCH_COLOR_UPSTREAM = 5,
63 BRANCH_COLOR_WORKTREE = 6
64 };
65
66 static const char *color_branch_slots[] = {
67 [BRANCH_COLOR_RESET] = "reset",
68 [BRANCH_COLOR_PLAIN] = "plain",
69 [BRANCH_COLOR_REMOTE] = "remote",
70 [BRANCH_COLOR_LOCAL] = "local",
71 [BRANCH_COLOR_CURRENT] = "current",
72 [BRANCH_COLOR_UPSTREAM] = "upstream",
73 [BRANCH_COLOR_WORKTREE] = "worktree",
74 };
75
76 static struct string_list output = STRING_LIST_INIT_DUP;
77 static unsigned int colopts;
78
79 define_list_config_array(color_branch_slots);
80
81 static int git_branch_config(const char *var, const char *value, void *cb)
82 {
83 const char *slot_name;
84
85 if (!strcmp(var, "branch.sort")) {
86 if (!value)
87 return config_error_nonbool(var);
88 string_list_append(cb, value);
89 return 0;
90 }
91
92 if (starts_with(var, "column."))
93 return git_column_config(var, value, "branch", &colopts);
94 if (!strcmp(var, "color.branch")) {
95 branch_use_color = git_config_colorbool(var, value);
96 return 0;
97 }
98 if (skip_prefix(var, "color.branch.", &slot_name)) {
99 int slot = LOOKUP_CONFIG(color_branch_slots, slot_name);
100 if (slot < 0)
101 return 0;
102 if (!value)
103 return config_error_nonbool(var);
104 return color_parse(value, branch_colors[slot]);
105 }
106 if (!strcmp(var, "submodule.recurse")) {
107 recurse_submodules = git_config_bool(var, value);
108 return 0;
109 }
110 if (!strcasecmp(var, "submodule.propagateBranches")) {
111 submodule_propagate_branches = git_config_bool(var, value);
112 return 0;
113 }
114
115 return git_color_default_config(var, value, cb);
116 }
117
118 static const char *branch_get_color(enum color_branch ix)
119 {
120 if (want_color(branch_use_color))
121 return branch_colors[ix];
122 return "";
123 }
124
125 static int branch_merged(int kind, const char *name,
126 struct commit *rev, struct commit *head_rev)
127 {
128 /*
129 * This checks whether the merge bases of branch and HEAD (or
130 * the other branch this branch builds upon) contains the
131 * branch, which means that the branch has already been merged
132 * safely to HEAD (or the other branch).
133 */
134 struct commit *reference_rev = NULL;
135 const char *reference_name = NULL;
136 void *reference_name_to_free = NULL;
137 int merged;
138
139 if (kind == FILTER_REFS_BRANCHES) {
140 struct branch *branch = branch_get(name);
141 const char *upstream = branch_get_upstream(branch, NULL);
142 struct object_id oid;
143
144 if (upstream &&
145 (reference_name = reference_name_to_free =
146 resolve_refdup(upstream, RESOLVE_REF_READING,
147 &oid, NULL)) != NULL)
148 reference_rev = lookup_commit_reference(the_repository,
149 &oid);
150 }
151 if (!reference_rev)
152 reference_rev = head_rev;
153
154 merged = reference_rev ? in_merge_bases(rev, reference_rev) : 0;
155
156 /*
157 * After the safety valve is fully redefined to "check with
158 * upstream, if any, otherwise with HEAD", we should just
159 * return the result of the in_merge_bases() above without
160 * any of the following code, but during the transition period,
161 * a gentle reminder is in order.
162 */
163 if ((head_rev != reference_rev) &&
164 (head_rev ? in_merge_bases(rev, head_rev) : 0) != merged) {
165 if (merged)
166 warning(_("deleting branch '%s' that has been merged to\n"
167 " '%s', but not yet merged to HEAD."),
168 name, reference_name);
169 else
170 warning(_("not deleting branch '%s' that is not yet merged to\n"
171 " '%s', even though it is merged to HEAD."),
172 name, reference_name);
173 }
174 free(reference_name_to_free);
175 return merged;
176 }
177
178 static int check_branch_commit(const char *branchname, const char *refname,
179 const struct object_id *oid, struct commit *head_rev,
180 int kinds, int force)
181 {
182 struct commit *rev = lookup_commit_reference(the_repository, oid);
183 if (!force && !rev) {
184 error(_("Couldn't look up commit object for '%s'"), refname);
185 return -1;
186 }
187 if (!force && !branch_merged(kinds, branchname, rev, head_rev)) {
188 error(_("The branch '%s' is not fully merged.\n"
189 "If you are sure you want to delete it, "
190 "run 'git branch -D %s'."), branchname, branchname);
191 return -1;
192 }
193 return 0;
194 }
195
196 static void delete_branch_config(const char *branchname)
197 {
198 struct strbuf buf = STRBUF_INIT;
199 strbuf_addf(&buf, "branch.%s", branchname);
200 if (git_config_rename_section(buf.buf, NULL) < 0)
201 warning(_("Update of config-file failed"));
202 strbuf_release(&buf);
203 }
204
205 static int delete_branches(int argc, const char **argv, int force, int kinds,
206 int quiet)
207 {
208 struct commit *head_rev = NULL;
209 struct object_id oid;
210 char *name = NULL;
211 const char *fmt;
212 int i;
213 int ret = 0;
214 int remote_branch = 0;
215 struct strbuf bname = STRBUF_INIT;
216 unsigned allowed_interpret;
217 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
218 struct string_list_item *item;
219 int branch_name_pos;
220
221 switch (kinds) {
222 case FILTER_REFS_REMOTES:
223 fmt = "refs/remotes/%s";
224 /* For subsequent UI messages */
225 remote_branch = 1;
226 allowed_interpret = INTERPRET_BRANCH_REMOTE;
227
228 force = 1;
229 break;
230 case FILTER_REFS_BRANCHES:
231 fmt = "refs/heads/%s";
232 allowed_interpret = INTERPRET_BRANCH_LOCAL;
233 break;
234 default:
235 die(_("cannot use -a with -d"));
236 }
237 branch_name_pos = strcspn(fmt, "%");
238
239 if (!force)
240 head_rev = lookup_commit_reference(the_repository, &head_oid);
241
242 for (i = 0; i < argc; i++, strbuf_reset(&bname)) {
243 char *target = NULL;
244 int flags = 0;
245
246 strbuf_branchname(&bname, argv[i], allowed_interpret);
247 free(name);
248 name = mkpathdup(fmt, bname.buf);
249
250 if (kinds == FILTER_REFS_BRANCHES) {
251 const char *path;
252 if ((path = branch_checked_out(name))) {
253 error(_("Cannot delete branch '%s' "
254 "checked out at '%s'"),
255 bname.buf, path);
256 ret = 1;
257 continue;
258 }
259 }
260
261 target = resolve_refdup(name,
262 RESOLVE_REF_READING
263 | RESOLVE_REF_NO_RECURSE
264 | RESOLVE_REF_ALLOW_BAD_NAME,
265 &oid, &flags);
266 if (!target) {
267 error(remote_branch
268 ? _("remote-tracking branch '%s' not found.")
269 : _("branch '%s' not found."), bname.buf);
270 ret = 1;
271 continue;
272 }
273
274 if (!(flags & (REF_ISSYMREF|REF_ISBROKEN)) &&
275 check_branch_commit(bname.buf, name, &oid, head_rev, kinds,
276 force)) {
277 ret = 1;
278 goto next;
279 }
280
281 item = string_list_append(&refs_to_delete, name);
282 item->util = xstrdup((flags & REF_ISBROKEN) ? "broken"
283 : (flags & REF_ISSYMREF) ? target
284 : find_unique_abbrev(&oid, DEFAULT_ABBREV));
285
286 next:
287 free(target);
288 }
289
290 if (delete_refs(NULL, &refs_to_delete, REF_NO_DEREF))
291 ret = 1;
292
293 for_each_string_list_item(item, &refs_to_delete) {
294 char *describe_ref = item->util;
295 char *name = item->string;
296 if (!ref_exists(name)) {
297 char *refname = name + branch_name_pos;
298 if (!quiet)
299 printf(remote_branch
300 ? _("Deleted remote-tracking branch %s (was %s).\n")
301 : _("Deleted branch %s (was %s).\n"),
302 name + branch_name_pos, describe_ref);
303
304 delete_branch_config(refname);
305 }
306 free(describe_ref);
307 }
308 string_list_clear(&refs_to_delete, 0);
309
310 free(name);
311 strbuf_release(&bname);
312
313 return ret;
314 }
315
316 static int calc_maxwidth(struct ref_array *refs, int remote_bonus)
317 {
318 int i, max = 0;
319 for (i = 0; i < refs->nr; i++) {
320 struct ref_array_item *it = refs->items[i];
321 const char *desc = it->refname;
322 int w;
323
324 skip_prefix(it->refname, "refs/heads/", &desc);
325 skip_prefix(it->refname, "refs/remotes/", &desc);
326 if (it->kind == FILTER_REFS_DETACHED_HEAD) {
327 char *head_desc = get_head_description();
328 w = utf8_strwidth(head_desc);
329 free(head_desc);
330 } else
331 w = utf8_strwidth(desc);
332
333 if (it->kind == FILTER_REFS_REMOTES)
334 w += remote_bonus;
335 if (w > max)
336 max = w;
337 }
338 return max;
339 }
340
341 static const char *quote_literal_for_format(const char *s)
342 {
343 static struct strbuf buf = STRBUF_INIT;
344
345 strbuf_reset(&buf);
346 while (*s) {
347 const char *ep = strchrnul(s, '%');
348 if (s < ep)
349 strbuf_add(&buf, s, ep - s);
350 if (*ep == '%') {
351 strbuf_addstr(&buf, "%%");
352 s = ep + 1;
353 } else {
354 s = ep;
355 }
356 }
357 return buf.buf;
358 }
359
360 static char *build_format(struct ref_filter *filter, int maxwidth, const char *remote_prefix)
361 {
362 struct strbuf fmt = STRBUF_INIT;
363 struct strbuf local = STRBUF_INIT;
364 struct strbuf remote = STRBUF_INIT;
365
366 strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)%%(if)%%(worktreepath)%%(then)+ %s%%(else) %s%%(end)%%(end)",
367 branch_get_color(BRANCH_COLOR_CURRENT),
368 branch_get_color(BRANCH_COLOR_WORKTREE),
369 branch_get_color(BRANCH_COLOR_LOCAL));
370 strbuf_addf(&remote, " %s",
371 branch_get_color(BRANCH_COLOR_REMOTE));
372
373 if (filter->verbose) {
374 struct strbuf obname = STRBUF_INIT;
375
376 if (filter->abbrev < 0)
377 strbuf_addf(&obname, "%%(objectname:short)");
378 else if (!filter->abbrev)
379 strbuf_addf(&obname, "%%(objectname)");
380 else
381 strbuf_addf(&obname, "%%(objectname:short=%d)", filter->abbrev);
382
383 strbuf_addf(&local, "%%(align:%d,left)%%(refname:lstrip=2)%%(end)", maxwidth);
384 strbuf_addstr(&local, branch_get_color(BRANCH_COLOR_RESET));
385 strbuf_addf(&local, " %s ", obname.buf);
386
387 if (filter->verbose > 1)
388 {
389 strbuf_addf(&local, "%%(if:notequals=*)%%(HEAD)%%(then)%%(if)%%(worktreepath)%%(then)(%s%%(worktreepath)%s) %%(end)%%(end)",
390 branch_get_color(BRANCH_COLOR_WORKTREE), branch_get_color(BRANCH_COLOR_RESET));
391 strbuf_addf(&local, "%%(if)%%(upstream)%%(then)[%s%%(upstream:short)%s%%(if)%%(upstream:track)"
392 "%%(then): %%(upstream:track,nobracket)%%(end)] %%(end)%%(contents:subject)",
393 branch_get_color(BRANCH_COLOR_UPSTREAM), branch_get_color(BRANCH_COLOR_RESET));
394 }
395 else
396 strbuf_addf(&local, "%%(if)%%(upstream:track)%%(then)%%(upstream:track) %%(end)%%(contents:subject)");
397
398 strbuf_addf(&remote, "%%(align:%d,left)%s%%(refname:lstrip=2)%%(end)%s"
399 "%%(if)%%(symref)%%(then) -> %%(symref:short)"
400 "%%(else) %s %%(contents:subject)%%(end)",
401 maxwidth, quote_literal_for_format(remote_prefix),
402 branch_get_color(BRANCH_COLOR_RESET), obname.buf);
403 strbuf_release(&obname);
404 } else {
405 strbuf_addf(&local, "%%(refname:lstrip=2)%s%%(if)%%(symref)%%(then) -> %%(symref:short)%%(end)",
406 branch_get_color(BRANCH_COLOR_RESET));
407 strbuf_addf(&remote, "%s%%(refname:lstrip=2)%s%%(if)%%(symref)%%(then) -> %%(symref:short)%%(end)",
408 quote_literal_for_format(remote_prefix),
409 branch_get_color(BRANCH_COLOR_RESET));
410 }
411
412 strbuf_addf(&fmt, "%%(if:notequals=refs/remotes)%%(refname:rstrip=-2)%%(then)%s%%(else)%s%%(end)", local.buf, remote.buf);
413
414 strbuf_release(&local);
415 strbuf_release(&remote);
416 return strbuf_detach(&fmt, NULL);
417 }
418
419 static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sorting,
420 struct ref_format *format, struct string_list *output)
421 {
422 int i;
423 struct ref_array array;
424 struct strbuf out = STRBUF_INIT;
425 struct strbuf err = STRBUF_INIT;
426 int maxwidth = 0;
427 const char *remote_prefix = "";
428 char *to_free = NULL;
429
430 /*
431 * If we are listing more than just remote branches,
432 * then remote branches will have a "remotes/" prefix.
433 * We need to account for this in the width.
434 */
435 if (filter->kind != FILTER_REFS_REMOTES)
436 remote_prefix = "remotes/";
437
438 memset(&array, 0, sizeof(array));
439
440 filter_refs(&array, filter, filter->kind);
441
442 if (filter->verbose)
443 maxwidth = calc_maxwidth(&array, strlen(remote_prefix));
444
445 if (!format->format)
446 format->format = to_free = build_format(filter, maxwidth, remote_prefix);
447 format->use_color = branch_use_color;
448
449 if (verify_ref_format(format))
450 die(_("unable to parse format string"));
451
452 ref_array_sort(sorting, &array);
453
454 for (i = 0; i < array.nr; i++) {
455 strbuf_reset(&err);
456 strbuf_reset(&out);
457 if (format_ref_array_item(array.items[i], format, &out, &err))
458 die("%s", err.buf);
459 if (column_active(colopts)) {
460 assert(!filter->verbose && "--column and --verbose are incompatible");
461 /* format to a string_list to let print_columns() do its job */
462 string_list_append(output, out.buf);
463 } else {
464 fwrite(out.buf, 1, out.len, stdout);
465 putchar('\n');
466 }
467 }
468
469 strbuf_release(&err);
470 strbuf_release(&out);
471 ref_array_clear(&array);
472 free(to_free);
473 }
474
475 static void print_current_branch_name(void)
476 {
477 int flags;
478 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
479 const char *shortname;
480 if (!refname)
481 die(_("could not resolve HEAD"));
482 else if (!(flags & REF_ISSYMREF))
483 return;
484 else if (skip_prefix(refname, "refs/heads/", &shortname))
485 puts(shortname);
486 else
487 die(_("HEAD (%s) points outside of refs/heads/"), refname);
488 }
489
490 static void reject_rebase_or_bisect_branch(const char *target)
491 {
492 struct worktree **worktrees = get_worktrees();
493 int i;
494
495 for (i = 0; worktrees[i]; i++) {
496 struct worktree *wt = worktrees[i];
497
498 if (!wt->is_detached)
499 continue;
500
501 if (is_worktree_being_rebased(wt, target))
502 die(_("Branch %s is being rebased at %s"),
503 target, wt->path);
504
505 if (is_worktree_being_bisected(wt, target))
506 die(_("Branch %s is being bisected at %s"),
507 target, wt->path);
508 }
509
510 free_worktrees(worktrees);
511 }
512
513 static void copy_or_rename_branch(const char *oldname, const char *newname, int copy, int force)
514 {
515 struct strbuf oldref = STRBUF_INIT, newref = STRBUF_INIT, logmsg = STRBUF_INIT;
516 struct strbuf oldsection = STRBUF_INIT, newsection = STRBUF_INIT;
517 const char *interpreted_oldname = NULL;
518 const char *interpreted_newname = NULL;
519 int recovery = 0;
520
521 if (strbuf_check_branch_ref(&oldref, oldname)) {
522 /*
523 * Bad name --- this could be an attempt to rename a
524 * ref that we used to allow to be created by accident.
525 */
526 if (ref_exists(oldref.buf))
527 recovery = 1;
528 else
529 die(_("Invalid branch name: '%s'"), oldname);
530 }
531
532 if ((copy || strcmp(head, oldname)) && !ref_exists(oldref.buf)) {
533 if (copy && !strcmp(head, oldname))
534 die(_("No commit on branch '%s' yet."), oldname);
535 else
536 die(_("No branch named '%s'."), oldname);
537 }
538
539 /*
540 * A command like "git branch -M currentbranch currentbranch" cannot
541 * cause the worktree to become inconsistent with HEAD, so allow it.
542 */
543 if (!strcmp(oldname, newname))
544 validate_branchname(newname, &newref);
545 else
546 validate_new_branchname(newname, &newref, force);
547
548 reject_rebase_or_bisect_branch(oldref.buf);
549
550 if (!skip_prefix(oldref.buf, "refs/heads/", &interpreted_oldname) ||
551 !skip_prefix(newref.buf, "refs/heads/", &interpreted_newname)) {
552 BUG("expected prefix missing for refs");
553 }
554
555 if (copy)
556 strbuf_addf(&logmsg, "Branch: copied %s to %s",
557 oldref.buf, newref.buf);
558 else
559 strbuf_addf(&logmsg, "Branch: renamed %s to %s",
560 oldref.buf, newref.buf);
561
562 if (!copy &&
563 (!head || strcmp(oldname, head) || !is_null_oid(&head_oid)) &&
564 rename_ref(oldref.buf, newref.buf, logmsg.buf))
565 die(_("Branch rename failed"));
566 if (copy && copy_existing_ref(oldref.buf, newref.buf, logmsg.buf))
567 die(_("Branch copy failed"));
568
569 if (recovery) {
570 if (copy)
571 warning(_("Created a copy of a misnamed branch '%s'"),
572 interpreted_oldname);
573 else
574 warning(_("Renamed a misnamed branch '%s' away"),
575 interpreted_oldname);
576 }
577
578 if (!copy &&
579 replace_each_worktree_head_symref(oldref.buf, newref.buf, logmsg.buf))
580 die(_("Branch renamed to %s, but HEAD is not updated!"), newname);
581
582 strbuf_release(&logmsg);
583
584 strbuf_addf(&oldsection, "branch.%s", interpreted_oldname);
585 strbuf_addf(&newsection, "branch.%s", interpreted_newname);
586 if (!copy && git_config_rename_section(oldsection.buf, newsection.buf) < 0)
587 die(_("Branch is renamed, but update of config-file failed"));
588 if (copy && strcmp(interpreted_oldname, interpreted_newname) && git_config_copy_section(oldsection.buf, newsection.buf) < 0)
589 die(_("Branch is copied, but update of config-file failed"));
590 strbuf_release(&oldref);
591 strbuf_release(&newref);
592 strbuf_release(&oldsection);
593 strbuf_release(&newsection);
594 }
595
596 static GIT_PATH_FUNC(edit_description, "EDIT_DESCRIPTION")
597
598 static int edit_branch_description(const char *branch_name)
599 {
600 int exists;
601 struct strbuf buf = STRBUF_INIT;
602 struct strbuf name = STRBUF_INIT;
603
604 exists = !read_branch_desc(&buf, branch_name);
605 if (!buf.len || buf.buf[buf.len-1] != '\n')
606 strbuf_addch(&buf, '\n');
607 strbuf_commented_addf(&buf,
608 _("Please edit the description for the branch\n"
609 " %s\n"
610 "Lines starting with '%c' will be stripped.\n"),
611 branch_name, comment_line_char);
612 write_file_buf(edit_description(), buf.buf, buf.len);
613 strbuf_reset(&buf);
614 if (launch_editor(edit_description(), &buf, NULL)) {
615 strbuf_release(&buf);
616 return -1;
617 }
618 strbuf_stripspace(&buf, 1);
619
620 strbuf_addf(&name, "branch.%s.description", branch_name);
621 if (buf.len || exists)
622 git_config_set(name.buf, buf.len ? buf.buf : NULL);
623 strbuf_release(&name);
624 strbuf_release(&buf);
625
626 return 0;
627 }
628
629 int cmd_branch(int argc, const char **argv, const char *prefix)
630 {
631 /* possible actions */
632 int delete = 0, rename = 0, copy = 0, list = 0,
633 unset_upstream = 0, show_current = 0, edit_description = 0;
634 const char *new_upstream = NULL;
635 int noncreate_actions = 0;
636 /* possible options */
637 int reflog = 0, quiet = 0, icase = 0, force = 0,
638 recurse_submodules_explicit = 0;
639 enum branch_track track;
640 struct ref_filter filter;
641 static struct ref_sorting *sorting;
642 struct string_list sorting_options = STRING_LIST_INIT_DUP;
643 struct ref_format format = REF_FORMAT_INIT;
644
645 struct option options[] = {
646 OPT_GROUP(N_("Generic options")),
647 OPT__VERBOSE(&filter.verbose,
648 N_("show hash and subject, give twice for upstream branch")),
649 OPT__QUIET(&quiet, N_("suppress informational messages")),
650 OPT_CALLBACK_F('t', "track", &track, "(direct|inherit)",
651 N_("set branch tracking configuration"),
652 PARSE_OPT_OPTARG,
653 parse_opt_tracking_mode),
654 OPT_SET_INT_F(0, "set-upstream", &track, N_("do not use"),
655 BRANCH_TRACK_OVERRIDE, PARSE_OPT_HIDDEN),
656 OPT_STRING('u', "set-upstream-to", &new_upstream, N_("upstream"), N_("change the upstream info")),
657 OPT_BOOL(0, "unset-upstream", &unset_upstream, N_("unset the upstream info")),
658 OPT__COLOR(&branch_use_color, N_("use colored output")),
659 OPT_SET_INT('r', "remotes", &filter.kind, N_("act on remote-tracking branches"),
660 FILTER_REFS_REMOTES),
661 OPT_CONTAINS(&filter.with_commit, N_("print only branches that contain the commit")),
662 OPT_NO_CONTAINS(&filter.no_commit, N_("print only branches that don't contain the commit")),
663 OPT_WITH(&filter.with_commit, N_("print only branches that contain the commit")),
664 OPT_WITHOUT(&filter.no_commit, N_("print only branches that don't contain the commit")),
665 OPT__ABBREV(&filter.abbrev),
666
667 OPT_GROUP(N_("Specific git-branch actions:")),
668 OPT_SET_INT('a', "all", &filter.kind, N_("list both remote-tracking and local branches"),
669 FILTER_REFS_REMOTES | FILTER_REFS_BRANCHES),
670 OPT_BIT('d', "delete", &delete, N_("delete fully merged branch"), 1),
671 OPT_BIT('D', NULL, &delete, N_("delete branch (even if not merged)"), 2),
672 OPT_BIT('m', "move", &rename, N_("move/rename a branch and its reflog"), 1),
673 OPT_BIT('M', NULL, &rename, N_("move/rename a branch, even if target exists"), 2),
674 OPT_BIT('c', "copy", &copy, N_("copy a branch and its reflog"), 1),
675 OPT_BIT('C', NULL, &copy, N_("copy a branch, even if target exists"), 2),
676 OPT_BOOL('l', "list", &list, N_("list branch names")),
677 OPT_BOOL(0, "show-current", &show_current, N_("show current branch name")),
678 OPT_BOOL(0, "create-reflog", &reflog, N_("create the branch's reflog")),
679 OPT_BOOL(0, "edit-description", &edit_description,
680 N_("edit the description for the branch")),
681 OPT__FORCE(&force, N_("force creation, move/rename, deletion"), PARSE_OPT_NOCOMPLETE),
682 OPT_MERGED(&filter, N_("print only branches that are merged")),
683 OPT_NO_MERGED(&filter, N_("print only branches that are not merged")),
684 OPT_COLUMN(0, "column", &colopts, N_("list branches in columns")),
685 OPT_REF_SORT(&sorting_options),
686 OPT_CALLBACK(0, "points-at", &filter.points_at, N_("object"),
687 N_("print only branches of the object"), parse_opt_object_name),
688 OPT_BOOL('i', "ignore-case", &icase, N_("sorting and filtering are case insensitive")),
689 OPT_BOOL(0, "recurse-submodules", &recurse_submodules_explicit, N_("recurse through submodules")),
690 OPT_STRING( 0 , "format", &format.format, N_("format"), N_("format to use for the output")),
691 OPT_END(),
692 };
693
694 setup_ref_filter_porcelain_msg();
695
696 memset(&filter, 0, sizeof(filter));
697 filter.kind = FILTER_REFS_BRANCHES;
698 filter.abbrev = -1;
699
700 if (argc == 2 && !strcmp(argv[1], "-h"))
701 usage_with_options(builtin_branch_usage, options);
702
703 git_config(git_branch_config, &sorting_options);
704
705 track = git_branch_track;
706
707 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
708 if (!head)
709 die(_("Failed to resolve HEAD as a valid ref."));
710 if (!strcmp(head, "HEAD"))
711 filter.detached = 1;
712 else if (!skip_prefix(head, "refs/heads/", &head))
713 die(_("HEAD not found below refs/heads!"));
714
715 argc = parse_options(argc, argv, prefix, options, builtin_branch_usage,
716 0);
717
718 if (!delete && !rename && !copy && !edit_description && !new_upstream &&
719 !show_current && !unset_upstream && argc == 0)
720 list = 1;
721
722 if (filter.with_commit || filter.no_commit ||
723 filter.reachable_from || filter.unreachable_from || filter.points_at.nr)
724 list = 1;
725
726 noncreate_actions = !!delete + !!rename + !!copy + !!new_upstream +
727 !!show_current + !!list + !!edit_description +
728 !!unset_upstream;
729 if (noncreate_actions > 1)
730 usage_with_options(builtin_branch_usage, options);
731
732 if (recurse_submodules_explicit) {
733 if (!submodule_propagate_branches)
734 die(_("branch with --recurse-submodules can only be used if submodule.propagateBranches is enabled"));
735 if (noncreate_actions)
736 die(_("--recurse-submodules can only be used to create branches"));
737 }
738
739 recurse_submodules =
740 (recurse_submodules || recurse_submodules_explicit) &&
741 submodule_propagate_branches;
742
743 if (filter.abbrev == -1)
744 filter.abbrev = DEFAULT_ABBREV;
745 filter.ignore_case = icase;
746
747 finalize_colopts(&colopts, -1);
748 if (filter.verbose) {
749 if (explicitly_enable_column(colopts))
750 die(_("options '%s' and '%s' cannot be used together"), "--column", "--verbose");
751 colopts = 0;
752 }
753
754 if (force) {
755 delete *= 2;
756 rename *= 2;
757 copy *= 2;
758 }
759
760 if (list)
761 setup_auto_pager("branch", 1);
762
763 if (delete) {
764 if (!argc)
765 die(_("branch name required"));
766 return delete_branches(argc, argv, delete > 1, filter.kind, quiet);
767 } else if (show_current) {
768 print_current_branch_name();
769 return 0;
770 } else if (list) {
771 /* git branch --list also shows HEAD when it is detached */
772 if ((filter.kind & FILTER_REFS_BRANCHES) && filter.detached)
773 filter.kind |= FILTER_REFS_DETACHED_HEAD;
774 filter.name_patterns = argv;
775 /*
776 * If no sorting parameter is given then we default to sorting
777 * by 'refname'. This would give us an alphabetically sorted
778 * array with the 'HEAD' ref at the beginning followed by
779 * local branches 'refs/heads/...' and finally remote-tracking
780 * branches 'refs/remotes/...'.
781 */
782 sorting = ref_sorting_options(&sorting_options);
783 ref_sorting_set_sort_flags_all(sorting, REF_SORTING_ICASE, icase);
784 ref_sorting_set_sort_flags_all(
785 sorting, REF_SORTING_DETACHED_HEAD_FIRST, 1);
786 print_ref_list(&filter, sorting, &format, &output);
787 print_columns(&output, colopts, NULL);
788 string_list_clear(&output, 0);
789 ref_sorting_release(sorting);
790 return 0;
791 } else if (edit_description) {
792 const char *branch_name;
793 struct strbuf branch_ref = STRBUF_INIT;
794 struct strbuf buf = STRBUF_INIT;
795 int ret = 1; /* assume failure */
796
797 if (!argc) {
798 if (filter.detached)
799 die(_("Cannot give description to detached HEAD"));
800 branch_name = head;
801 } else if (argc == 1) {
802 strbuf_branchname(&buf, argv[0], INTERPRET_BRANCH_LOCAL);
803 branch_name = buf.buf;
804 } else {
805 die(_("cannot edit description of more than one branch"));
806 }
807
808 strbuf_addf(&branch_ref, "refs/heads/%s", branch_name);
809 if (!ref_exists(branch_ref.buf))
810 error((!argc || !strcmp(head, branch_name))
811 ? _("No commit on branch '%s' yet.")
812 : _("No branch named '%s'."),
813 branch_name);
814 else if (!edit_branch_description(branch_name))
815 ret = 0; /* happy */
816
817 strbuf_release(&branch_ref);
818 strbuf_release(&buf);
819
820 return ret;
821 } else if (copy || rename) {
822 if (!argc)
823 die(_("branch name required"));
824 else if ((argc == 1) && filter.detached)
825 die(copy? _("cannot copy the current branch while not on any.")
826 : _("cannot rename the current branch while not on any."));
827 else if (argc == 1)
828 copy_or_rename_branch(head, argv[0], copy, copy + rename > 1);
829 else if (argc == 2)
830 copy_or_rename_branch(argv[0], argv[1], copy, copy + rename > 1);
831 else
832 die(copy? _("too many branches for a copy operation")
833 : _("too many arguments for a rename operation"));
834 } else if (new_upstream) {
835 struct branch *branch;
836 struct strbuf buf = STRBUF_INIT;
837
838 if (!argc)
839 branch = branch_get(NULL);
840 else if (argc == 1) {
841 strbuf_branchname(&buf, argv[0], INTERPRET_BRANCH_LOCAL);
842 branch = branch_get(buf.buf);
843 } else
844 die(_("too many arguments to set new upstream"));
845
846 if (!branch) {
847 if (!argc || !strcmp(argv[0], "HEAD"))
848 die(_("could not set upstream of HEAD to %s when "
849 "it does not point to any branch."),
850 new_upstream);
851 die(_("no such branch '%s'"), argv[0]);
852 }
853
854 if (!ref_exists(branch->refname)) {
855 if (!argc || !strcmp(head, branch->name))
856 die(_("No commit on branch '%s' yet."), branch->name);
857 die(_("branch '%s' does not exist"), branch->name);
858 }
859
860 dwim_and_setup_tracking(the_repository, branch->name,
861 new_upstream, BRANCH_TRACK_OVERRIDE,
862 quiet);
863 strbuf_release(&buf);
864 } else if (unset_upstream) {
865 struct branch *branch;
866 struct strbuf buf = STRBUF_INIT;
867
868 if (!argc)
869 branch = branch_get(NULL);
870 else if (argc == 1) {
871 strbuf_branchname(&buf, argv[0], INTERPRET_BRANCH_LOCAL);
872 branch = branch_get(buf.buf);
873 } else
874 die(_("too many arguments to unset upstream"));
875
876 if (!branch) {
877 if (!argc || !strcmp(argv[0], "HEAD"))
878 die(_("could not unset upstream of HEAD when "
879 "it does not point to any branch."));
880 die(_("no such branch '%s'"), argv[0]);
881 }
882
883 if (!branch_has_merge_config(branch))
884 die(_("Branch '%s' has no upstream information"), branch->name);
885
886 strbuf_reset(&buf);
887 strbuf_addf(&buf, "branch.%s.remote", branch->name);
888 git_config_set_multivar(buf.buf, NULL, NULL, CONFIG_FLAGS_MULTI_REPLACE);
889 strbuf_reset(&buf);
890 strbuf_addf(&buf, "branch.%s.merge", branch->name);
891 git_config_set_multivar(buf.buf, NULL, NULL, CONFIG_FLAGS_MULTI_REPLACE);
892 strbuf_release(&buf);
893 } else if (!noncreate_actions && argc > 0 && argc <= 2) {
894 const char *branch_name = argv[0];
895 const char *start_name = argc == 2 ? argv[1] : head;
896
897 if (filter.kind != FILTER_REFS_BRANCHES)
898 die(_("The -a, and -r, options to 'git branch' do not take a branch name.\n"
899 "Did you mean to use: -a|-r --list <pattern>?"));
900
901 if (track == BRANCH_TRACK_OVERRIDE)
902 die(_("the '--set-upstream' option is no longer supported. Please use '--track' or '--set-upstream-to' instead."));
903
904 if (recurse_submodules) {
905 create_branches_recursively(the_repository, branch_name,
906 start_name, NULL, force,
907 reflog, quiet, track, 0);
908 return 0;
909 }
910 create_branch(the_repository, branch_name, start_name, force, 0,
911 reflog, quiet, track, 0);
912 } else
913 usage_with_options(builtin_branch_usage, options);
914
915 return 0;
916 }