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