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