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