]> git.ipfire.org Git - thirdparty/git.git/blame - branch.c
The eighth batch
[thirdparty/git.git] / branch.c
CommitLineData
e7da9385
PS
1#define USE_THE_REPOSITORY_VARIABLE
2
303d1d0b 3#include "git-compat-util.h"
6c6ddf92 4#include "advice.h"
b2141fc1 5#include "config.h"
e496c003 6#include "branch.h"
32a8f510 7#include "environment.h"
f394e093 8#include "gettext.h"
41771fa4 9#include "hex.h"
dabab1d6 10#include "object-name.h"
c339932b 11#include "path.h"
e496c003 12#include "refs.h"
ec0cb496 13#include "refspec.h"
e496c003 14#include "remote.h"
d1cbe1e6 15#include "repository.h"
b07d9bfd 16#include "sequencer.h"
e496c003 17#include "commit.h"
ac6c561b 18#include "worktree.h"
961b130d
GC
19#include "submodule-config.h"
20#include "run-command.h"
31ad6b61 21#include "strmap.h"
e496c003
DB
22
23struct tracking {
0ad4a5ff 24 struct refspec_item spec;
d3115660 25 struct string_list *srcs;
e496c003
DB
26 const char *remote;
27 int matches;
28};
29
e4921d87
TK
30struct find_tracked_branch_cb {
31 struct tracking *tracking;
32 struct string_list ambiguous_remotes;
33};
34
e496c003
DB
35static int find_tracked_branch(struct remote *remote, void *priv)
36{
e4921d87
TK
37 struct find_tracked_branch_cb *ftb = priv;
38 struct tracking *tracking = ftb->tracking;
e496c003
DB
39
40 if (!remote_find_tracking(remote, &tracking->spec)) {
e4921d87
TK
41 switch (++tracking->matches) {
42 case 1:
861c56f6 43 string_list_append_nodup(tracking->srcs, tracking->spec.src);
e496c003 44 tracking->remote = remote->name;
e4921d87
TK
45 break;
46 case 2:
47 /* there are at least two remotes; backfill the first one */
48 string_list_append(&ftb->ambiguous_remotes, tracking->remote);
49 /* fall through */
50 default:
51 string_list_append(&ftb->ambiguous_remotes, remote->name);
e496c003 52 free(tracking->spec.src);
d3115660 53 string_list_clear(tracking->srcs, 0);
e4921d87 54 break;
e496c003 55 }
bdaf1dfa 56 /* remote_find_tracking() searches by src if present */
e496c003
DB
57 tracking->spec.src = NULL;
58 }
e496c003
DB
59 return 0;
60}
61
a9f2c136 62static int should_setup_rebase(const char *origin)
c998ae9b
DS
63{
64 switch (autorebase) {
65 case AUTOREBASE_NEVER:
66 return 0;
67 case AUTOREBASE_LOCAL:
a9f2c136 68 return origin == NULL;
c998ae9b 69 case AUTOREBASE_REMOTE:
a9f2c136 70 return origin != NULL;
c998ae9b
DS
71 case AUTOREBASE_ALWAYS:
72 return 1;
73 }
74 return 0;
75}
76
a3f40ec4
JS
77/**
78 * Install upstream tracking configuration for a branch; specifically, add
79 * `branch.<name>.remote` and `branch.<name>.merge` entries.
80 *
81 * `flag` contains integer flags for options; currently only
82 * BRANCH_CONFIG_VERBOSE is checked.
83 *
84 * `local` is the name of the branch whose configuration we're installing.
85 *
86 * `origin` is the name of the remote owning the upstream branches. NULL means
87 * the upstream branches are local to this repo.
88 *
89 * `remotes` is a list of refs that are upstream of local
90 */
91static int install_branch_config_multiple_remotes(int flag, const char *local,
92 const char *origin, struct string_list *remotes)
a9f2c136 93{
cf4fff57 94 const char *shortname = NULL;
a9f2c136 95 struct strbuf key = STRBUF_INIT;
a3f40ec4 96 struct string_list_item *item;
a9f2c136
JH
97 int rebasing = should_setup_rebase(origin);
98
a3f40ec4
JS
99 if (!remotes->nr)
100 BUG("must provide at least one remote for branch config");
101 if (rebasing && remotes->nr > 1)
102 die(_("cannot inherit upstream tracking configuration of "
103 "multiple refs when rebasing is requested"));
104
105 /*
106 * If the new branch is trying to track itself, something has gone
107 * wrong. Warn the user and don't proceed any further.
108 */
109 if (!origin)
110 for_each_string_list_item(item, remotes)
111 if (skip_prefix(item->string, "refs/heads/", &shortname)
112 && !strcmp(local, shortname)) {
0669bdf4 113 warning(_("not setting branch '%s' as its own upstream"),
a3f40ec4
JS
114 local);
115 return 0;
116 }
85e2233f 117
a9f2c136 118 strbuf_addf(&key, "branch.%s.remote", local);
30598ad0 119 if (git_config_set_gently(key.buf, origin ? origin : ".") < 0)
27852b2c 120 goto out_err;
a9f2c136
JH
121
122 strbuf_reset(&key);
123 strbuf_addf(&key, "branch.%s.merge", local);
a3f40ec4
JS
124 /*
125 * We want to overwrite any existing config with all the branches in
126 * "remotes". Override any existing config, then write our branches. If
127 * more than one is provided, use CONFIG_REGEX_NONE to preserve what
128 * we've written so far.
129 */
130 if (git_config_set_gently(key.buf, NULL) < 0)
27852b2c 131 goto out_err;
a3f40ec4
JS
132 for_each_string_list_item(item, remotes)
133 if (git_config_set_multivar_gently(key.buf, item->string, CONFIG_REGEX_NONE, 0) < 0)
134 goto out_err;
a9f2c136
JH
135
136 if (rebasing) {
137 strbuf_reset(&key);
138 strbuf_addf(&key, "branch.%s.rebase", local);
30598ad0 139 if (git_config_set_gently(key.buf, "true") < 0)
27852b2c 140 goto out_err;
a9f2c136 141 }
d53a3503 142 strbuf_release(&key);
a9f2c136 143
72f60083 144 if (flag & BRANCH_CONFIG_VERBOSE) {
a3f40ec4
JS
145 struct strbuf tmp_ref_name = STRBUF_INIT;
146 struct string_list friendly_ref_names = STRING_LIST_INIT_DUP;
147
148 for_each_string_list_item(item, remotes) {
149 shortname = item->string;
150 skip_prefix(shortname, "refs/heads/", &shortname);
151 if (origin) {
152 strbuf_addf(&tmp_ref_name, "%s/%s",
153 origin, shortname);
154 string_list_append_nodup(
155 &friendly_ref_names,
156 strbuf_detach(&tmp_ref_name, NULL));
157 } else {
158 string_list_append(
159 &friendly_ref_names, shortname);
160 }
161 }
162
163 if (remotes->nr == 1) {
164 /*
165 * Rebasing is only allowed in the case of a single
166 * upstream branch.
167 */
168 printf_ln(rebasing ?
169 _("branch '%s' set up to track '%s' by rebasing.") :
170 _("branch '%s' set up to track '%s'."),
171 local, friendly_ref_names.items[0].string);
9fe0cf3a 172 } else {
a3f40ec4
JS
173 printf_ln(_("branch '%s' set up to track:"), local);
174 for_each_string_list_item(item, &friendly_ref_names)
175 printf_ln(" %s", item->string);
9fe0cf3a 176 }
a3f40ec4
JS
177
178 string_list_clear(&friendly_ref_names, 0);
72f60083 179 }
27852b2c
PS
180
181 return 0;
182
183out_err:
184 strbuf_release(&key);
7435e7e2 185 error(_("unable to write upstream branch configuration"));
27852b2c 186
a3f40ec4
JS
187 advise(_("\nAfter fixing the error cause you may try to fix up\n"
188 "the remote tracking information by invoking:"));
189 if (remotes->nr == 1)
190 advise(" git branch --set-upstream-to=%s%s%s",
191 origin ? origin : "",
192 origin ? "/" : "",
193 remotes->items[0].string);
194 else {
195 advise(" git config --add branch.\"%s\".remote %s",
196 local, origin ? origin : ".");
197 for_each_string_list_item(item, remotes)
198 advise(" git config --add branch.\"%s\".merge %s",
199 local, item->string);
200 }
27852b2c
PS
201
202 return -1;
a9f2c136
JH
203}
204
a3f40ec4
JS
205int install_branch_config(int flag, const char *local, const char *origin,
206 const char *remote)
207{
208 int ret;
209 struct string_list remotes = STRING_LIST_INIT_DUP;
210
211 string_list_append(&remotes, remote);
212 ret = install_branch_config_multiple_remotes(flag, local, origin, &remotes);
213 string_list_clear(&remotes, 0);
214 return ret;
215}
216
d3115660
JS
217static int inherit_tracking(struct tracking *tracking, const char *orig_ref)
218{
219 const char *bare_ref;
220 struct branch *branch;
221 int i;
222
223 bare_ref = orig_ref;
224 skip_prefix(orig_ref, "refs/heads/", &bare_ref);
225
226 branch = branch_get(bare_ref);
227 if (!branch->remote_name) {
228 warning(_("asked to inherit tracking from '%s', but no remote is set"),
229 bare_ref);
230 return -1;
231 }
232
f62dcc7f 233 if (branch->merge_nr < 1 || !branch->merge || !branch->merge[0] || !branch->merge[0]->src) {
d3115660
JS
234 warning(_("asked to inherit tracking from '%s', but no merge configuration is set"),
235 bare_ref);
236 return -1;
237 }
238
a88a3d7c 239 tracking->remote = branch->remote_name;
d3115660 240 for (i = 0; i < branch->merge_nr; i++)
f62dcc7f 241 string_list_append(tracking->srcs, branch->merge[i]->src);
d3115660
JS
242 return 0;
243}
244
e496c003 245/*
e89f151d
GC
246 * Used internally to set the branch.<new_ref>.{remote,merge} config
247 * settings so that branch 'new_ref' tracks 'orig_ref'. Unlike
248 * dwim_and_setup_tracking(), this does not do DWIM, i.e. "origin/main"
249 * will not be expanded to "refs/remotes/origin/main", so it is not safe
250 * for 'orig_ref' to be raw user input.
e496c003 251 */
27852b2c
PS
252static void setup_tracking(const char *new_ref, const char *orig_ref,
253 enum branch_track track, int quiet)
e496c003 254{
e496c003 255 struct tracking tracking;
d3115660 256 struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
f9a482e6 257 int config_flags = quiet ? 0 : BRANCH_CONFIG_VERBOSE;
e4921d87
TK
258 struct find_tracked_branch_cb ftb_cb = {
259 .tracking = &tracking,
260 .ambiguous_remotes = STRING_LIST_INIT_DUP,
261 };
e496c003 262
75388bf5
GC
263 if (!track)
264 BUG("asked to set up tracking, but tracking is disallowed");
265
e496c003
DB
266 memset(&tracking, 0, sizeof(tracking));
267 tracking.spec.dst = (char *)orig_ref;
d3115660
JS
268 tracking.srcs = &tracking_srcs;
269 if (track != BRANCH_TRACK_INHERIT)
e4921d87 270 for_each_remote(find_tracked_branch, &ftb_cb);
d3115660 271 else if (inherit_tracking(&tracking, orig_ref))
679e3693 272 goto cleanup;
e496c003 273
9ed36cfa
JS
274 if (!tracking.matches)
275 switch (track) {
bdaf1dfa 276 /* If ref is not remote, still use local */
9ed36cfa
JS
277 case BRANCH_TRACK_ALWAYS:
278 case BRANCH_TRACK_EXPLICIT:
4fc50066 279 case BRANCH_TRACK_OVERRIDE:
bdaf1dfa 280 /* Remote matches not evaluated */
d3115660 281 case BRANCH_TRACK_INHERIT:
9ed36cfa 282 break;
bdaf1dfa 283 /* Otherwise, if no remote don't track */
9ed36cfa 284 default:
679e3693 285 goto cleanup;
9ed36cfa
JS
286 }
287
bdaf1dfa
TK
288 /*
289 * This check does not apply to BRANCH_TRACK_INHERIT;
290 * that supports multiple entries in tracking_srcs but
291 * leaves tracking.matches at 0.
292 */
e4921d87
TK
293 if (tracking.matches > 1) {
294 int status = die_message(_("not tracking: ambiguous information for ref '%s'"),
295 orig_ref);
296 if (advice_enabled(ADVICE_AMBIGUOUS_FETCH_REFSPEC)) {
297 struct strbuf remotes_advice = STRBUF_INIT;
298 struct string_list_item *item;
299
300 for_each_string_list_item(item, &ftb_cb.ambiguous_remotes)
301 /*
302 * TRANSLATORS: This is a line listing a remote with duplicate
303 * refspecs in the advice message below. For RTL languages you'll
304 * probably want to swap the "%s" and leading " " space around.
305 */
306 strbuf_addf(&remotes_advice, _(" %s\n"), item->string);
307
308 /*
309 * TRANSLATORS: The second argument is a \n-delimited list of
310 * duplicate refspecs, composed above.
311 */
312 advise(_("There are multiple remotes whose fetch refspecs map to the remote\n"
313 "tracking ref '%s':\n"
314 "%s"
315 "\n"
316 "This is typically a configuration error.\n"
317 "\n"
318 "To support setting up tracking branches, ensure that\n"
319 "different remotes' fetch refspecs map into different\n"
320 "tracking namespaces."), orig_ref,
321 remotes_advice.buf);
322 strbuf_release(&remotes_advice);
323 }
324 exit(status);
325 }
e496c003 326
bdaf1dfa
TK
327 if (track == BRANCH_TRACK_SIMPLE) {
328 /*
329 * Only track if remote branch name matches.
330 * Reaching into items[0].string is safe because
331 * we know there is at least one and not more than
332 * one entry (because only BRANCH_TRACK_INHERIT can
333 * produce more than one entry).
334 */
335 const char *tracked_branch;
336 if (!skip_prefix(tracking.srcs->items[0].string,
337 "refs/heads/", &tracked_branch) ||
338 strcmp(tracked_branch, new_ref))
5ace483a 339 goto cleanup;
bdaf1dfa
TK
340 }
341
d3115660
JS
342 if (tracking.srcs->nr < 1)
343 string_list_append(tracking.srcs, orig_ref);
344 if (install_branch_config_multiple_remotes(config_flags, new_ref,
345 tracking.remote, tracking.srcs) < 0)
5391e948 346 exit(1);
e496c003 347
679e3693
GC
348cleanup:
349 string_list_clear(&tracking_srcs, 0);
e4921d87 350 string_list_clear(&ftb_cb.ambiguous_remotes, 0);
e496c003
DB
351}
352
6f9a3321
JH
353int read_branch_desc(struct strbuf *buf, const char *branch_name)
354{
540b0f49 355 char *v = NULL;
6f9a3321
JH
356 struct strbuf name = STRBUF_INIT;
357 strbuf_addf(&name, "branch.%s.description", branch_name);
540b0f49
TA
358 if (git_config_get_string(name.buf, &v)) {
359 strbuf_release(&name);
360 return -1;
361 }
362 strbuf_addstr(buf, v);
363 free(v);
6f9a3321
JH
364 strbuf_release(&name);
365 return 0;
366}
367
bc1c9c0e
JH
368/*
369 * Check if 'name' can be a valid name for a branch; die otherwise.
370 * Return 1 if the named branch already exists; return 0 otherwise.
371 * Fill ref with the full refname for the branch.
372 */
373int validate_branchname(const char *name, struct strbuf *ref)
55c4a673 374{
93e5e048 375 if (check_branch_ref(ref, name)) {
8fbd903e
KH
376 int code = die_message(_("'%s' is not a valid branch name"), name);
377 advise_if_enabled(ADVICE_REF_SYNTAX,
378 _("See `man git check-ref-format`"));
379 exit(code);
380 }
55c4a673 381
2e5c4758 382 return refs_ref_exists(get_main_ref_store(the_repository), ref->buf);
bc1c9c0e 383}
55c4a673 384
31ad6b61
DS
385static int initialized_checked_out_branches;
386static struct strmap current_checked_out_branches = STRMAP_INIT;
387
388static void prepare_checked_out_branches(void)
389{
390 int i = 0;
391 struct worktree **worktrees;
392
393 if (initialized_checked_out_branches)
394 return;
395 initialized_checked_out_branches = 1;
396
397 worktrees = get_worktrees();
398
399 while (worktrees[i]) {
8e4710f0 400 char *old, *wt_gitdir;
d2ba271a 401 struct wt_status_state state = { 0 };
31ad6b61 402 struct worktree *wt = worktrees[i++];
aa7f2fd1 403 struct string_list update_refs = STRING_LIST_INIT_DUP;
31ad6b61
DS
404
405 if (wt->is_bare)
406 continue;
407
4b6e18f5
DS
408 if (wt->head_ref) {
409 old = strmap_put(&current_checked_out_branches,
410 wt->head_ref,
411 xstrdup(wt->path));
412 free(old);
413 }
d2ba271a
DS
414
415 if (wt_status_check_rebase(wt, &state) &&
416 (state.rebase_in_progress || state.rebase_interactive_in_progress) &&
417 state.branch) {
418 struct strbuf ref = STRBUF_INIT;
419 strbuf_addf(&ref, "refs/heads/%s", state.branch);
4b6e18f5
DS
420 old = strmap_put(&current_checked_out_branches,
421 ref.buf,
422 xstrdup(wt->path));
423 free(old);
d2ba271a
DS
424 strbuf_release(&ref);
425 }
426 wt_status_state_free_buffers(&state);
427
428 if (wt_status_check_bisect(wt, &state) &&
990adccb 429 state.bisecting_from) {
d2ba271a 430 struct strbuf ref = STRBUF_INIT;
990adccb 431 strbuf_addf(&ref, "refs/heads/%s", state.bisecting_from);
4b6e18f5
DS
432 old = strmap_put(&current_checked_out_branches,
433 ref.buf,
434 xstrdup(wt->path));
435 free(old);
d2ba271a
DS
436 strbuf_release(&ref);
437 }
438 wt_status_state_free_buffers(&state);
aa7f2fd1 439
8e4710f0
PS
440 wt_gitdir = get_worktree_git_dir(wt);
441 if (!sequencer_get_update_refs_state(wt_gitdir,
aa7f2fd1
DS
442 &update_refs)) {
443 struct string_list_item *item;
444 for_each_string_list_item(item, &update_refs) {
445 old = strmap_put(&current_checked_out_branches,
446 item->string,
447 xstrdup(wt->path));
448 free(old);
449 }
450 string_list_clear(&update_refs, 1);
451 }
8e4710f0
PS
452
453 free(wt_gitdir);
31ad6b61
DS
454 }
455
456 free_worktrees(worktrees);
457}
458
459const char *branch_checked_out(const char *refname)
460{
461 prepare_checked_out_branches();
462 return strmap_get(&current_checked_out_branches, refname);
463}
464
bc1c9c0e
JH
465/*
466 * Check if a branch 'name' can be created as a new branch; die otherwise.
467 * 'force' can be used when it is OK for the named branch already exists.
468 * Return 1 if the named branch already exists; return 0 otherwise.
469 * Fill ref with the full refname for the branch.
470 */
471int validate_new_branchname(const char *name, struct strbuf *ref, int force)
472{
d2ba271a 473 const char *path;
bc1c9c0e 474 if (!validate_branchname(name, ref))
55c4a673 475 return 0;
55c4a673 476
8280c4c1 477 if (!force)
7435e7e2 478 die(_("a branch named '%s' already exists"),
8280c4c1
JH
479 ref->buf + strlen("refs/heads/"));
480
d2ba271a 481 if ((path = branch_checked_out(ref->buf)))
68d924e1 482 die(_("cannot force update the branch '%s' "
4970bede 483 "used by worktree at '%s'"),
d2ba271a 484 ref->buf + strlen("refs/heads/"), path);
55c4a673
CI
485
486 return 1;
487}
488
41c21f22
JH
489static int check_tracking_branch(struct remote *remote, void *cb_data)
490{
491 char *tracking_branch = cb_data;
0ad4a5ff 492 struct refspec_item query;
caee1d66 493 int res;
0ad4a5ff 494 memset(&query, 0, sizeof(struct refspec_item));
41c21f22 495 query.dst = tracking_branch;
caee1d66
RJ
496 res = !remote_find_tracking(remote, &query);
497 free(query.src);
498 return res;
41c21f22
JH
499}
500
501static int validate_remote_tracking_branch(char *ref)
502{
503 return !for_each_remote(check_tracking_branch, ref);
504}
505
e2b6aa5f 506static const char upstream_not_branch[] =
7435e7e2 507N_("cannot set up tracking information; starting point '%s' is not a branch");
a5e91c72 508static const char upstream_missing[] =
caa2036b
JK
509N_("the requested upstream branch '%s' does not exist");
510static const char upstream_advice[] =
511N_("\n"
512"If you are planning on basing your work on an upstream\n"
513"branch that already exists at the remote, you may need to\n"
514"run \"git fetch\" to retrieve it.\n"
515"\n"
516"If you are planning to push out a new local branch that\n"
517"will track its remote counterpart, you may want to use\n"
518"\"git push -u\" to set the upstream config as you push.");
e2b6aa5f 519
e89f151d
GC
520/**
521 * DWIMs a user-provided ref to determine the starting point for a
522 * branch and validates it, where:
523 *
524 * - r is the repository to validate the branch for
525 *
526 * - start_name is the ref that we would like to test. This is
527 * expanded with DWIM and assigned to out_real_ref.
528 *
529 * - track is the tracking mode of the new branch. If tracking is
530 * explicitly requested, start_name must be a branch (because
531 * otherwise start_name cannot be tracked)
532 *
533 * - out_oid is an out parameter containing the object_id of start_name
534 *
535 * - out_real_ref is an out parameter containing the full, 'real' form
536 * of start_name e.g. refs/heads/main instead of main
537 *
538 */
539static void dwim_branch_start(struct repository *r, const char *start_name,
540 enum branch_track track, char **out_real_ref,
541 struct object_id *out_oid)
e496c003 542{
e496c003 543 struct commit *commit;
48713bfa 544 struct object_id oid;
3818b258 545 char *real_ref;
4fc50066
IL
546 int explicit_tracking = 0;
547
548 if (track == BRANCH_TRACK_EXPLICIT || track == BRANCH_TRACK_OVERRIDE)
549 explicit_tracking = 1;
e496c003 550
e496c003 551 real_ref = NULL;
4a93b899 552 if (repo_get_oid_mb(r, start_name, &oid)) {
caa2036b 553 if (explicit_tracking) {
66966012
GC
554 int code = die_message(_(upstream_missing), start_name);
555 advise_if_enabled(ADVICE_SET_UPSTREAM_FAILURE,
556 _(upstream_advice));
557 exit(code);
caa2036b 558 }
7435e7e2 559 die(_("not a valid object name: '%s'"), start_name);
a5e91c72 560 }
e496c003 561
4a93b899
ÆAB
562 switch (repo_dwim_ref(r, start_name, strlen(start_name), &oid,
563 &real_ref, 0)) {
e496c003
DB
564 case 0:
565 /* Not branching from any existing branch */
4fc50066 566 if (explicit_tracking)
1a15d00b 567 die(_(upstream_not_branch), start_name);
e496c003
DB
568 break;
569 case 1:
21b5b1e8 570 /* Unique completion -- good, only if it is a real branch */
59556548 571 if (!starts_with(real_ref, "refs/heads/") &&
41c21f22 572 validate_remote_tracking_branch(real_ref)) {
21b5b1e8 573 if (explicit_tracking)
1a15d00b 574 die(_(upstream_not_branch), start_name);
21b5b1e8 575 else
d895804b 576 FREE_AND_NULL(real_ref);
21b5b1e8 577 }
e496c003
DB
578 break;
579 default:
7435e7e2 580 die(_("ambiguous object name: '%s'"), start_name);
e496c003
DB
581 break;
582 }
583
afe8a907 584 if (!(commit = lookup_commit_reference(r, &oid)))
7435e7e2 585 die(_("not a valid branch point: '%s'"), start_name);
e89f151d
GC
586 if (out_real_ref) {
587 *out_real_ref = real_ref;
588 real_ref = NULL;
589 }
590 if (out_oid)
591 oidcpy(out_oid, &commit->object.oid);
592
593 FREE_AND_NULL(real_ref);
594}
595
596void create_branch(struct repository *r,
597 const char *name, const char *start_name,
598 int force, int clobber_head_ok, int reflog,
3f3e7608 599 int quiet, enum branch_track track, int dry_run)
e89f151d
GC
600{
601 struct object_id oid;
602 char *real_ref;
603 struct strbuf ref = STRBUF_INIT;
604 int forcing = 0;
bc0893cf
GC
605 struct ref_transaction *transaction;
606 struct strbuf err = STRBUF_INIT;
118fd1a2 607 int flags = 0;
bc0893cf
GC
608 char *msg;
609
610 if (track == BRANCH_TRACK_OVERRIDE)
611 BUG("'track' cannot be BRANCH_TRACK_OVERRIDE. Did you mean to call dwim_and_setup_tracking()?");
612 if (clobber_head_ok && !force)
613 BUG("'clobber_head_ok' can only be used with 'force'");
614
615 if (clobber_head_ok ?
616 validate_branchname(name, &ref) :
617 validate_new_branchname(name, &ref, force)) {
618 forcing = 1;
e89f151d
GC
619 }
620
621 dwim_branch_start(r, start_name, track, &real_ref, &oid);
3f3e7608
GC
622 if (dry_run)
623 goto cleanup;
e496c003 624
d43f990f 625 if (reflog)
118fd1a2 626 flags |= REF_FORCE_CREATE_REFLOG;
d43f990f 627
bc0893cf
GC
628 if (forcing)
629 msg = xstrfmt("branch: Reset to %s", start_name);
630 else
631 msg = xstrfmt("branch: Created from %s", start_name);
2e5c4758 632 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
a0efef14 633 0, &err);
bc0893cf
GC
634 if (!transaction ||
635 ref_transaction_update(transaction, ref.buf,
7d70b29c 636 &oid, forcing ? NULL : null_oid(the_hash_algo),
118fd1a2 637 NULL, NULL, flags, msg, &err) ||
bc0893cf
GC
638 ref_transaction_commit(transaction, &err))
639 die("%s", err.buf);
640 ref_transaction_free(transaction);
641 strbuf_release(&err);
642 free(msg);
d43f990f 643
e496c003 644 if (real_ref && track)
82a0672f 645 setup_tracking(ref.buf + 11, real_ref, track, quiet);
e496c003 646
3f3e7608 647cleanup:
8415d5c7 648 strbuf_release(&ref);
9ed36cfa 649 free(real_ref);
e496c003 650}
c369e7b8 651
e89f151d
GC
652void dwim_and_setup_tracking(struct repository *r, const char *new_ref,
653 const char *orig_ref, enum branch_track track,
654 int quiet)
655{
1533bda7 656 char *real_orig_ref = NULL;
e89f151d
GC
657 dwim_branch_start(r, orig_ref, track, &real_orig_ref, NULL);
658 setup_tracking(new_ref, real_orig_ref, track, quiet);
1533bda7 659 free(real_orig_ref);
e89f151d
GC
660}
661
961b130d
GC
662/**
663 * Creates a branch in a submodule by calling
664 * create_branches_recursively() in a child process. The child process
665 * is necessary because install_branch_config_multiple_remotes() (which
666 * is called by setup_tracking()) does not support writing configs to
667 * submodules.
668 */
669static int submodule_create_branch(struct repository *r,
670 const struct submodule *submodule,
671 const char *name, const char *start_oid,
672 const char *tracking_name, int force,
673 int reflog, int quiet,
674 enum branch_track track, int dry_run)
675{
676 int ret = 0;
677 struct child_process child = CHILD_PROCESS_INIT;
678 struct strbuf child_err = STRBUF_INIT;
679 struct strbuf out_buf = STRBUF_INIT;
680 char *out_prefix = xstrfmt("submodule '%s': ", submodule->name);
681 child.git_cmd = 1;
682 child.err = -1;
683 child.stdout_to_stderr = 1;
684
29fda24d 685 prepare_other_repo_env(&child.env, r->gitdir);
961b130d
GC
686 /*
687 * submodule_create_branch() is indirectly invoked by "git
688 * branch", but we cannot invoke "git branch" in the child
689 * process. "git branch" accepts a branch name and start point,
690 * where the start point is assumed to provide both the OID
691 * (start_oid) and the branch to use for tracking
692 * (tracking_name). But when recursing through submodules,
693 * start_oid and tracking name need to be specified separately
694 * (see create_branches_recursively()).
695 */
696 strvec_pushl(&child.args, "submodule--helper", "create-branch", NULL);
697 if (dry_run)
698 strvec_push(&child.args, "--dry-run");
699 if (force)
700 strvec_push(&child.args, "--force");
701 if (quiet)
702 strvec_push(&child.args, "--quiet");
703 if (reflog)
704 strvec_push(&child.args, "--create-reflog");
75388bf5
GC
705
706 switch (track) {
707 case BRANCH_TRACK_NEVER:
708 strvec_push(&child.args, "--no-track");
709 break;
710 case BRANCH_TRACK_ALWAYS:
711 case BRANCH_TRACK_EXPLICIT:
712 strvec_push(&child.args, "--track=direct");
713 break;
714 case BRANCH_TRACK_OVERRIDE:
715 BUG("BRANCH_TRACK_OVERRIDE cannot be used when creating a branch.");
716 break;
717 case BRANCH_TRACK_INHERIT:
718 strvec_push(&child.args, "--track=inherit");
719 break;
720 case BRANCH_TRACK_UNSPECIFIED:
1f888282 721 /* Default for "git checkout". Do not pass --track. */
75388bf5 722 case BRANCH_TRACK_REMOTE:
1f888282 723 /* Default for "git branch". Do not pass --track. */
bdaf1dfa
TK
724 case BRANCH_TRACK_SIMPLE:
725 /* Config-driven only. Do not pass --track. */
75388bf5
GC
726 break;
727 }
961b130d
GC
728
729 strvec_pushl(&child.args, name, start_oid, tracking_name, NULL);
730
731 if ((ret = start_command(&child)))
732 return ret;
733 ret = finish_command(&child);
734 strbuf_read(&child_err, child.err, 0);
735 strbuf_add_lines(&out_buf, out_prefix, child_err.buf, child_err.len);
736
737 if (ret)
738 fprintf(stderr, "%s", out_buf.buf);
739 else
740 printf("%s", out_buf.buf);
741
742 strbuf_release(&child_err);
743 strbuf_release(&out_buf);
5cca1149 744 free(out_prefix);
961b130d
GC
745 return ret;
746}
747
748void create_branches_recursively(struct repository *r, const char *name,
84a7c33a 749 const char *start_committish,
961b130d
GC
750 const char *tracking_name, int force,
751 int reflog, int quiet, enum branch_track track,
752 int dry_run)
753{
754 int i = 0;
755 char *branch_point = NULL;
756 struct object_id super_oid;
757 struct submodule_entry_list submodule_entry_list;
758
84a7c33a
PF
759 /* Perform dwim on start_committish to get super_oid and branch_point. */
760 dwim_branch_start(r, start_committish, BRANCH_TRACK_NEVER,
961b130d
GC
761 &branch_point, &super_oid);
762
763 /*
764 * If we were not given an explicit name to track, then assume we are at
765 * the top level and, just like the non-recursive case, the tracking
766 * name is the branch point.
767 */
768 if (!tracking_name)
769 tracking_name = branch_point;
770
771 submodules_of_tree(r, &super_oid, &submodule_entry_list);
772 /*
773 * Before creating any branches, first check that the branch can
774 * be created in every submodule.
775 */
776 for (i = 0; i < submodule_entry_list.entry_nr; i++) {
e6bf70d1 777 if (!submodule_entry_list.entries[i].repo) {
cfbda6ba
GC
778 int code = die_message(
779 _("submodule '%s': unable to find submodule"),
780 submodule_entry_list.entries[i].submodule->name);
961b130d 781 if (advice_enabled(ADVICE_SUBMODULES_NOT_UPDATED))
97cf0c7d 782 advise(_("You may try updating the submodules using 'git checkout --no-recurse-submodules %s && git submodule update --init'"),
84a7c33a 783 start_committish);
cfbda6ba 784 exit(code);
961b130d
GC
785 }
786
787 if (submodule_create_branch(
788 submodule_entry_list.entries[i].repo,
789 submodule_entry_list.entries[i].submodule, name,
790 oid_to_hex(&submodule_entry_list.entries[i]
791 .name_entry->oid),
792 tracking_name, force, reflog, quiet, track, 1))
793 die(_("submodule '%s': cannot create branch '%s'"),
794 submodule_entry_list.entries[i].submodule->name,
795 name);
796 }
797
84a7c33a 798 create_branch(r, name, start_committish, force, 0, reflog, quiet,
961b130d
GC
799 BRANCH_TRACK_NEVER, dry_run);
800 if (dry_run)
5cca1149 801 goto out;
961b130d
GC
802 /*
803 * NEEDSWORK If tracking was set up in the superproject but not the
804 * submodule, users might expect "git branch --recurse-submodules" to
805 * fail or give a warning, but this is not yet implemented because it is
806 * tedious to determine whether or not tracking was set up in the
807 * superproject.
808 */
75388bf5
GC
809 if (track)
810 setup_tracking(name, tracking_name, track, quiet);
961b130d
GC
811
812 for (i = 0; i < submodule_entry_list.entry_nr; i++) {
813 if (submodule_create_branch(
814 submodule_entry_list.entries[i].repo,
815 submodule_entry_list.entries[i].submodule, name,
816 oid_to_hex(&submodule_entry_list.entries[i]
817 .name_entry->oid),
818 tracking_name, force, reflog, quiet, track, 0))
819 die(_("submodule '%s': cannot create branch '%s'"),
820 submodule_entry_list.entries[i].submodule->name,
821 name);
961b130d 822 }
5cca1149
PS
823
824out:
825 submodule_entry_list_release(&submodule_entry_list);
826 free(branch_point);
961b130d
GC
827}
828
b6433555 829void remove_merge_branch_state(struct repository *r)
c369e7b8 830{
4edce172
NTND
831 unlink(git_path_merge_head(r));
832 unlink(git_path_merge_rr(r));
833 unlink(git_path_merge_msg(r));
834 unlink(git_path_merge_mode(r));
fd7c6ffa
PS
835 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
836 NULL, REF_NO_DEREF);
3f921c75 837 save_autostash_ref(r, "MERGE_AUTOSTASH");
b6433555
NTND
838}
839
f496b064 840void remove_branch_state(struct repository *r, int verbose)
b6433555 841{
f496b064 842 sequencer_post_commit_cleanup(r, verbose);
4edce172 843 unlink(git_path_squash_msg(r));
b6433555 844 remove_merge_branch_state(r);
c369e7b8 845}
ed89f84b 846
8d9fdd70 847void die_if_checked_out(const char *branch, int ignore_current_worktree)
41af6565 848{
c8dd491f 849 struct worktree **worktrees = get_worktrees();
41af6565 850
faa4d598
RJ
851 for (int i = 0; worktrees[i]; i++) {
852 if (worktrees[i]->is_current && ignore_current_worktree)
853 continue;
854
855 if (is_shared_symref(worktrees[i], "HEAD", branch)) {
856 skip_prefix(branch, "refs/heads/", &branch);
2a499264 857 die(_("'%s' is already used by worktree at '%s'"),
faa4d598
RJ
858 branch, worktrees[i]->path);
859 }
c8dd491f
AK
860 }
861
862 free_worktrees(worktrees);
ed89f84b 863}