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