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