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