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