]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/branch.c
object-name.h: move declarations for object-name.c functions from cache.h
[thirdparty/git.git] / builtin / branch.c
CommitLineData
c31820c2
LH
1/*
2 * Builtin "git branch"
3 *
d972cce0 4 * Copyright (c) 2006 Kristian Høgsberg <krh@redhat.com>
c31820c2
LH
5 * Based on git-branch.sh by Junio C Hamano.
6 */
7
8#include "cache.h"
b2141fc1 9#include "config.h"
85023577 10#include "color.h"
7ee24e18 11#include "environment.h"
c31820c2
LH
12#include "refs.h"
13#include "commit.h"
14#include "builtin.h"
f394e093 15#include "gettext.h"
dabab1d6 16#include "object-name.h"
6f084a56 17#include "remote.h"
a8dfd5ea 18#include "parse-options.h"
e496c003 19#include "branch.h"
68067ca1
JH
20#include "diff.h"
21#include "revision.h"
ebe31ef2
NTND
22#include "string-list.h"
23#include "column.h"
1452bd64 24#include "utf8.h"
c8183cd2 25#include "wt-status.h"
1511b22d 26#include "ref-filter.h"
f292244c 27#include "worktree.h"
3ac68a93 28#include "help.h"
64043556 29#include "commit-reach.h"
d5ebb50d 30#include "wrapper.h"
a8dfd5ea
PH
31
32static const char * const builtin_branch_usage[] = {
21bf9339 33 N_("git branch [<options>] [-r | -a] [--merged] [--no-merged]"),
961b130d
GC
34 N_("git branch [<options>] [-f] [--recurse-submodules] <branch-name> [<start-point>]"),
35 N_("git branch [<options>] [-l] [<pattern>...]"),
9c9b4f2f
AH
36 N_("git branch [<options>] [-r] (-d | -D) <branch-name>..."),
37 N_("git branch [<options>] (-m | -M) [<old-branch>] <new-branch>"),
52d59cc6 38 N_("git branch [<options>] (-c | -C) [<old-branch>] <new-branch>"),
aa3bc55e 39 N_("git branch [<options>] [-r | -a] [--points-at]"),
3d9e4ce3 40 N_("git branch [<options>] [-r | -a] [--format]"),
a8dfd5ea
PH
41 NULL
42};
c31820c2 43
c31820c2 44static const char *head;
0c77cd24 45static struct object_id head_oid;
961b130d
GC
46static int recurse_submodules = 0;
47static int submodule_propagate_branches = 0;
c31820c2 48
6b2f2d98 49static int branch_use_color = -1;
a1158cae 50static char branch_colors[][COLOR_MAXLEN] = {
dc6ebd4c 51 GIT_COLOR_RESET,
949af068
KN
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 */
ab313814 57 GIT_COLOR_CYAN, /* WORKTREE */
a1158cae
AP
58};
59enum color_branch {
74bb2dfb
AL
60 BRANCH_COLOR_RESET = 0,
61 BRANCH_COLOR_PLAIN = 1,
62 BRANCH_COLOR_REMOTE = 2,
63 BRANCH_COLOR_LOCAL = 3,
dbda21fa 64 BRANCH_COLOR_CURRENT = 4,
ab313814
NB
65 BRANCH_COLOR_UPSTREAM = 5,
66 BRANCH_COLOR_WORKTREE = 6
a1158cae
AP
67};
68
a73b3680
NTND
69static 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",
ab313814 76 [BRANCH_COLOR_WORKTREE] = "worktree",
a73b3680
NTND
77};
78
ebe31ef2
NTND
79static struct string_list output = STRING_LIST_INIT_DUP;
80static unsigned int colopts;
81
3ac68a93 82define_list_config_array(color_branch_slots);
a1158cae 83
ef90d6d4 84static int git_branch_config(const char *var, const char *value, void *cb)
a1158cae 85{
e3f1da98 86 const char *slot_name;
560ae1c1
SM
87
88 if (!strcmp(var, "branch.sort")) {
89 if (!value)
90 return config_error_nonbool(var);
98e7ab6d 91 string_list_append(cb, value);
560ae1c1
SM
92 return 0;
93 }
e3f1da98 94
59556548 95 if (starts_with(var, "column."))
ebe31ef2 96 return git_column_config(var, value, "branch", &colopts);
a1158cae 97 if (!strcmp(var, "color.branch")) {
e269eb79 98 branch_use_color = git_config_colorbool(var, value);
a1158cae
AP
99 return 0;
100 }
e3f1da98 101 if (skip_prefix(var, "color.branch.", &slot_name)) {
a73b3680 102 int slot = LOOKUP_CONFIG(color_branch_slots, slot_name);
8b8e8624
JK
103 if (slot < 0)
104 return 0;
5768c98a
JH
105 if (!value)
106 return config_error_nonbool(var);
f6c5a296 107 return color_parse(value, branch_colors[slot]);
a1158cae 108 }
961b130d
GC
109 if (!strcmp(var, "submodule.recurse")) {
110 recurse_submodules = git_config_bool(var, value);
111 return 0;
112 }
113 if (!strcasecmp(var, "submodule.propagateBranches")) {
114 submodule_propagate_branches = git_config_bool(var, value);
115 return 0;
116 }
117
33c643bb 118 return git_color_default_config(var, value, cb);
a1158cae
AP
119}
120
52fae7de 121static const char *branch_get_color(enum color_branch ix)
a1158cae 122{
daa0c3d9 123 if (want_color(branch_use_color))
a1158cae
AP
124 return branch_colors[ix];
125 return "";
126}
127
99c419c9
JH
128static int branch_merged(int kind, const char *name,
129 struct commit *rev, struct commit *head_rev)
130{
131 /*
132 * This checks whether the merge bases of branch and HEAD (or
133 * the other branch this branch builds upon) contains the
134 * branch, which means that the branch has already been merged
135 * safely to HEAD (or the other branch).
136 */
137 struct commit *reference_rev = NULL;
138 const char *reference_name = NULL;
96ec7b1e 139 void *reference_name_to_free = NULL;
99c419c9
JH
140 int merged;
141
1511b22d 142 if (kind == FILTER_REFS_BRANCHES) {
99c419c9 143 struct branch *branch = branch_get(name);
3a429d0a 144 const char *upstream = branch_get_upstream(branch, NULL);
0c77cd24 145 struct object_id oid;
99c419c9 146
a9f9f8cc 147 if (upstream &&
96ec7b1e 148 (reference_name = reference_name_to_free =
a9f9f8cc 149 resolve_refdup(upstream, RESOLVE_REF_READING,
0f2dc722 150 &oid, NULL)) != NULL)
2122f675
SB
151 reference_rev = lookup_commit_reference(the_repository,
152 &oid);
99c419c9
JH
153 }
154 if (!reference_rev)
155 reference_rev = head_rev;
156
cb338c23
ÆAB
157 merged = reference_rev ? repo_in_merge_bases(the_repository, rev,
158 reference_rev) : 0;
99c419c9
JH
159
160 /*
161 * After the safety valve is fully redefined to "check with
162 * upstream, if any, otherwise with HEAD", we should just
c7c33f50 163 * return the result of the repo_in_merge_bases() above without
99c419c9
JH
164 * any of the following code, but during the transition period,
165 * a gentle reminder is in order.
166 */
167 if ((head_rev != reference_rev) &&
cb338c23 168 (head_rev ? repo_in_merge_bases(the_repository, rev, head_rev) : 0) != merged) {
99c419c9 169 if (merged)
49df4b02 170 warning(_("deleting branch '%s' that has been merged to\n"
6c80cd29 171 " '%s', but not yet merged to HEAD."),
99c419c9
JH
172 name, reference_name);
173 else
49df4b02
ÆAB
174 warning(_("not deleting branch '%s' that is not yet merged to\n"
175 " '%s', even though it is merged to HEAD."),
99c419c9
JH
176 name, reference_name);
177 }
96ec7b1e 178 free(reference_name_to_free);
99c419c9
JH
179 return merged;
180}
181
f5d0e162 182static int check_branch_commit(const char *branchname, const char *refname,
0c77cd24 183 const struct object_id *oid, struct commit *head_rev,
f5d0e162
RS
184 int kinds, int force)
185{
2122f675 186 struct commit *rev = lookup_commit_reference(the_repository, oid);
597a9774 187 if (!force && !rev) {
f5d0e162
RS
188 error(_("Couldn't look up commit object for '%s'"), refname);
189 return -1;
190 }
191 if (!force && !branch_merged(kinds, branchname, rev, head_rev)) {
192 error(_("The branch '%s' is not fully merged.\n"
193 "If you are sure you want to delete it, "
194 "run 'git branch -D %s'."), branchname, branchname);
195 return -1;
196 }
197 return 0;
198}
199
22ed7927
RS
200static void delete_branch_config(const char *branchname)
201{
202 struct strbuf buf = STRBUF_INIT;
203 strbuf_addf(&buf, "branch.%s", branchname);
204 if (git_config_rename_section(buf.buf, NULL) < 0)
205 warning(_("Update of config-file failed"));
206 strbuf_release(&buf);
207}
208
d65ddf19
JK
209static int delete_branches(int argc, const char **argv, int force, int kinds,
210 int quiet)
c31820c2 211{
f5d0e162 212 struct commit *head_rev = NULL;
0c77cd24 213 struct object_id oid;
b8e9a00d 214 char *name = NULL;
c179837c 215 const char *fmt;
c31820c2 216 int i;
b8e9a00d 217 int ret = 0;
c179837c 218 int remote_branch = 0;
8415d5c7 219 struct strbuf bname = STRBUF_INIT;
6b145e01 220 unsigned allowed_interpret;
81989077
PH
221 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
222 struct string_list_item *item;
223 int branch_name_pos;
c31820c2 224
f3d985c3 225 switch (kinds) {
1511b22d 226 case FILTER_REFS_REMOTES:
f3d985c3 227 fmt = "refs/remotes/%s";
c179837c
ÆAB
228 /* For subsequent UI messages */
229 remote_branch = 1;
6b145e01 230 allowed_interpret = INTERPRET_BRANCH_REMOTE;
c179837c 231
f3d985c3
JH
232 force = 1;
233 break;
1511b22d 234 case FILTER_REFS_BRANCHES:
f3d985c3 235 fmt = "refs/heads/%s";
6b145e01 236 allowed_interpret = INTERPRET_BRANCH_LOCAL;
f3d985c3
JH
237 break;
238 default:
49df4b02 239 die(_("cannot use -a with -d"));
f3d985c3 240 }
81989077 241 branch_name_pos = strcspn(fmt, "%");
c31820c2 242
eb20e63f 243 if (!force)
2122f675 244 head_rev = lookup_commit_reference(the_repository, &head_oid);
c8dd491f 245
a9155c50 246 for (i = 0; i < argc; i++, strbuf_reset(&bname)) {
8bb04553 247 char *target = NULL;
0fe700e3
RS
248 int flags = 0;
249
6b145e01 250 strbuf_branchname(&bname, argv[i], allowed_interpret);
8e0f7003 251 free(name);
4e2d094d 252 name = mkpathdup(fmt, bname.buf);
f292244c
KY
253
254 if (kinds == FILTER_REFS_BRANCHES) {
b489b9d9
DS
255 const char *path;
256 if ((path = branch_checked_out(name))) {
f292244c
KY
257 error(_("Cannot delete branch '%s' "
258 "checked out at '%s'"),
b489b9d9 259 bname.buf, path);
f292244c
KY
260 ret = 1;
261 continue;
262 }
263 }
264
8bb04553
MH
265 target = resolve_refdup(name,
266 RESOLVE_REF_READING
267 | RESOLVE_REF_NO_RECURSE
268 | RESOLVE_REF_ALLOW_BAD_NAME,
0f2dc722 269 &oid, &flags);
18f29fc6 270 if (!target) {
c179837c 271 error(remote_branch
ccd593cf 272 ? _("remote-tracking branch '%s' not found.")
c179837c 273 : _("branch '%s' not found."), bname.buf);
b8e9a00d
QT
274 ret = 1;
275 continue;
276 }
c31820c2 277
d0f810f0 278 if (!(flags & (REF_ISSYMREF|REF_ISBROKEN)) &&
0c77cd24 279 check_branch_commit(bname.buf, name, &oid, head_rev, kinds,
f5d0e162 280 force)) {
b8e9a00d 281 ret = 1;
8bb04553 282 goto next;
c31820c2
LH
283 }
284
81989077
PH
285 item = string_list_append(&refs_to_delete, name);
286 item->util = xstrdup((flags & REF_ISBROKEN) ? "broken"
287 : (flags & REF_ISSYMREF) ? target
d850b7a5 288 : repo_find_unique_abbrev(the_repository, &oid, DEFAULT_ABBREV));
8bb04553
MH
289
290 next:
291 free(target);
c31820c2 292 }
c31820c2 293
81989077
PH
294 if (delete_refs(NULL, &refs_to_delete, REF_NO_DEREF))
295 ret = 1;
296
297 for_each_string_list_item(item, &refs_to_delete) {
298 char *describe_ref = item->util;
299 char *name = item->string;
300 if (!ref_exists(name)) {
301 char *refname = name + branch_name_pos;
302 if (!quiet)
303 printf(remote_branch
304 ? _("Deleted remote-tracking branch %s (was %s).\n")
305 : _("Deleted branch %s (was %s).\n"),
306 name + branch_name_pos, describe_ref);
307
308 delete_branch_config(refname);
309 }
310 free(describe_ref);
311 }
312 string_list_clear(&refs_to_delete, 0);
313
8e0f7003 314 free(name);
a9155c50 315 strbuf_release(&bname);
b8e9a00d 316
a9155c50 317 return ret;
c31820c2 318}
c31820c2 319
949af068 320static int calc_maxwidth(struct ref_array *refs, int remote_bonus)
94fcb730 321{
949af068
KN
322 int i, max = 0;
323 for (i = 0; i < refs->nr; i++) {
324 struct ref_array_item *it = refs->items[i];
325 const char *desc = it->refname;
326 int w;
dbda21fa 327
949af068
KN
328 skip_prefix(it->refname, "refs/heads/", &desc);
329 skip_prefix(it->refname, "refs/remotes/", &desc);
330 if (it->kind == FILTER_REFS_DETACHED_HEAD) {
331 char *head_desc = get_head_description();
332 w = utf8_strwidth(head_desc);
333 free(head_desc);
334 } else
335 w = utf8_strwidth(desc);
21dfc09d 336
949af068
KN
337 if (it->kind == FILTER_REFS_REMOTES)
338 w += remote_bonus;
339 if (w > max)
340 max = w;
21dfc09d 341 }
949af068 342 return max;
94fcb730
JH
343}
344
949af068 345static const char *quote_literal_for_format(const char *s)
6e0332ec 346{
949af068
KN
347 static struct strbuf buf = STRBUF_INIT;
348
349 strbuf_reset(&buf);
350 while (*s) {
351 const char *ep = strchrnul(s, '%');
352 if (s < ep)
353 strbuf_add(&buf, s, ep - s);
354 if (*ep == '%') {
355 strbuf_addstr(&buf, "%%");
356 s = ep + 1;
357 } else {
358 s = ep;
359 }
6e0332ec 360 }
949af068 361 return buf.buf;
6e0332ec
JN
362}
363
949af068 364static char *build_format(struct ref_filter *filter, int maxwidth, const char *remote_prefix)
75e6e213 365{
949af068
KN
366 struct strbuf fmt = STRBUF_INIT;
367 struct strbuf local = STRBUF_INIT;
368 struct strbuf remote = STRBUF_INIT;
75e6e213 369
ab313814
NB
370 strbuf_addf(&local, "%%(if)%%(HEAD)%%(then)* %s%%(else)%%(if)%%(worktreepath)%%(then)+ %s%%(else) %s%%(end)%%(end)",
371 branch_get_color(BRANCH_COLOR_CURRENT),
372 branch_get_color(BRANCH_COLOR_WORKTREE),
373 branch_get_color(BRANCH_COLOR_LOCAL));
7ca260ab
JK
374 strbuf_addf(&remote, " %s",
375 branch_get_color(BRANCH_COLOR_REMOTE));
75e6e213 376
1511b22d 377 if (filter->verbose) {
ac5bbc02
JH
378 struct strbuf obname = STRBUF_INIT;
379
380 if (filter->abbrev < 0)
381 strbuf_addf(&obname, "%%(objectname:short)");
382 else if (!filter->abbrev)
383 strbuf_addf(&obname, "%%(objectname)");
384 else
385 strbuf_addf(&obname, "%%(objectname:short=%d)", filter->abbrev);
386
949af068 387 strbuf_addf(&local, "%%(align:%d,left)%%(refname:lstrip=2)%%(end)", maxwidth);
72d4a9a7 388 strbuf_addstr(&local, branch_get_color(BRANCH_COLOR_RESET));
ac5bbc02 389 strbuf_addf(&local, " %s ", obname.buf);
949af068
KN
390
391 if (filter->verbose > 1)
6e938146
NB
392 {
393 strbuf_addf(&local, "%%(if:notequals=*)%%(HEAD)%%(then)%%(if)%%(worktreepath)%%(then)(%s%%(worktreepath)%s) %%(end)%%(end)",
394 branch_get_color(BRANCH_COLOR_WORKTREE), branch_get_color(BRANCH_COLOR_RESET));
949af068
KN
395 strbuf_addf(&local, "%%(if)%%(upstream)%%(then)[%s%%(upstream:short)%s%%(if)%%(upstream:track)"
396 "%%(then): %%(upstream:track,nobracket)%%(end)] %%(end)%%(contents:subject)",
397 branch_get_color(BRANCH_COLOR_UPSTREAM), branch_get_color(BRANCH_COLOR_RESET));
6e938146 398 }
949af068
KN
399 else
400 strbuf_addf(&local, "%%(if)%%(upstream:track)%%(then)%%(upstream:track) %%(end)%%(contents:subject)");
401
7ca260ab 402 strbuf_addf(&remote, "%%(align:%d,left)%s%%(refname:lstrip=2)%%(end)%s"
ac5bbc02
JH
403 "%%(if)%%(symref)%%(then) -> %%(symref:short)"
404 "%%(else) %s %%(contents:subject)%%(end)",
7ca260ab 405 maxwidth, quote_literal_for_format(remote_prefix),
ac5bbc02
JH
406 branch_get_color(BRANCH_COLOR_RESET), obname.buf);
407 strbuf_release(&obname);
ebe31ef2 408 } else {
949af068
KN
409 strbuf_addf(&local, "%%(refname:lstrip=2)%s%%(if)%%(symref)%%(then) -> %%(symref:short)%%(end)",
410 branch_get_color(BRANCH_COLOR_RESET));
7ca260ab
JK
411 strbuf_addf(&remote, "%s%%(refname:lstrip=2)%s%%(if)%%(symref)%%(then) -> %%(symref:short)%%(end)",
412 quote_literal_for_format(remote_prefix),
949af068 413 branch_get_color(BRANCH_COLOR_RESET));
ebe31ef2 414 }
75e6e213 415
949af068 416 strbuf_addf(&fmt, "%%(if:notequals=refs/remotes)%%(refname:rstrip=-2)%%(then)%s%%(else)%s%%(end)", local.buf, remote.buf);
aedcb7dc 417
949af068
KN
418 strbuf_release(&local);
419 strbuf_release(&remote);
420 return strbuf_detach(&fmt, NULL);
7e9ff00b
LT
421}
422
d72d4f92
ÆAB
423static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sorting,
424 struct ref_format *format, struct string_list *output)
c31820c2
LH
425{
426 int i;
1511b22d 427 struct ref_array array;
844c3f0b
ZH
428 struct strbuf out = STRBUF_INIT;
429 struct strbuf err = STRBUF_INIT;
1051e40d
KN
430 int maxwidth = 0;
431 const char *remote_prefix = "";
3d9e4ce3 432 char *to_free = NULL;
1051e40d 433
35257aa0 434 /*
1051e40d
KN
435 * If we are listing more than just remote branches,
436 * then remote branches will have a "remotes/" prefix.
437 * We need to account for this in the width.
35257aa0 438 */
1511b22d 439 if (filter->kind != FILTER_REFS_REMOTES)
1051e40d 440 remote_prefix = "remotes/";
8376a704 441
1511b22d 442 memset(&array, 0, sizeof(array));
8376a704 443
1763334c 444 filter_refs(&array, filter, filter->kind);
c31820c2 445
1511b22d
KN
446 if (filter->verbose)
447 maxwidth = calc_maxwidth(&array, strlen(remote_prefix));
bfcc9214 448
4a68e36d
JK
449 if (!format->format)
450 format->format = to_free = build_format(filter, maxwidth, remote_prefix);
11b087ad 451 format->use_color = branch_use_color;
2eda0102
JK
452
453 if (verify_ref_format(format))
454 die(_("unable to parse format string"));
949af068 455
aedcb7dc 456 ref_array_sort(sorting, &array);
1603ade8 457
949af068 458 for (i = 0; i < array.nr; i++) {
844c3f0b
ZH
459 strbuf_reset(&err);
460 strbuf_reset(&out);
3019eca9
OT
461 if (format_ref_array_item(array.items[i], format, &out, &err))
462 die("%s", err.buf);
949af068
KN
463 if (column_active(colopts)) {
464 assert(!filter->verbose && "--column and --verbose are incompatible");
465 /* format to a string_list to let print_columns() do its job */
d72d4f92 466 string_list_append(output, out.buf);
949af068
KN
467 } else {
468 fwrite(out.buf, 1, out.len, stdout);
469 putchar('\n');
470 }
949af068 471 }
0e9716e6 472
844c3f0b
ZH
473 strbuf_release(&err);
474 strbuf_release(&out);
1511b22d 475 ref_array_clear(&array);
3d9e4ce3 476 free(to_free);
c31820c2
LH
477}
478
0ecb1fc7
DU
479static void print_current_branch_name(void)
480{
481 int flags;
482 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
483 const char *shortname;
484 if (!refname)
485 die(_("could not resolve HEAD"));
486 else if (!(flags & REF_ISSYMREF))
487 return;
488 else if (skip_prefix(refname, "refs/heads/", &shortname))
489 puts(shortname);
490 else
491 die(_("HEAD (%s) points outside of refs/heads/"), refname);
492}
493
14ace5b7
NTND
494static void reject_rebase_or_bisect_branch(const char *target)
495{
03f2465b 496 struct worktree **worktrees = get_worktrees();
14ace5b7
NTND
497 int i;
498
499 for (i = 0; worktrees[i]; i++) {
500 struct worktree *wt = worktrees[i];
501
502 if (!wt->is_detached)
503 continue;
504
505 if (is_worktree_being_rebased(wt, target))
506 die(_("Branch %s is being rebased at %s"),
507 target, wt->path);
508
509 if (is_worktree_being_bisected(wt, target))
510 die(_("Branch %s is being bisected at %s"),
511 target, wt->path);
512 }
513
514 free_worktrees(worktrees);
515}
516
52d59cc6 517static void copy_or_rename_branch(const char *oldname, const char *newname, int copy, int force)
c976d415 518{
da3f78a2 519 struct strbuf oldref = STRBUF_INIT, newref = STRBUF_INIT, logmsg = STRBUF_INIT;
da3f78a2 520 struct strbuf oldsection = STRBUF_INIT, newsection = STRBUF_INIT;
255073ca
KS
521 const char *interpreted_oldname = NULL;
522 const char *interpreted_newname = NULL;
cbdffe40 523 int recovery = 0;
c976d415 524
cbdffe40
JH
525 if (strbuf_check_branch_ref(&oldref, oldname)) {
526 /*
527 * Bad name --- this could be an attempt to rename a
528 * ref that we used to allow to be created by accident.
529 */
c6893323 530 if (ref_exists(oldref.buf))
cbdffe40
JH
531 recovery = 1;
532 else
49df4b02 533 die(_("Invalid branch name: '%s'"), oldname);
cbdffe40 534 }
c976d415 535
bcfc82bd
RJ
536 if ((copy || strcmp(head, oldname)) && !ref_exists(oldref.buf)) {
537 if (copy && !strcmp(head, oldname))
538 die(_("No commit on branch '%s' yet."), oldname);
539 else
540 die(_("No branch named '%s'."), oldname);
541 }
542
3f59481e
JN
543 /*
544 * A command like "git branch -M currentbranch currentbranch" cannot
545 * cause the worktree to become inconsistent with HEAD, so allow it.
546 */
bc1c9c0e
JH
547 if (!strcmp(oldname, newname))
548 validate_branchname(newname, &newref);
549 else
550 validate_new_branchname(newname, &newref, force);
c976d415 551
14ace5b7
NTND
552 reject_rebase_or_bisect_branch(oldref.buf);
553
255073ca
KS
554 if (!skip_prefix(oldref.buf, "refs/heads/", &interpreted_oldname) ||
555 !skip_prefix(newref.buf, "refs/heads/", &interpreted_newname)) {
033abf97 556 BUG("expected prefix missing for refs");
255073ca
KS
557 }
558
52d59cc6
SD
559 if (copy)
560 strbuf_addf(&logmsg, "Branch: copied %s to %s",
561 oldref.buf, newref.buf);
562 else
563 strbuf_addf(&logmsg, "Branch: renamed %s to %s",
564 oldref.buf, newref.buf);
678d0f4c 565
cfaff3aa
JS
566 if (!copy &&
567 (!head || strcmp(oldname, head) || !is_null_oid(&head_oid)) &&
568 rename_ref(oldref.buf, newref.buf, logmsg.buf))
49df4b02 569 die(_("Branch rename failed"));
52d59cc6
SD
570 if (copy && copy_existing_ref(oldref.buf, newref.buf, logmsg.buf))
571 die(_("Branch copy failed"));
c976d415 572
52d59cc6
SD
573 if (recovery) {
574 if (copy)
a48ebe97 575 warning(_("Created a copy of a misnamed branch '%s'"),
255073ca 576 interpreted_oldname);
52d59cc6
SD
577 else
578 warning(_("Renamed a misnamed branch '%s' away"),
255073ca 579 interpreted_oldname);
52d59cc6 580 }
cbdffe40 581
e5435ff1
JH
582 if (!copy &&
583 replace_each_worktree_head_symref(oldref.buf, newref.buf, logmsg.buf))
49df4b02 584 die(_("Branch renamed to %s, but HEAD is not updated!"), newname);
19eba151 585
39ee4c6c
KM
586 strbuf_release(&logmsg);
587
255073ca 588 strbuf_addf(&oldsection, "branch.%s", interpreted_oldname);
255073ca 589 strbuf_addf(&newsection, "branch.%s", interpreted_newname);
52d59cc6 590 if (!copy && git_config_rename_section(oldsection.buf, newsection.buf) < 0)
49df4b02 591 die(_("Branch is renamed, but update of config-file failed"));
cfbd173c 592 if (copy && strcmp(interpreted_oldname, interpreted_newname) && git_config_copy_section(oldsection.buf, newsection.buf) < 0)
52d59cc6 593 die(_("Branch is copied, but update of config-file failed"));
cfbd173c
RJ
594 strbuf_release(&oldref);
595 strbuf_release(&newref);
da3f78a2
MV
596 strbuf_release(&oldsection);
597 strbuf_release(&newsection);
c976d415
LH
598}
599
c10388c7 600static GIT_PATH_FUNC(edit_description, "EDIT_DESCRIPTION")
b7200e83
JH
601
602static int edit_branch_description(const char *branch_name)
603{
e288b3de 604 int exists;
b7200e83
JH
605 struct strbuf buf = STRBUF_INIT;
606 struct strbuf name = STRBUF_INIT;
607
e288b3de 608 exists = !read_branch_desc(&buf, branch_name);
b7200e83
JH
609 if (!buf.len || buf.buf[buf.len-1] != '\n')
610 strbuf_addch(&buf, '\n');
eff80a9f 611 strbuf_commented_addf(&buf,
b18237f4
VA
612 _("Please edit the description for the branch\n"
613 " %s\n"
614 "Lines starting with '%c' will be stripped.\n"),
eff80a9f 615 branch_name, comment_line_char);
c10388c7 616 write_file_buf(edit_description(), buf.buf, buf.len);
b7200e83 617 strbuf_reset(&buf);
c10388c7 618 if (launch_editor(edit_description(), &buf, NULL)) {
b7200e83
JH
619 strbuf_release(&buf);
620 return -1;
621 }
63af4a84 622 strbuf_stripspace(&buf, 1);
b7200e83
JH
623
624 strbuf_addf(&name, "branch.%s.description", branch_name);
e288b3de
JH
625 if (buf.len || exists)
626 git_config_set(name.buf, buf.len ? buf.buf : NULL);
b7200e83
JH
627 strbuf_release(&name);
628 strbuf_release(&buf);
629
bd25f890 630 return 0;
b7200e83
JH
631}
632
c31820c2
LH
633int cmd_branch(int argc, const char **argv, const char *prefix)
634{
6e0a2ca0
GC
635 /* possible actions */
636 int delete = 0, rename = 0, copy = 0, list = 0,
637 unset_upstream = 0, show_current = 0, edit_description = 0;
6183d826 638 const char *new_upstream = NULL;
6e0a2ca0
GC
639 int noncreate_actions = 0;
640 /* possible options */
961b130d
GC
641 int reflog = 0, quiet = 0, icase = 0, force = 0,
642 recurse_submodules_explicit = 0;
9ed36cfa 643 enum branch_track track;
1511b22d 644 struct ref_filter filter;
98e7ab6d
JH
645 static struct ref_sorting *sorting;
646 struct string_list sorting_options = STRING_LIST_INIT_DUP;
4a68e36d 647 struct ref_format format = REF_FORMAT_INIT;
a8dfd5ea
PH
648
649 struct option options[] = {
24a85214 650 OPT_GROUP(N_("Generic options")),
1511b22d 651 OPT__VERBOSE(&filter.verbose,
24a85214
NTND
652 N_("show hash and subject, give twice for upstream branch")),
653 OPT__QUIET(&quiet, N_("suppress informational messages")),
6327f0ef 654 OPT_CALLBACK_F('t', "track", &track, "(direct|inherit)",
d3115660 655 N_("set branch tracking configuration"),
15f00281 656 PARSE_OPT_OPTARG,
d3115660 657 parse_opt_tracking_mode),
3e4a67b4
NTND
658 OPT_SET_INT_F(0, "set-upstream", &track, N_("do not use"),
659 BRANCH_TRACK_OVERRIDE, PARSE_OPT_HIDDEN),
ab86885a 660 OPT_STRING('u', "set-upstream-to", &new_upstream, N_("upstream"), N_("change the upstream info")),
11de8dd7 661 OPT_BOOL(0, "unset-upstream", &unset_upstream, N_("unset the upstream info")),
24a85214 662 OPT__COLOR(&branch_use_color, N_("use colored output")),
1511b22d
KN
663 OPT_SET_INT('r', "remotes", &filter.kind, N_("act on remote-tracking branches"),
664 FILTER_REFS_REMOTES),
665 OPT_CONTAINS(&filter.with_commit, N_("print only branches that contain the commit")),
ac3f5a34 666 OPT_NO_CONTAINS(&filter.no_commit, N_("print only branches that don't contain the commit")),
1511b22d 667 OPT_WITH(&filter.with_commit, N_("print only branches that contain the commit")),
ac3f5a34 668 OPT_WITHOUT(&filter.no_commit, N_("print only branches that don't contain the commit")),
1511b22d 669 OPT__ABBREV(&filter.abbrev),
a8dfd5ea 670
24a85214 671 OPT_GROUP(N_("Specific git-branch actions:")),
1511b22d
KN
672 OPT_SET_INT('a', "all", &filter.kind, N_("list both remote-tracking and local branches"),
673 FILTER_REFS_REMOTES | FILTER_REFS_BRANCHES),
24a85214
NTND
674 OPT_BIT('d', "delete", &delete, N_("delete fully merged branch"), 1),
675 OPT_BIT('D', NULL, &delete, N_("delete branch (even if not merged)"), 2),
676 OPT_BIT('m', "move", &rename, N_("move/rename a branch and its reflog"), 1),
677 OPT_BIT('M', NULL, &rename, N_("move/rename a branch, even if target exists"), 2),
52d59cc6
SD
678 OPT_BIT('c', "copy", &copy, N_("copy a branch and its reflog"), 1),
679 OPT_BIT('C', NULL, &copy, N_("copy a branch, even if target exists"), 2),
a15d5981 680 OPT_BOOL('l', "list", &list, N_("list branch names")),
0ecb1fc7 681 OPT_BOOL(0, "show-current", &show_current, N_("show current branch name")),
055930bc 682 OPT_BOOL(0, "create-reflog", &reflog, N_("create the branch's reflog")),
d5d09d47
SB
683 OPT_BOOL(0, "edit-description", &edit_description,
684 N_("edit the description for the branch")),
c01b56a3 685 OPT__FORCE(&force, N_("force creation, move/rename, deletion"), PARSE_OPT_NOCOMPLETE),
1511b22d
KN
686 OPT_MERGED(&filter, N_("print only branches that are merged")),
687 OPT_NO_MERGED(&filter, N_("print only branches that are not merged")),
24a85214 688 OPT_COLUMN(0, "column", &colopts, N_("list branches in columns")),
98e7ab6d 689 OPT_REF_SORT(&sorting_options),
203c8533
DL
690 OPT_CALLBACK(0, "points-at", &filter.points_at, N_("object"),
691 N_("print only branches of the object"), parse_opt_object_name),
3bb16a8b 692 OPT_BOOL('i', "ignore-case", &icase, N_("sorting and filtering are case insensitive")),
961b130d 693 OPT_BOOL(0, "recurse-submodules", &recurse_submodules_explicit, N_("recurse through submodules")),
4a68e36d 694 OPT_STRING( 0 , "format", &format.format, N_("format"), N_("format to use for the output")),
a8dfd5ea
PH
695 OPT_END(),
696 };
c31820c2 697
56b43607
KN
698 setup_ref_filter_porcelain_msg();
699
1511b22d
KN
700 memset(&filter, 0, sizeof(filter));
701 filter.kind = FILTER_REFS_BRANCHES;
702 filter.abbrev = -1;
703
1dacfbcf
NTND
704 if (argc == 2 && !strcmp(argv[1], "-h"))
705 usage_with_options(builtin_branch_usage, options);
706
98e7ab6d 707 git_config(git_branch_config, &sorting_options);
6b2f2d98 708
9ed36cfa 709 track = git_branch_track;
c976d415 710
0f2dc722 711 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
c31820c2 712 if (!head)
49df4b02 713 die(_("Failed to resolve HEAD as a valid ref."));
e3f1da98 714 if (!strcmp(head, "HEAD"))
1511b22d 715 filter.detached = 1;
e3f1da98
RS
716 else if (!skip_prefix(head, "refs/heads/", &head))
717 die(_("HEAD not found below refs/heads!"));
ebe31ef2 718
37782920
SB
719 argc = parse_options(argc, argv, prefix, options, builtin_branch_usage,
720 0);
cddd127b 721
0ecb1fc7
DU
722 if (!delete && !rename && !copy && !edit_description && !new_upstream &&
723 !show_current && !unset_upstream && argc == 0)
cddd127b
MG
724 list = 1;
725
21bf9339
AL
726 if (filter.with_commit || filter.no_commit ||
727 filter.reachable_from || filter.unreachable_from || filter.points_at.nr)
d0403508
JK
728 list = 1;
729
6e0a2ca0
GC
730 noncreate_actions = !!delete + !!rename + !!copy + !!new_upstream +
731 !!show_current + !!list + !!edit_description +
732 !!unset_upstream;
733 if (noncreate_actions > 1)
049716b3 734 usage_with_options(builtin_branch_usage, options);
c31820c2 735
961b130d
GC
736 if (recurse_submodules_explicit) {
737 if (!submodule_propagate_branches)
738 die(_("branch with --recurse-submodules can only be used if submodule.propagateBranches is enabled"));
739 if (noncreate_actions)
740 die(_("--recurse-submodules can only be used to create branches"));
741 }
742
743 recurse_submodules =
744 (recurse_submodules || recurse_submodules_explicit) &&
745 submodule_propagate_branches;
746
1511b22d
KN
747 if (filter.abbrev == -1)
748 filter.abbrev = DEFAULT_ABBREV;
3bb16a8b
NTND
749 filter.ignore_case = icase;
750
ebe31ef2 751 finalize_colopts(&colopts, -1);
1511b22d 752 if (filter.verbose) {
ebe31ef2 753 if (explicitly_enable_column(colopts))
12909b6b 754 die(_("options '%s' and '%s' cannot be used together"), "--column", "--verbose");
ebe31ef2
NTND
755 colopts = 0;
756 }
b792c067 757
356e91f2
MG
758 if (force) {
759 delete *= 2;
760 rename *= 2;
52d59cc6 761 copy *= 2;
356e91f2
MG
762 }
763
d74b541e 764 if (list)
0ae19de7 765 setup_auto_pager("branch", 1);
d74b541e 766
640d0401
NTND
767 if (delete) {
768 if (!argc)
769 die(_("branch name required"));
1511b22d 770 return delete_branches(argc, argv, delete > 1, filter.kind, quiet);
0ecb1fc7
DU
771 } else if (show_current) {
772 print_current_branch_name();
773 return 0;
640d0401 774 } else if (list) {
ffdd02a5 775 /* git branch --list also shows HEAD when it is detached */
1511b22d
KN
776 if ((filter.kind & FILTER_REFS_BRANCHES) && filter.detached)
777 filter.kind |= FILTER_REFS_DETACHED_HEAD;
778 filter.name_patterns = argv;
3bb16a8b
NTND
779 /*
780 * If no sorting parameter is given then we default to sorting
781 * by 'refname'. This would give us an alphabetically sorted
782 * array with the 'HEAD' ref at the beginning followed by
30aa96cd 783 * local branches 'refs/heads/...' and finally remote-tracking
3bb16a8b
NTND
784 * branches 'refs/remotes/...'.
785 */
98e7ab6d 786 sorting = ref_sorting_options(&sorting_options);
7c269a7b 787 ref_sorting_set_sort_flags_all(sorting, REF_SORTING_ICASE, icase);
2708ce62
ÆAB
788 ref_sorting_set_sort_flags_all(
789 sorting, REF_SORTING_DETACHED_HEAD_FIRST, 1);
d72d4f92 790 print_ref_list(&filter, sorting, &format, &output);
ebe31ef2
NTND
791 print_columns(&output, colopts, NULL);
792 string_list_clear(&output, 0);
d72d4f92 793 ref_sorting_release(sorting);
ca417990 794 return 0;
2e3c894f 795 } else if (edit_description) {
b7200e83 796 const char *branch_name;
c2d17ba3 797 struct strbuf branch_ref = STRBUF_INIT;
0dc4e5c5
RJ
798 struct strbuf buf = STRBUF_INIT;
799 int ret = 1; /* assume failure */
c2d17ba3 800
75135b23 801 if (!argc) {
1511b22d 802 if (filter.detached)
045e3884 803 die(_("Cannot give description to detached HEAD"));
b7200e83 804 branch_name = head;
0dc4e5c5
RJ
805 } else if (argc == 1) {
806 strbuf_branchname(&buf, argv[0], INTERPRET_BRANCH_LOCAL);
807 branch_name = buf.buf;
808 } else {
43722c4d 809 die(_("cannot edit description of more than one branch"));
0dc4e5c5 810 }
c2d17ba3
JH
811
812 strbuf_addf(&branch_ref, "refs/heads/%s", branch_name);
0dc4e5c5 813 if (!ref_exists(branch_ref.buf))
8f241151 814 error((!argc || !strcmp(head, branch_name))
0dc4e5c5
RJ
815 ? _("No commit on branch '%s' yet.")
816 : _("No branch named '%s'."),
817 branch_name);
818 else if (!edit_branch_description(branch_name))
819 ret = 0; /* happy */
820
c2d17ba3 821 strbuf_release(&branch_ref);
0dc4e5c5 822 strbuf_release(&buf);
c2d17ba3 823
0dc4e5c5 824 return ret;
77e7267e 825 } else if (copy || rename) {
d1520c4b
JM
826 if (!argc)
827 die(_("branch name required"));
77e7267e
RJ
828 else if ((argc == 1) && filter.detached)
829 die(copy? _("cannot copy the current branch while not on any.")
830 : _("cannot rename the current branch while not on any."));
d1520c4b 831 else if (argc == 1)
77e7267e 832 copy_or_rename_branch(head, argv[0], copy, copy + rename > 1);
3706ed29 833 else if (argc == 2)
77e7267e 834 copy_or_rename_branch(argv[0], argv[1], copy, copy + rename > 1);
3706ed29 835 else
77e7267e
RJ
836 die(copy? _("too many branches for a copy operation")
837 : _("too many arguments for a rename operation"));
6183d826 838 } else if (new_upstream) {
0dc4e5c5
RJ
839 struct branch *branch;
840 struct strbuf buf = STRBUF_INIT;
6183d826 841
0dc4e5c5
RJ
842 if (!argc)
843 branch = branch_get(NULL);
844 else if (argc == 1) {
845 strbuf_branchname(&buf, argv[0], INTERPRET_BRANCH_LOCAL);
846 branch = branch_get(buf.buf);
847 } else
f7776235 848 die(_("too many arguments to set new upstream"));
8efb8899
NTND
849
850 if (!branch) {
851 if (!argc || !strcmp(argv[0], "HEAD"))
852 die(_("could not set upstream of HEAD to %s when "
853 "it does not point to any branch."),
854 new_upstream);
855 die(_("no such branch '%s'"), argv[0]);
856 }
857
bcfc82bd
RJ
858 if (!ref_exists(branch->refname)) {
859 if (!argc || !strcmp(head, branch->name))
860 die(_("No commit on branch '%s' yet."), branch->name);
6183d826 861 die(_("branch '%s' does not exist"), branch->name);
bcfc82bd 862 }
6183d826 863
e89f151d
GC
864 dwim_and_setup_tracking(the_repository, branch->name,
865 new_upstream, BRANCH_TRACK_OVERRIDE,
866 quiet);
0dc4e5c5 867 strbuf_release(&buf);
b84869ef 868 } else if (unset_upstream) {
0dc4e5c5 869 struct branch *branch;
b84869ef
CMN
870 struct strbuf buf = STRBUF_INIT;
871
0dc4e5c5
RJ
872 if (!argc)
873 branch = branch_get(NULL);
874 else if (argc == 1) {
875 strbuf_branchname(&buf, argv[0], INTERPRET_BRANCH_LOCAL);
876 branch = branch_get(buf.buf);
877 } else
f7776235 878 die(_("too many arguments to unset upstream"));
8efb8899
NTND
879
880 if (!branch) {
881 if (!argc || !strcmp(argv[0], "HEAD"))
882 die(_("could not unset upstream of HEAD when "
883 "it does not point to any branch."));
884 die(_("no such branch '%s'"), argv[0]);
885 }
886
54d07f2e 887 if (!branch_has_merge_config(branch))
b84869ef 888 die(_("Branch '%s' has no upstream information"), branch->name);
b84869ef 889
0dc4e5c5 890 strbuf_reset(&buf);
b84869ef 891 strbuf_addf(&buf, "branch.%s.remote", branch->name);
504ee129 892 git_config_set_multivar(buf.buf, NULL, NULL, CONFIG_FLAGS_MULTI_REPLACE);
b84869ef
CMN
893 strbuf_reset(&buf);
894 strbuf_addf(&buf, "branch.%s.merge", branch->name);
504ee129 895 git_config_set_multivar(buf.buf, NULL, NULL, CONFIG_FLAGS_MULTI_REPLACE);
b84869ef 896 strbuf_release(&buf);
6e0a2ca0 897 } else if (!noncreate_actions && argc > 0 && argc <= 2) {
961b130d
GC
898 const char *branch_name = argv[0];
899 const char *start_name = argc == 2 ? argv[1] : head;
900
1511b22d 901 if (filter.kind != FILTER_REFS_BRANCHES)
1fde99cf
PO
902 die(_("The -a, and -r, options to 'git branch' do not take a branch name.\n"
903 "Did you mean to use: -a|-r --list <pattern>?"));
b347d06b
CMN
904
905 if (track == BRANCH_TRACK_OVERRIDE)
52668846 906 die(_("the '--set-upstream' option is no longer supported. Please use '--track' or '--set-upstream-to' instead."));
b347d06b 907
961b130d
GC
908 if (recurse_submodules) {
909 create_branches_recursively(the_repository, branch_name,
910 start_name, NULL, force,
911 reflog, quiet, track, 0);
912 return 0;
913 }
914 create_branch(the_repository, branch_name, start_name, force, 0,
915 reflog, quiet, track, 0);
6e8f993a 916 } else
a8dfd5ea 917 usage_with_options(builtin_branch_usage, options);
c31820c2
LH
918
919 return 0;
920}