Raw
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 #define USE_THE_REPOSITORY_VARIABLE
9
10 #include "builtin.h"
11 #include "config.h"
12 #include "color.h"
13 #include "editor.h"
14 #include "environment.h"
15 #include "refs.h"
16 #include "commit.h"
17 #include "gettext.h"
18 #include "object-name.h"
19 #include "remote.h"
20 #include "parse-options.h"
21 #include "branch.h"
22 #include "path.h"
23 #include "string-list.h"
24 #include "strmap.h"
25 #include "column.h"
26 #include "utf8.h"
27 #include "ref-filter.h"
28 #include "worktree.h"
29 #include "help.h"
30 #include "advice.h"
31 #include "commit-reach.h"
32
33 static const char * const builtin_branch_usage[] = {
34 N_("git branch [<options>] [-r | -a] [--merged] [--no-merged] [(--forked <branch>)...]"),
35 N_("git branch [<options>] [-f] [--recurse-submodules] <branch-name> [<start-point>]"),
36 N_("git branch [<options>] [-l] [<pattern>...]"),
37 N_("git branch [<options>] [-r] (-d | -D) <branch-name>..."),
38 N_("git branch [<options>] (-m | -M) [<old-branch>] <new-branch>"),
39 N_("git branch [<options>] (-c | -C) [<old-branch>] <new-branch>"),
40 N_("git branch [<options>] [-r | -a] [--points-at]"),
41 N_("git branch [<options>] [-r | -a] [--format]"),
42 N_("git branch [<options>] (--delete-merged <branch>)... [<pattern>...]"),
43 NULL
44 };
45
46 static const char *head;
47 static struct object_id head_oid;
48 static int recurse_submodules = 0;
49 static int submodule_propagate_branches = 0;
50
51 static enum git_colorbool branch_use_color = GIT_COLOR_UNKNOWN;
52 static char branch_colors[][COLOR_MAXLEN] = {
53 GIT_COLOR_RESET,
54 GIT_COLOR_NORMAL, /* PLAIN */
55 GIT_COLOR_RED, /* REMOTE */
56 GIT_COLOR_NORMAL, /* LOCAL */
57 GIT_COLOR_GREEN, /* CURRENT */
58 GIT_COLOR_BLUE, /* UPSTREAM */
59 GIT_COLOR_CYAN, /* WORKTREE */
60 };
61 enum color_branch {
62 BRANCH_COLOR_RESET = 0,
63 BRANCH_COLOR_PLAIN = 1,
64 BRANCH_COLOR_REMOTE = 2,
65 BRANCH_COLOR_LOCAL = 3,
66 BRANCH_COLOR_CURRENT = 4,
67 BRANCH_COLOR_UPSTREAM = 5,
68 BRANCH_COLOR_WORKTREE = 6
69 };
70
71 static const char *color_branch_slots[] = {
72 [BRANCH_COLOR_RESET] = "reset",
73 [BRANCH_COLOR_PLAIN] = "plain",
74 [BRANCH_COLOR_REMOTE] = "remote",
75 [BRANCH_COLOR_LOCAL] = "local",
76 [BRANCH_COLOR_CURRENT] = "current",
77 [BRANCH_COLOR_UPSTREAM] = "upstream",
78 [BRANCH_COLOR_WORKTREE] = "worktree",
79 };
80
81 static struct string_list output = STRING_LIST_INIT_DUP;
82 static unsigned int colopts;
83
84 define_list_config_array(color_branch_slots);
85
86 static int git_branch_config(const char *var, const char *value,
87 const struct config_context *ctx, void *cb)
88 {
89 const char *slot_name;
90
91 if (!strcmp(var, "branch.sort")) {
92 if (!value)
93 return config_error_nonbool(var);
94 string_list_append(cb, value);
95 return 0;
96 }
97
98 if (starts_with(var, "column."))
99 return git_column_config(var, value, "branch", &colopts);
100 if (!strcmp(var, "color.branch")) {
101 branch_use_color = git_config_colorbool(var, value);
102 return 0;
103 }
104 if (skip_prefix(var, "color.branch.", &slot_name)) {
105 int slot = LOOKUP_CONFIG(color_branch_slots, slot_name);
106 if (slot < 0)
107 return 0;
108 if (!value)
109 return config_error_nonbool(var);
110 return color_parse(value, branch_colors[slot]);
111 }
112 if (!strcmp(var, "submodule.recurse")) {
113 recurse_submodules = git_config_bool(var, value);
114 return 0;
115 }
116 if (!strcasecmp(var, "submodule.propagateBranches")) {
117 submodule_propagate_branches = git_config_bool(var, value);
118 return 0;
119 }
120
121 if (git_color_config(var, value, cb) < 0)
122 return -1;
123
124 return git_default_config(var, value, ctx, cb);
125 }
126
127 static const char *branch_get_color(enum color_branch ix)
128 {
129 if (want_color(branch_use_color))
130 return branch_colors[ix];
131 return "";
132 }
133
134 static int branch_merged(int kind, const char *name,
135 struct commit *rev, struct commit *head_rev)
136 {
137 /*
138 * This checks whether the merge bases of branch and HEAD (or
139 * the other branch this branch builds upon) contains the
140 * branch, which means that the branch has already been merged
141 * safely to HEAD (or the other branch).
142 */
143 struct commit *reference_rev = NULL;
144 const char *reference_name = NULL;
145 void *reference_name_to_free = NULL;
146 int merged;
147
148 if (kind == FILTER_REFS_BRANCHES) {
149 struct branch *branch = branch_get(name);
150 const char *upstream = branch_get_upstream(branch, NULL);
151 struct object_id oid;
152
153 if (upstream &&
154 (reference_name = reference_name_to_free =
155 refs_resolve_refdup(get_main_ref_store(the_repository), upstream, RESOLVE_REF_READING,
156 &oid, NULL)) != NULL)
157 reference_rev = lookup_commit_reference(the_repository,
158 &oid);
159 }
160 if (!reference_rev)
161 reference_rev = head_rev;
162
163 merged = reference_rev ? repo_in_merge_bases(the_repository, rev,
164 reference_rev) : 0;
165 if (merged < 0)
166 exit(128);
167
168 /*
169 * After the safety valve is fully redefined to "check with
170 * upstream, if any, otherwise with HEAD", we should just
171 * return the result of the repo_in_merge_bases() above without
172 * any of the following code, but during the transition period,
173 * a gentle reminder is in order. Callers that opt out of the
174 * HEAD fallback by passing head_rev=NULL are not interested in
175 * the reminder either: they have already established that the
176 * branch has an upstream, so HEAD is irrelevant to the decision.
177 */
178 if (head_rev && head_rev != reference_rev) {
179 int expect = repo_in_merge_bases(the_repository, rev, head_rev);
180 if (expect < 0)
181 exit(128);
182 if (expect == merged)
183 ; /* okay */
184 else if (merged)
185 warning(_("deleting branch '%s' that has been merged to\n"
186 " '%s', but not yet merged to HEAD"),
187 name, reference_name);
188 else
189 warning(_("not deleting branch '%s' that is not yet merged to\n"
190 " '%s', even though it is merged to HEAD"),
191 name, reference_name);
192 }
193 free(reference_name_to_free);
194 return merged;
195 }
196
197 enum delete_branch_flags {
198 DELETE_BRANCH_FORCE = (1 << 0),
199 DELETE_BRANCH_QUIET = (1 << 1),
200 DELETE_BRANCH_SKIP_UNMERGED = (1 << 2),
201 DELETE_BRANCH_NO_HEAD_FALLBACK = (1 << 3),
202 DELETE_BRANCH_DRY_RUN = (1 << 4),
203 };
204
205 static int check_branch_commit(const char *branchname, const char *refname,
206 const struct object_id *oid, struct commit *head_rev,
207 int kinds, unsigned int flags)
208 {
209 struct commit *rev = lookup_commit_reference(the_repository, oid);
210 if (!(flags & DELETE_BRANCH_FORCE) && !rev) {
211 error(_("couldn't look up commit object for '%s'"), refname);
212 return -1;
213 }
214 if (!(flags & DELETE_BRANCH_FORCE) &&
215 !branch_merged(kinds, branchname, rev, head_rev)) {
216 if (!(flags & DELETE_BRANCH_SKIP_UNMERGED)) {
217 error(_("the branch '%s' is not fully merged"),
218 branchname);
219 advise_if_enabled(ADVICE_FORCE_DELETE_BRANCH,
220 _("If you are sure you want to delete it, "
221 "run 'git branch -D %s'"), branchname);
222 }
223 return -1;
224 }
225 return 0;
226 }
227
228 static void delete_branch_config(const char *branchname)
229 {
230 struct strbuf buf = STRBUF_INIT;
231 strbuf_addf(&buf, "branch.%s", branchname);
232 if (repo_config_rename_section(the_repository, buf.buf, NULL) < 0)
233 warning(_("update of config-file failed"));
234 strbuf_release(&buf);
235 }
236
237 static int delete_branches(int argc, const char **argv, int kinds,
238 unsigned int flags)
239 {
240 struct commit *head_rev = NULL;
241 struct object_id oid;
242 char *name = NULL;
243 const char *fmt;
244 int i;
245 int ret = 0;
246 int remote_branch = 0;
247 struct strbuf bname = STRBUF_INIT;
248 enum interpret_branch_kind allowed_interpret;
249 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
250 struct string_list_item *item;
251 int branch_name_pos;
252 const char *fmt_remotes = "refs/remotes/%s";
253
254 switch (kinds) {
255 case FILTER_REFS_REMOTES:
256 fmt = fmt_remotes;
257 /* For subsequent UI messages */
258 remote_branch = 1;
259 allowed_interpret = INTERPRET_BRANCH_REMOTE;
260
261 flags |= DELETE_BRANCH_FORCE;
262 break;
263 case FILTER_REFS_BRANCHES:
264 fmt = "refs/heads/%s";
265 allowed_interpret = INTERPRET_BRANCH_LOCAL;
266 break;
267 default:
268 die(_("cannot use -a with -d"));
269 }
270 branch_name_pos = strcspn(fmt, "%");
271
272 if (!(flags & DELETE_BRANCH_FORCE) &&
273 !(flags & DELETE_BRANCH_NO_HEAD_FALLBACK))
274 head_rev = lookup_commit_reference(the_repository, &head_oid);
275
276 for (i = 0; i < argc; i++, strbuf_reset(&bname)) {
277 char *target = NULL;
278 int ref_flags = 0;
279
280 copy_branchname(the_repository, &bname,
281 argv[i], allowed_interpret);
282 free(name);
283 name = mkpathdup(fmt, bname.buf);
284
285 if (kinds == FILTER_REFS_BRANCHES) {
286 const char *path;
287 if ((path = branch_checked_out(name))) {
288 error(_("cannot delete branch '%s' "
289 "used by worktree at '%s'"),
290 bname.buf, path);
291 ret = 1;
292 continue;
293 }
294 }
295
296 target = refs_resolve_refdup(get_main_ref_store(the_repository),
297 name,
298 RESOLVE_REF_READING
299 | RESOLVE_REF_NO_RECURSE
300 | RESOLVE_REF_ALLOW_BAD_NAME,
301 &oid, &ref_flags);
302 if (!target) {
303 if (remote_branch) {
304 error(_("remote-tracking branch '%s' not found"), bname.buf);
305 } else {
306 char *virtual_name = mkpathdup(fmt_remotes, bname.buf);
307 char *virtual_target = refs_resolve_refdup(get_main_ref_store(the_repository),
308 virtual_name,
309 RESOLVE_REF_READING
310 | RESOLVE_REF_NO_RECURSE
311 | RESOLVE_REF_ALLOW_BAD_NAME,
312 &oid,
313 &ref_flags);
314 FREE_AND_NULL(virtual_name);
315
316 if (virtual_target)
317 error(_("branch '%s' not found.\n"
318 "Did you forget --remote?"),
319 bname.buf);
320 else
321 error(_("branch '%s' not found"), bname.buf);
322 FREE_AND_NULL(virtual_target);
323 }
324 ret = 1;
325 continue;
326 }
327
328 if (!(ref_flags & (REF_ISSYMREF|REF_ISBROKEN)) &&
329 check_branch_commit(bname.buf, name, &oid, head_rev, kinds,
330 flags)) {
331 if (!(flags & DELETE_BRANCH_SKIP_UNMERGED))
332 ret = 1;
333 goto next;
334 }
335
336 item = string_list_append(&refs_to_delete, name);
337 item->util = xstrdup((ref_flags & REF_ISBROKEN) ? "broken"
338 : (ref_flags & REF_ISSYMREF) ? target
339 : repo_find_unique_abbrev(the_repository, &oid, DEFAULT_ABBREV));
340
341 next:
342 free(target);
343 }
344
345 if (!(flags & DELETE_BRANCH_DRY_RUN) &&
346 refs_delete_refs(get_main_ref_store(the_repository), NULL, &refs_to_delete, REF_NO_DEREF))
347 ret = 1;
348
349 for_each_string_list_item(item, &refs_to_delete) {
350 char *describe_ref = item->util;
351 char *name = item->string;
352 if (flags & DELETE_BRANCH_DRY_RUN) {
353 if (!(flags & DELETE_BRANCH_QUIET))
354 printf(remote_branch
355 ? _("Would delete remote-tracking branch %s (was %s).\n")
356 : _("Would delete branch %s (was %s).\n"),
357 name + branch_name_pos, describe_ref);
358 } else if (!refs_ref_exists(get_main_ref_store(the_repository), name)) {
359 char *refname = name + branch_name_pos;
360 if (!(flags & DELETE_BRANCH_QUIET))
361 printf(remote_branch
362 ? _("Deleted remote-tracking branch %s (was %s).\n")
363 : _("Deleted branch %s (was %s).\n"),
364 name + branch_name_pos, describe_ref);
365
366 delete_branch_config(refname);
367 }
368 free(describe_ref);
369 }
370 string_list_clear(&refs_to_delete, 0);
371
372 free(name);
373 strbuf_release(&bname);
374
375 return ret;
376 }
377
378 static int calc_maxwidth(struct ref_array *refs, int remote_bonus)
379 {
380 int i, max = 0;
381 for (i = 0; i < refs->nr; i++) {
382 struct ref_array_item *it = refs->items[i];
383 const char *desc = it->refname;
384 int w;
385
386 skip_prefix(it->refname, "refs/heads/", &desc);
387 skip_prefix(it->refname, "refs/remotes/", &desc);
388 if (it->kind == FILTER_REFS_DETACHED_HEAD) {
389 char *head_desc = get_head_description();
390 w = utf8_strwidth(head_desc);
391 free(head_desc);
392 } else
393 w = utf8_strwidth(desc);
394
395 if (it->kind == FILTER_REFS_REMOTES)
396 w += remote_bonus;
397 if (w > max)
398 max = w;
399 }
400 return max;
401 }
402
403 static const char *quote_literal_for_format(const char *s)
404 {
405 static struct strbuf buf = STRBUF_INIT;
406
407 strbuf_reset(&buf);
408 while (strbuf_expand_step(&buf, &s))
409 strbuf_addstr(&buf, "%%");
410 return buf.buf;
411 }
412
413 static char *build_format(struct ref_filter *filter, int maxwidth, const char *remote_prefix)
414 {
415 struct strbuf fmt = STRBUF_INIT;
416 struct strbuf local = STRBUF_INIT;
417 struct strbuf remote = STRBUF_INIT;
418
419 strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)%%(if)%%(worktreepath)%%(then)+ %s%%(else) %s%%(end)%%(end)",
420 branch_get_color(BRANCH_COLOR_CURRENT),
421 branch_get_color(BRANCH_COLOR_WORKTREE),
422 branch_get_color(BRANCH_COLOR_LOCAL));
423 strbuf_addf(&remote, " %s",
424 branch_get_color(BRANCH_COLOR_REMOTE));
425
426 if (filter->verbose) {
427 struct strbuf obname = STRBUF_INIT;
428
429 if (filter->abbrev < 0)
430 strbuf_addf(&obname, "%%(objectname:short)");
431 else if (!filter->abbrev)
432 strbuf_addf(&obname, "%%(objectname)");
433 else
434 strbuf_addf(&obname, "%%(objectname:short=%d)", filter->abbrev);
435
436 strbuf_addf(&local, "%%(align:%d,left)%%(refname:lstrip=2)%%(end)", maxwidth);
437 strbuf_addstr(&local, branch_get_color(BRANCH_COLOR_RESET));
438 strbuf_addf(&local, " %s ", obname.buf);
439
440 if (filter->verbose > 1)
441 {
442 strbuf_addf(&local, "%%(if:notequals=*)%%(HEAD)%%(then)%%(if)%%(worktreepath)%%(then)(%s%%(worktreepath)%s) %%(end)%%(end)",
443 branch_get_color(BRANCH_COLOR_WORKTREE), branch_get_color(BRANCH_COLOR_RESET));
444 strbuf_addf(&local, "%%(if)%%(upstream)%%(then)[%s%%(upstream:short)%s%%(if)%%(upstream:track)"
445 "%%(then): %%(upstream:track,nobracket)%%(end)] %%(end)%%(contents:subject)",
446 branch_get_color(BRANCH_COLOR_UPSTREAM), branch_get_color(BRANCH_COLOR_RESET));
447 }
448 else
449 strbuf_addf(&local, "%%(if)%%(upstream:track)%%(then)%%(upstream:track) %%(end)%%(contents:subject)");
450
451 strbuf_addf(&remote, "%%(align:%d,left)%s%%(refname:lstrip=2)%%(end)%s"
452 "%%(if)%%(symref)%%(then) -> %%(symref:short)"
453 "%%(else) %s %%(contents:subject)%%(end)",
454 maxwidth, quote_literal_for_format(remote_prefix),
455 branch_get_color(BRANCH_COLOR_RESET), obname.buf);
456 strbuf_release(&obname);
457 } else {
458 strbuf_addf(&local, "%%(refname:lstrip=2)%s%%(if)%%(symref)%%(then) -> %%(symref:short)%%(end)",
459 branch_get_color(BRANCH_COLOR_RESET));
460 strbuf_addf(&remote, "%s%%(refname:lstrip=2)%s%%(if)%%(symref)%%(then) -> %%(symref:short)%%(end)",
461 quote_literal_for_format(remote_prefix),
462 branch_get_color(BRANCH_COLOR_RESET));
463 }
464
465 strbuf_addf(&fmt, "%%(if:notequals=refs/remotes)%%(refname:rstrip=-2)%%(then)%s%%(else)%s%%(end)", local.buf, remote.buf);
466
467 strbuf_release(&local);
468 strbuf_release(&remote);
469 return strbuf_detach(&fmt, NULL);
470 }
471
472 static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sorting,
473 struct ref_format *format, struct string_list *output)
474 {
475 int i;
476 struct ref_array array;
477 int maxwidth = 0;
478 const char *remote_prefix = "";
479 char *to_free = NULL;
480
481 /*
482 * If we are listing more than just remote branches,
483 * then remote branches will have a "remotes/" prefix.
484 * We need to account for this in the width.
485 */
486 if (filter->kind != FILTER_REFS_REMOTES)
487 remote_prefix = "remotes/";
488
489 memset(&array, 0, sizeof(array));
490
491 filter_refs(&array, filter, filter->kind);
492
493 if (filter->verbose)
494 maxwidth = calc_maxwidth(&array, strlen(remote_prefix));
495
496 if (!format->format)
497 format->format = to_free = build_format(filter, maxwidth, remote_prefix);
498 format->use_color = branch_use_color;
499
500 if (verify_ref_format(format))
501 die(_("unable to parse format string"));
502
503 filter_ahead_behind(the_repository, &array);
504 ref_array_sort(sorting, &array);
505
506 if (column_active(colopts)) {
507 struct strbuf out = STRBUF_INIT, err = STRBUF_INIT;
508
509 assert(!filter->verbose && "--column and --verbose are incompatible");
510
511 for (i = 0; i < array.nr; i++) {
512 strbuf_reset(&err);
513 strbuf_reset(&out);
514 if (format_ref_array_item(array.items[i], format, &out, &err))
515 die("%s", err.buf);
516
517 /* format to a string_list to let print_columns() do its job */
518 string_list_append(output, out.buf);
519 }
520
521 strbuf_release(&err);
522 strbuf_release(&out);
523 } else {
524 print_formatted_ref_array(&array, format);
525 }
526
527 ref_array_clear(&array);
528 free(to_free);
529 }
530
531 static void print_current_branch_name(void)
532 {
533 int flags;
534 const char *refname = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
535 "HEAD", 0, NULL, &flags);
536 const char *shortname;
537 if (!refname)
538 die(_("could not resolve HEAD"));
539 else if (!(flags & REF_ISSYMREF))
540 return;
541 else if (skip_prefix(refname, "refs/heads/", &shortname))
542 puts(shortname);
543 else
544 die(_("HEAD (%s) points outside of refs/heads/"), refname);
545 }
546
547 static void reject_rebase_or_bisect_branch(struct worktree **worktrees,
548 const char *target)
549 {
550 int i;
551
552 for (i = 0; worktrees[i]; i++) {
553 struct worktree *wt = worktrees[i];
554
555 if (!wt->is_detached)
556 continue;
557
558 if (is_worktree_being_rebased(wt, target))
559 die(_("branch %s is being rebased at %s"),
560 target, wt->path);
561
562 if (is_worktree_being_bisected(wt, target))
563 die(_("branch %s is being bisected at %s"),
564 target, wt->path);
565 }
566 }
567
568 /*
569 * Update all per-worktree HEADs pointing at the old ref to point the new ref.
570 * This will be used when renaming a branch. Returns 0 if successful, non-zero
571 * otherwise.
572 */
573 static int replace_each_worktree_head_symref(struct worktree **worktrees,
574 const char *oldref, const char *newref,
575 const char *logmsg)
576 {
577 int ret = 0;
578 int i;
579
580 for (i = 0; worktrees[i]; i++) {
581 struct ref_store *refs;
582
583 if (worktrees[i]->is_detached)
584 continue;
585 if (!worktrees[i]->head_ref)
586 continue;
587 if (strcmp(oldref, worktrees[i]->head_ref))
588 continue;
589
590 refs = get_worktree_ref_store(worktrees[i]);
591 if (refs_update_symref(refs, "HEAD", newref, logmsg))
592 ret = error(_("HEAD of working tree %s is not updated"),
593 worktrees[i]->path);
594 }
595
596 return ret;
597 }
598
599 #define IS_HEAD 1
600 #define IS_ORPHAN 2
601
602 static void copy_or_rename_branch(const char *oldname, const char *newname, int copy, int force)
603 {
604 struct strbuf oldref = STRBUF_INIT, newref = STRBUF_INIT, logmsg = STRBUF_INIT;
605 struct strbuf oldsection = STRBUF_INIT, newsection = STRBUF_INIT;
606 const char *interpreted_oldname = NULL;
607 const char *interpreted_newname = NULL;
608 int recovery = 0, oldref_usage = 0;
609 struct worktree **worktrees = get_worktrees(the_repository);
610
611 if (check_branch_ref(the_repository, &oldref, oldname)) {
612 /*
613 * Bad name --- this could be an attempt to rename a
614 * ref that we used to allow to be created by accident.
615 */
616 if (refs_ref_exists(get_main_ref_store(the_repository), oldref.buf))
617 recovery = 1;
618 else {
619 int code = die_message(_("invalid branch name: '%s'"), oldname);
620 advise_if_enabled(ADVICE_REF_SYNTAX,
621 _("See 'git help check-ref-format'"));
622 exit(code);
623 }
624 }
625
626 for (int i = 0; worktrees[i]; i++) {
627 struct worktree *wt = worktrees[i];
628
629 if (wt->head_ref && !strcmp(oldref.buf, wt->head_ref)) {
630 oldref_usage |= IS_HEAD;
631 if (is_null_oid(&wt->head_oid))
632 oldref_usage |= IS_ORPHAN;
633 break;
634 }
635 }
636
637 if ((copy || !(oldref_usage & IS_HEAD)) && !refs_ref_exists(get_main_ref_store(the_repository), oldref.buf)) {
638 if (oldref_usage & IS_HEAD)
639 die(_("no commit on branch '%s' yet"), oldname);
640 else
641 die(_("no branch named '%s'"), oldname);
642 }
643
644 /*
645 * A command like "git branch -M currentbranch currentbranch" cannot
646 * cause the worktree to become inconsistent with HEAD, so allow it.
647 */
648 if (!strcmp(oldname, newname))
649 validate_branchname(newname, &newref);
650 else
651 validate_new_branchname(newname, &newref, force);
652
653 reject_rebase_or_bisect_branch(worktrees, oldref.buf);
654
655 if (!skip_prefix(oldref.buf, "refs/heads/", &interpreted_oldname) ||
656 !skip_prefix(newref.buf, "refs/heads/", &interpreted_newname)) {
657 BUG("expected prefix missing for refs");
658 }
659
660 if (copy)
661 strbuf_addf(&logmsg, "Branch: copied %s to %s",
662 oldref.buf, newref.buf);
663 else
664 strbuf_addf(&logmsg, "Branch: renamed %s to %s",
665 oldref.buf, newref.buf);
666
667 if (!copy && !(oldref_usage & IS_ORPHAN) &&
668 refs_rename_ref(get_main_ref_store(the_repository), oldref.buf, newref.buf, logmsg.buf))
669 die(_("branch rename failed"));
670 if (copy && refs_copy_existing_ref(get_main_ref_store(the_repository), oldref.buf, newref.buf, logmsg.buf))
671 die(_("branch copy failed"));
672
673 if (recovery) {
674 if (copy)
675 warning(_("created a copy of a misnamed branch '%s'"),
676 interpreted_oldname);
677 else
678 warning(_("renamed a misnamed branch '%s' away"),
679 interpreted_oldname);
680 }
681
682 if (!copy && (oldref_usage & IS_HEAD) &&
683 replace_each_worktree_head_symref(worktrees, oldref.buf, newref.buf,
684 logmsg.buf))
685 die(_("branch renamed to %s, but HEAD is not updated"), newname);
686
687 strbuf_release(&logmsg);
688
689 strbuf_addf(&oldsection, "branch.%s", interpreted_oldname);
690 strbuf_addf(&newsection, "branch.%s", interpreted_newname);
691 if (!copy && repo_config_rename_section(the_repository, oldsection.buf, newsection.buf) < 0)
692 die(_("branch is renamed, but update of config-file failed"));
693 if (copy && strcmp(interpreted_oldname, interpreted_newname) &&
694 repo_config_copy_section(the_repository, oldsection.buf, newsection.buf) < 0)
695 die(_("branch is copied, but update of config-file failed"));
696 strbuf_release(&oldref);
697 strbuf_release(&newref);
698 strbuf_release(&oldsection);
699 strbuf_release(&newsection);
700 free_worktrees(worktrees);
701 }
702
703 static int parse_opt_forked(const struct option *opt, const char *arg, int unset)
704 {
705 struct ref_filter *filter = opt->value;
706
707 BUG_ON_OPT_NEG(unset);
708 if (ref_filter_forked_add(filter, arg) < 0)
709 die(_("'%s' is not a valid branch or pattern"), arg);
710 return 0;
711 }
712
713 struct stacked_branch_data {
714 struct strset *deletable_branch_names;
715 struct strset *protected_branch_names;
716 struct strset *visited_branch_names;
717 };
718
719 static int collect_stacked_branch_bases(const struct reference *ref,
720 void *cb_data)
721 {
722 struct stacked_branch_data *data = cb_data;
723 const char *branch_name;
724
725 if (!skip_prefix(ref->name, "refs/heads/", &branch_name))
726 BUG("expected local branch ref, got '%s'", ref->name);
727 if (strset_contains(data->deletable_branch_names, branch_name))
728 return 0;
729
730 while (strset_add(data->visited_branch_names, branch_name)) {
731 struct branch *branch = branch_get(branch_name);
732 const char *upstream_refname = branch_get_upstream(branch, NULL);
733 const char *upstream_branch_name;
734
735 if (!upstream_refname ||
736 !skip_prefix(upstream_refname, "refs/heads/",
737 &upstream_branch_name) ||
738 !strset_contains(data->deletable_branch_names,
739 upstream_branch_name))
740 break;
741
742 strset_add(data->protected_branch_names, upstream_branch_name);
743 branch_name = upstream_branch_name;
744 }
745
746 return 0;
747 }
748
749 static void protect_stacked_branch_bases(struct ref_store *refs,
750 struct strset *deletable_branch_names)
751 {
752 struct strset protected_branch_names = STRSET_INIT;
753 struct strset visited_branch_names = STRSET_INIT;
754 struct stacked_branch_data data = {
755 .deletable_branch_names = deletable_branch_names,
756 .protected_branch_names = &protected_branch_names,
757 .visited_branch_names = &visited_branch_names,
758 };
759 struct refs_for_each_ref_options opts = {
760 .prefix = "refs/heads/",
761 };
762 struct hashmap_iter iter;
763 struct strmap_entry *entry;
764
765 refs_for_each_ref_ext(refs, collect_stacked_branch_bases, &data, &opts);
766
767 strset_for_each_entry(&protected_branch_names, &iter, entry)
768 strset_remove(deletable_branch_names, entry->key);
769
770 strset_clear(&visited_branch_names);
771 strset_clear(&protected_branch_names);
772 }
773
774 static int branch_pushes_to_upstream(struct branch *branch,
775 const char *upstream)
776 {
777 struct remote *remote = remote_get(remote_for_branch(branch, NULL));
778 char *tracking = NULL;
779 int ret = 0;
780
781 if (remote)
782 tracking = apply_refspecs(&remote->fetch, branch->refname);
783 if (tracking && !strcmp(tracking, upstream))
784 ret = 1;
785
786 free(tracking);
787 return ret;
788 }
789
790 static int delete_merged_branches(const struct strvec *upstreams,
791 const char **argv, unsigned int flags)
792 {
793 struct ref_store *refs = get_main_ref_store(the_repository);
794 struct ref_filter filter = REF_FILTER_INIT;
795 struct ref_array candidates = { 0 };
796 struct strset deletable_branch_names = STRSET_INIT;
797 struct strvec branches_to_delete = STRVEC_INIT;
798 struct strbuf key = STRBUF_INIT;
799 struct hashmap_iter iter;
800 struct strmap_entry *entry;
801 size_t i;
802 int ret = 0;
803
804 for (i = 0; i < upstreams->nr; i++)
805 if (ref_filter_forked_add(&filter, upstreams->v[i]) < 0)
806 die(_("'%s' is not a valid branch or pattern"),
807 upstreams->v[i]);
808
809 filter.kind = FILTER_REFS_BRANCHES;
810 filter.name_patterns = argv;
811 filter_refs(&candidates, &filter, filter.kind);
812
813 for (i = 0; i < (size_t)candidates.nr; i++) {
814 const char *branch_refname = candidates.items[i]->refname;
815 const char *branch_name;
816 struct branch *branch;
817 const char *upstream_refname;
818 int opt_out;
819
820 if (!skip_prefix(branch_refname, "refs/heads/", &branch_name))
821 BUG("filter returned non-branch ref '%s'", branch_refname);
822 if (branch_checked_out(branch_refname))
823 continue;
824
825 branch = branch_get(branch_name);
826 upstream_refname = branch_get_upstream(branch, NULL);
827 if (!upstream_refname || !refs_ref_exists(refs, upstream_refname))
828 continue;
829 if (branch_pushes_to_upstream(branch, upstream_refname))
830 continue;
831 if (check_branch_commit(branch_name, branch_name,
832 &candidates.items[i]->objectname, NULL,
833 FILTER_REFS_BRANCHES, DELETE_BRANCH_SKIP_UNMERGED))
834 continue;
835
836 strbuf_reset(&key);
837 strbuf_addf(&key, "branch.%s.deletemerged", branch_name);
838 if (!repo_config_get_bool(the_repository, key.buf, &opt_out) &&
839 !opt_out) {
840 if (!(flags & DELETE_BRANCH_QUIET))
841 fprintf(stderr,
842 _("Skipping '%s' (branch.%s.deleteMerged is false)\n"),
843 branch_name, branch_name);
844 continue;
845 }
846
847 strset_add(&deletable_branch_names, branch_name);
848 }
849
850 protect_stacked_branch_bases(refs, &deletable_branch_names);
851
852 strset_for_each_entry(&deletable_branch_names, &iter, entry)
853 strvec_push(&branches_to_delete, entry->key);
854
855 if (branches_to_delete.nr)
856 ret = delete_branches(branches_to_delete.nr, branches_to_delete.v,
857 FILTER_REFS_BRANCHES,
858 DELETE_BRANCH_SKIP_UNMERGED |
859 DELETE_BRANCH_NO_HEAD_FALLBACK |
860 flags);
861
862 strbuf_release(&key);
863 strvec_clear(&branches_to_delete);
864 strset_clear(&deletable_branch_names);
865 ref_array_clear(&candidates);
866 ref_filter_clear(&filter);
867 return ret;
868 }
869
870 static GIT_PATH_FUNC(edit_description, "EDIT_DESCRIPTION")
871
872 static int edit_branch_description(const char *branch_name)
873 {
874 int exists;
875 struct strbuf buf = STRBUF_INIT;
876 struct strbuf name = STRBUF_INIT;
877
878 exists = !read_branch_desc(&buf, branch_name);
879 if (!buf.len || buf.buf[buf.len-1] != '\n')
880 strbuf_addch(&buf, '\n');
881 strbuf_commented_addf(&buf, comment_line_str,
882 _("Please edit the description for the branch\n"
883 " %s\n"
884 "Lines starting with '%s' will be stripped.\n"),
885 branch_name, comment_line_str);
886 write_file_buf(edit_description(), buf.buf, buf.len);
887 strbuf_reset(&buf);
888 if (launch_editor(edit_description(), &buf, NULL)) {
889 strbuf_release(&buf);
890 return -1;
891 }
892 strbuf_stripspace(&buf, comment_line_str);
893
894 strbuf_addf(&name, "branch.%s.description", branch_name);
895 if (buf.len || exists)
896 repo_config_set(the_repository, name.buf, buf.len ? buf.buf : NULL);
897 strbuf_release(&name);
898 strbuf_release(&buf);
899
900 return 0;
901 }
902
903 static void die_if_upstream_looks_like_remote(const char *new_upstream, const char *branch_name)
904 {
905 struct strbuf remote_ref = STRBUF_INIT;
906 int code;
907
908 if (strchr(new_upstream, '/') ||
909 !remote_is_configured(remote_get(new_upstream), 0))
910 return;
911
912 strbuf_addf(&remote_ref, "refs/remotes/%s/%s", new_upstream, branch_name);
913 if (!refs_ref_exists(get_main_ref_store(the_repository), remote_ref.buf)) {
914 strbuf_release(&remote_ref);
915 return;
916 }
917
918 code = die_message(_("--set-upstream-to takes a single <remote>/<branch> argument"));
919 advise_if_enabled(ADVICE_SET_UPSTREAM_FAILURE,
920 _("Did you mean to use: git branch --set-upstream-to=%s/%s?"),
921 new_upstream, branch_name);
922 strbuf_release(&remote_ref);
923 exit(code);
924 }
925
926 int cmd_branch(int argc,
927 const char **argv,
928 const char *prefix,
929 struct repository *repo UNUSED)
930 {
931 /* possible actions */
932 int delete = 0, rename = 0, copy = 0, list = 0,
933 unset_upstream = 0, show_current = 0, edit_description = 0;
934 struct strvec delete_merged = STRVEC_INIT;
935 int dry_run = 0;
936 const char *new_upstream = NULL;
937 int noncreate_actions = 0;
938 /* possible options */
939 int reflog = 0, quiet = 0, icase = 0, force = 0,
940 recurse_submodules_explicit = 0;
941 enum branch_track track;
942 struct ref_filter filter = REF_FILTER_INIT;
943 static struct ref_sorting *sorting;
944 struct string_list sorting_options = STRING_LIST_INIT_DUP;
945 struct ref_format format = REF_FORMAT_INIT;
946 struct repo_config_values *cfg = repo_config_values(the_repository);
947 int ret;
948
949 struct option options[] = {
950 OPT_GROUP(N_("Generic options")),
951 OPT__VERBOSE(&filter.verbose,
952 N_("show hash and subject, give twice for upstream branch")),
953 OPT__QUIET(&quiet, N_("suppress informational messages")),
954 OPT_CALLBACK_F('t', "track", &track, "(direct|inherit)",
955 N_("set branch tracking configuration"),
956 PARSE_OPT_OPTARG,
957 parse_opt_tracking_mode),
958 OPT_SET_INT_F(0, "set-upstream", &track, N_("do not use"),
959 BRANCH_TRACK_OVERRIDE, PARSE_OPT_HIDDEN),
960 OPT_STRING('u', "set-upstream-to", &new_upstream, N_("upstream"), N_("change the upstream info")),
961 OPT_BOOL(0, "unset-upstream", &unset_upstream, N_("unset the upstream info")),
962 OPT__COLOR(&branch_use_color, N_("use colored output")),
963 OPT_SET_INT_F('r', "remotes", &filter.kind, N_("act on remote-tracking branches"),
964 FILTER_REFS_REMOTES,
965 PARSE_OPT_NONEG),
966 OPT_CONTAINS(&filter.with_commit, N_("print only branches that contain the commit")),
967 OPT_NO_CONTAINS(&filter.no_commit, N_("print only branches that don't contain the commit")),
968 OPT_WITH(&filter.with_commit, N_("print only branches that contain the commit")),
969 OPT_WITHOUT(&filter.no_commit, N_("print only branches that don't contain the commit")),
970 OPT__ABBREV(&filter.abbrev),
971
972 OPT_GROUP(N_("Specific git-branch actions:")),
973 OPT_SET_INT_F('a', "all", &filter.kind, N_("list both remote-tracking and local branches"),
974 FILTER_REFS_REMOTES | FILTER_REFS_BRANCHES,
975 PARSE_OPT_NONEG),
976 OPT_BIT('d', "delete", &delete, N_("delete fully merged branch"), 1),
977 OPT_BIT('D', NULL, &delete, N_("delete branch (even if not merged)"), 2),
978 OPT_BIT('m', "move", &rename, N_("move/rename a branch and its reflog"), 1),
979 OPT_BIT('M', NULL, &rename, N_("move/rename a branch, even if target exists"), 2),
980 OPT_BOOL(0, "omit-empty", &format.array_opts.omit_empty,
981 N_("do not output a newline after empty formatted refs")),
982 OPT_BIT('c', "copy", &copy, N_("copy a branch and its reflog"), 1),
983 OPT_BIT('C', NULL, &copy, N_("copy a branch, even if target exists"), 2),
984 OPT_BOOL('l', "list", &list, N_("list branch names")),
985 OPT_BOOL(0, "show-current", &show_current, N_("show current branch name")),
986 OPT_BOOL(0, "create-reflog", &reflog, N_("create the branch's reflog")),
987 OPT_BOOL(0, "edit-description", &edit_description,
988 N_("edit the description for the branch")),
989 OPT_CALLBACK_F(0, "delete-merged", &delete_merged, N_("branch"),
990 N_("delete merged branches whose upstream matches <branch> (repeatable)"),
991 PARSE_OPT_NONEG, parse_opt_strvec),
992 OPT_BOOL(0, "dry-run", &dry_run,
993 N_("with --delete-merged, only print which branches would be deleted")),
994 OPT__FORCE(&force, N_("force creation, move/rename, deletion"), PARSE_OPT_NOCOMPLETE),
995 OPT_MERGED(&filter, N_("print only branches that are merged")),
996 OPT_NO_MERGED(&filter, N_("print only branches that are not merged")),
997 OPT_CALLBACK_F(0, "forked", &filter, N_("branch"),
998 N_("print only branches whose upstream matches <branch> (repeatable)"),
999 PARSE_OPT_NONEG, parse_opt_forked),
1000 OPT_COLUMN(0, "column", &colopts, N_("list branches in columns")),
1001 OPT_REF_SORT(&sorting_options),
1002 OPT_CALLBACK(0, "points-at", &filter.points_at, N_("object"),
1003 N_("print only branches of the object"), parse_opt_object_name),
1004 OPT_BOOL('i', "ignore-case", &icase, N_("sorting and filtering are case insensitive")),
1005 OPT_BOOL(0, "recurse-submodules", &recurse_submodules_explicit, N_("recurse through submodules")),
1006 OPT_STRING( 0 , "format", &format.format, N_("format"), N_("format to use for the output")),
1007 OPT_END(),
1008 };
1009
1010 setup_ref_filter_porcelain_msg();
1011
1012 filter.kind = FILTER_REFS_BRANCHES;
1013 filter.abbrev = -1;
1014
1015 show_usage_with_options_if_asked(argc, argv,
1016 builtin_branch_usage, options);
1017
1018 /*
1019 * Try to set sort keys from config. If config does not set any,
1020 * fall back on default (refname) sorting.
1021 */
1022 repo_config(the_repository, git_branch_config, &sorting_options);
1023 if (!sorting_options.nr)
1024 string_list_append(&sorting_options, "refname");
1025
1026 track = cfg->branch_track;
1027
1028 head = refs_resolve_refdup(get_main_ref_store(the_repository), "HEAD",
1029 0, &head_oid, NULL);
1030 if (!head)
1031 die(_("failed to resolve HEAD as a valid ref"));
1032 if (!strcmp(head, "HEAD"))
1033 filter.detached = 1;
1034 else if (!skip_prefix(head, "refs/heads/", &head))
1035 die(_("HEAD not found below refs/heads!"));
1036
1037 argc = parse_options(argc, argv, prefix, options, builtin_branch_usage,
1038 0);
1039
1040 if (!delete && !rename && !copy && !edit_description && !new_upstream &&
1041 !show_current && !unset_upstream && !delete_merged.nr &&
1042 argc == 0)
1043 list = 1;
1044
1045 if (filter.with_commit || filter.no_commit ||
1046 filter.reachable_from || filter.unreachable_from ||
1047 filter.points_at.nr || filter.forked.nr)
1048 list = 1;
1049
1050 noncreate_actions = !!delete + !!rename + !!copy + !!new_upstream +
1051 !!show_current + !!list + !!edit_description +
1052 !!unset_upstream + !!delete_merged.nr;
1053 if (noncreate_actions > 1)
1054 usage_with_options(builtin_branch_usage, options);
1055
1056 if (dry_run && !delete_merged.nr)
1057 die(_("--dry-run requires --delete-merged"));
1058
1059 if (recurse_submodules_explicit) {
1060 if (!submodule_propagate_branches)
1061 die(_("branch with --recurse-submodules can only be used if submodule.propagateBranches is enabled"));
1062 if (noncreate_actions)
1063 die(_("--recurse-submodules can only be used to create branches"));
1064 }
1065
1066 recurse_submodules =
1067 (recurse_submodules || recurse_submodules_explicit) &&
1068 submodule_propagate_branches;
1069
1070 if (filter.abbrev == -1)
1071 filter.abbrev = DEFAULT_ABBREV;
1072 filter.ignore_case = icase;
1073
1074 finalize_colopts(&colopts, -1);
1075 if (filter.verbose) {
1076 if (explicitly_enable_column(colopts))
1077 die(_("options '%s' and '%s' cannot be used together"), "--column", "--verbose");
1078 colopts = 0;
1079 }
1080
1081 if (force) {
1082 delete *= 2;
1083 rename *= 2;
1084 copy *= 2;
1085 }
1086
1087 if (list)
1088 setup_auto_pager("branch", 1);
1089
1090 if (delete) {
1091 if (!argc)
1092 die(_("branch name required"));
1093 ret = delete_branches(argc, argv, filter.kind,
1094 (delete > 1 ? DELETE_BRANCH_FORCE : 0) |
1095 (quiet ? DELETE_BRANCH_QUIET : 0));
1096 goto out;
1097 } else if (delete_merged.nr) {
1098 ret = delete_merged_branches(&delete_merged, argv,
1099 (quiet ? DELETE_BRANCH_QUIET : 0) |
1100 (dry_run ? DELETE_BRANCH_DRY_RUN : 0));
1101 goto out;
1102 } else if (show_current) {
1103 print_current_branch_name();
1104 ret = 0;
1105 goto out;
1106 } else if (list) {
1107 /* git branch --list also shows HEAD when it is detached */
1108 if ((filter.kind & FILTER_REFS_BRANCHES) && filter.detached)
1109 filter.kind |= FILTER_REFS_DETACHED_HEAD;
1110 filter.name_patterns = argv;
1111 /*
1112 * If no sorting parameter is given then we default to sorting
1113 * by 'refname'. This would give us an alphabetically sorted
1114 * array with the 'HEAD' ref at the beginning followed by
1115 * local branches 'refs/heads/...' and finally remote-tracking
1116 * branches 'refs/remotes/...'.
1117 */
1118 sorting = ref_sorting_options(&sorting_options);
1119 ref_sorting_set_sort_flags_all(sorting, REF_SORTING_ICASE, icase);
1120 ref_sorting_set_sort_flags_all(
1121 sorting, REF_SORTING_DETACHED_HEAD_FIRST, 1);
1122 print_ref_list(&filter, sorting, &format, &output);
1123 print_columns(&output, colopts, NULL);
1124 string_list_clear(&output, 0);
1125 ref_sorting_release(sorting);
1126 ref_filter_clear(&filter);
1127
1128 ret = 0;
1129 goto out;
1130 } else if (edit_description) {
1131 const char *branch_name;
1132 struct strbuf branch_ref = STRBUF_INIT;
1133 struct strbuf buf = STRBUF_INIT;
1134
1135 if (!argc) {
1136 if (filter.detached)
1137 die(_("cannot give description to detached HEAD"));
1138 branch_name = head;
1139 } else if (argc == 1) {
1140 copy_branchname(the_repository, &buf, argv[0],
1141 INTERPRET_BRANCH_LOCAL);
1142 branch_name = buf.buf;
1143 } else {
1144 die(_("cannot edit description of more than one branch"));
1145 }
1146
1147 strbuf_addf(&branch_ref, "refs/heads/%s", branch_name);
1148 if (!refs_ref_exists(get_main_ref_store(the_repository), branch_ref.buf)) {
1149 error((!argc || branch_checked_out(branch_ref.buf))
1150 ? _("no commit on branch '%s' yet")
1151 : _("no branch named '%s'"),
1152 branch_name);
1153 ret = 1;
1154 } else if (!edit_branch_description(branch_name)) {
1155 ret = 0; /* happy */
1156 } else {
1157 ret = 1;
1158 }
1159
1160 strbuf_release(&branch_ref);
1161 strbuf_release(&buf);
1162
1163 goto out;
1164 } else if (copy || rename) {
1165 if (!argc)
1166 die(_("branch name required"));
1167 else if ((argc == 1) && filter.detached)
1168 die(copy? _("cannot copy the current branch while not on any")
1169 : _("cannot rename the current branch while not on any"));
1170 else if (argc == 1)
1171 copy_or_rename_branch(head, argv[0], copy, copy + rename > 1);
1172 else if (argc == 2)
1173 copy_or_rename_branch(argv[0], argv[1], copy, copy + rename > 1);
1174 else
1175 die(copy? _("too many branches for a copy operation")
1176 : _("too many arguments for a rename operation"));
1177 } else if (new_upstream) {
1178 struct branch *branch;
1179 struct strbuf buf = STRBUF_INIT;
1180
1181 if (!argc)
1182 branch = branch_get(NULL);
1183 else if (argc == 1) {
1184 copy_branchname(the_repository, &buf, argv[0],
1185 INTERPRET_BRANCH_LOCAL);
1186 branch = branch_get(buf.buf);
1187 } else
1188 die(_("too many arguments to set new upstream"));
1189
1190 if (!branch) {
1191 if (!argc || !strcmp(argv[0], "HEAD"))
1192 die(_("could not set upstream of HEAD to %s when "
1193 "it does not point to any branch"),
1194 new_upstream);
1195 die(_("no such branch '%s'"), argv[0]);
1196 }
1197
1198 if (!refs_ref_exists(get_main_ref_store(the_repository), branch->refname)) {
1199 if (!argc || branch_checked_out(branch->refname))
1200 die(_("no commit on branch '%s' yet"), branch->name);
1201 /*
1202 * Check the advice up front to avoid the ref
1203 * lookups when the hint is off. The helper still
1204 * calls advise_if_enabled() so the hint carries the
1205 * standard "disable this message" instructions.
1206 */
1207 if (argc == 1 &&
1208 advice_enabled(ADVICE_SET_UPSTREAM_FAILURE))
1209 die_if_upstream_looks_like_remote(new_upstream, argv[0]);
1210 die(_("branch '%s' does not exist"), branch->name);
1211 }
1212
1213 dwim_and_setup_tracking(the_repository, branch->name,
1214 new_upstream, BRANCH_TRACK_OVERRIDE,
1215 quiet);
1216 strbuf_release(&buf);
1217 } else if (unset_upstream) {
1218 struct branch *branch;
1219 struct strbuf buf = STRBUF_INIT;
1220
1221 if (!argc)
1222 branch = branch_get(NULL);
1223 else if (argc == 1) {
1224 copy_branchname(the_repository, &buf, argv[0],
1225 INTERPRET_BRANCH_LOCAL);
1226 branch = branch_get(buf.buf);
1227 } else
1228 die(_("too many arguments to unset upstream"));
1229
1230 if (!branch) {
1231 if (!argc || !strcmp(argv[0], "HEAD"))
1232 die(_("could not unset upstream of HEAD when "
1233 "it does not point to any branch"));
1234 die(_("no such branch '%s'"), argv[0]);
1235 }
1236
1237 if (!branch_has_merge_config(branch))
1238 die(_("branch '%s' has no upstream information"), branch->name);
1239
1240 strbuf_reset(&buf);
1241 strbuf_addf(&buf, "branch.%s.remote", branch->name);
1242 repo_config_set_multivar(the_repository, buf.buf, NULL, NULL, CONFIG_FLAGS_MULTI_REPLACE);
1243 strbuf_reset(&buf);
1244 strbuf_addf(&buf, "branch.%s.merge", branch->name);
1245 repo_config_set_multivar(the_repository, buf.buf, NULL, NULL, CONFIG_FLAGS_MULTI_REPLACE);
1246 strbuf_release(&buf);
1247 } else if (!noncreate_actions && argc > 0 && argc <= 2) {
1248 const char *branch_name = argv[0];
1249 const char *start_name = argc == 2 ? argv[1] : head;
1250
1251 if (filter.kind != FILTER_REFS_BRANCHES)
1252 die(_("the -a, and -r, options to 'git branch' do not take a branch name.\n"
1253 "Did you mean to use: -a|-r --list <pattern>?"));
1254
1255 if (track == BRANCH_TRACK_OVERRIDE)
1256 die(_("the '--set-upstream' option is no longer supported. Please use '--track' or '--set-upstream-to' instead"));
1257
1258 if (recurse_submodules) {
1259 create_branches_recursively(the_repository, branch_name,
1260 start_name, NULL, force,
1261 reflog, quiet, track, 0);
1262 ret = 0;
1263 goto out;
1264 }
1265 create_branch(the_repository, branch_name, start_name, force, 0,
1266 reflog, quiet, track, 0);
1267 } else
1268 usage_with_options(builtin_branch_usage, options);
1269
1270 ret = 0;
1271
1272 out:
1273 strvec_clear(&delete_merged);
1274 string_list_clear(&sorting_options, 0);
1275 return ret;
1276 }