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