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