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