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