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