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