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