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