1 #include "git-compat-util.h"
11 #include "submodule-config.h"
12 #include "run-command.h"
15 struct refspec_item spec
;
16 struct string_list
*srcs
;
21 struct find_tracked_branch_cb
{
22 struct tracking
*tracking
;
23 struct string_list ambiguous_remotes
;
26 static int find_tracked_branch(struct remote
*remote
, void *priv
)
28 struct find_tracked_branch_cb
*ftb
= priv
;
29 struct tracking
*tracking
= ftb
->tracking
;
31 if (!remote_find_tracking(remote
, &tracking
->spec
)) {
32 switch (++tracking
->matches
) {
34 string_list_append(tracking
->srcs
, tracking
->spec
.src
);
35 tracking
->remote
= remote
->name
;
38 /* there are at least two remotes; backfill the first one */
39 string_list_append(&ftb
->ambiguous_remotes
, tracking
->remote
);
42 string_list_append(&ftb
->ambiguous_remotes
, remote
->name
);
43 free(tracking
->spec
.src
);
44 string_list_clear(tracking
->srcs
, 0);
47 tracking
->spec
.src
= NULL
;
53 static int should_setup_rebase(const char *origin
)
56 case AUTOREBASE_NEVER
:
58 case AUTOREBASE_LOCAL
:
59 return origin
== NULL
;
60 case AUTOREBASE_REMOTE
:
61 return origin
!= NULL
;
62 case AUTOREBASE_ALWAYS
:
69 * Install upstream tracking configuration for a branch; specifically, add
70 * `branch.<name>.remote` and `branch.<name>.merge` entries.
72 * `flag` contains integer flags for options; currently only
73 * BRANCH_CONFIG_VERBOSE is checked.
75 * `local` is the name of the branch whose configuration we're installing.
77 * `origin` is the name of the remote owning the upstream branches. NULL means
78 * the upstream branches are local to this repo.
80 * `remotes` is a list of refs that are upstream of local
82 static int install_branch_config_multiple_remotes(int flag
, const char *local
,
83 const char *origin
, struct string_list
*remotes
)
85 const char *shortname
= NULL
;
86 struct strbuf key
= STRBUF_INIT
;
87 struct string_list_item
*item
;
88 int rebasing
= should_setup_rebase(origin
);
91 BUG("must provide at least one remote for branch config");
92 if (rebasing
&& remotes
->nr
> 1)
93 die(_("cannot inherit upstream tracking configuration of "
94 "multiple refs when rebasing is requested"));
97 * If the new branch is trying to track itself, something has gone
98 * wrong. Warn the user and don't proceed any further.
101 for_each_string_list_item(item
, remotes
)
102 if (skip_prefix(item
->string
, "refs/heads/", &shortname
)
103 && !strcmp(local
, shortname
)) {
104 warning(_("not setting branch '%s' as its own upstream"),
109 strbuf_addf(&key
, "branch.%s.remote", local
);
110 if (git_config_set_gently(key
.buf
, origin
? origin
: ".") < 0)
114 strbuf_addf(&key
, "branch.%s.merge", local
);
116 * We want to overwrite any existing config with all the branches in
117 * "remotes". Override any existing config, then write our branches. If
118 * more than one is provided, use CONFIG_REGEX_NONE to preserve what
119 * we've written so far.
121 if (git_config_set_gently(key
.buf
, NULL
) < 0)
123 for_each_string_list_item(item
, remotes
)
124 if (git_config_set_multivar_gently(key
.buf
, item
->string
, CONFIG_REGEX_NONE
, 0) < 0)
129 strbuf_addf(&key
, "branch.%s.rebase", local
);
130 if (git_config_set_gently(key
.buf
, "true") < 0)
133 strbuf_release(&key
);
135 if (flag
& BRANCH_CONFIG_VERBOSE
) {
136 struct strbuf tmp_ref_name
= STRBUF_INIT
;
137 struct string_list friendly_ref_names
= STRING_LIST_INIT_DUP
;
139 for_each_string_list_item(item
, remotes
) {
140 shortname
= item
->string
;
141 skip_prefix(shortname
, "refs/heads/", &shortname
);
143 strbuf_addf(&tmp_ref_name
, "%s/%s",
145 string_list_append_nodup(
147 strbuf_detach(&tmp_ref_name
, NULL
));
150 &friendly_ref_names
, shortname
);
154 if (remotes
->nr
== 1) {
156 * Rebasing is only allowed in the case of a single
160 _("branch '%s' set up to track '%s' by rebasing.") :
161 _("branch '%s' set up to track '%s'."),
162 local
, friendly_ref_names
.items
[0].string
);
164 printf_ln(_("branch '%s' set up to track:"), local
);
165 for_each_string_list_item(item
, &friendly_ref_names
)
166 printf_ln(" %s", item
->string
);
169 string_list_clear(&friendly_ref_names
, 0);
175 strbuf_release(&key
);
176 error(_("unable to write upstream branch configuration"));
178 advise(_("\nAfter fixing the error cause you may try to fix up\n"
179 "the remote tracking information by invoking:"));
180 if (remotes
->nr
== 1)
181 advise(" git branch --set-upstream-to=%s%s%s",
182 origin
? origin
: "",
184 remotes
->items
[0].string
);
186 advise(" git config --add branch.\"%s\".remote %s",
187 local
, origin
? origin
: ".");
188 for_each_string_list_item(item
, remotes
)
189 advise(" git config --add branch.\"%s\".merge %s",
190 local
, item
->string
);
196 int install_branch_config(int flag
, const char *local
, const char *origin
,
200 struct string_list remotes
= STRING_LIST_INIT_DUP
;
202 string_list_append(&remotes
, remote
);
203 ret
= install_branch_config_multiple_remotes(flag
, local
, origin
, &remotes
);
204 string_list_clear(&remotes
, 0);
208 static int inherit_tracking(struct tracking
*tracking
, const char *orig_ref
)
210 const char *bare_ref
;
211 struct branch
*branch
;
215 skip_prefix(orig_ref
, "refs/heads/", &bare_ref
);
217 branch
= branch_get(bare_ref
);
218 if (!branch
->remote_name
) {
219 warning(_("asked to inherit tracking from '%s', but no remote is set"),
224 if (branch
->merge_nr
< 1 || !branch
->merge_name
|| !branch
->merge_name
[0]) {
225 warning(_("asked to inherit tracking from '%s', but no merge configuration is set"),
230 tracking
->remote
= xstrdup(branch
->remote_name
);
231 for (i
= 0; i
< branch
->merge_nr
; i
++)
232 string_list_append(tracking
->srcs
, branch
->merge_name
[i
]);
237 * Used internally to set the branch.<new_ref>.{remote,merge} config
238 * settings so that branch 'new_ref' tracks 'orig_ref'. Unlike
239 * dwim_and_setup_tracking(), this does not do DWIM, i.e. "origin/main"
240 * will not be expanded to "refs/remotes/origin/main", so it is not safe
241 * for 'orig_ref' to be raw user input.
243 static void setup_tracking(const char *new_ref
, const char *orig_ref
,
244 enum branch_track track
, int quiet
)
246 struct tracking tracking
;
247 struct string_list tracking_srcs
= STRING_LIST_INIT_DUP
;
248 int config_flags
= quiet
? 0 : BRANCH_CONFIG_VERBOSE
;
249 struct find_tracked_branch_cb ftb_cb
= {
250 .tracking
= &tracking
,
251 .ambiguous_remotes
= STRING_LIST_INIT_DUP
,
255 BUG("asked to set up tracking, but tracking is disallowed");
257 memset(&tracking
, 0, sizeof(tracking
));
258 tracking
.spec
.dst
= (char *)orig_ref
;
259 tracking
.srcs
= &tracking_srcs
;
260 if (track
!= BRANCH_TRACK_INHERIT
)
261 for_each_remote(find_tracked_branch
, &ftb_cb
);
262 else if (inherit_tracking(&tracking
, orig_ref
))
265 if (!tracking
.matches
)
267 case BRANCH_TRACK_ALWAYS
:
268 case BRANCH_TRACK_EXPLICIT
:
269 case BRANCH_TRACK_OVERRIDE
:
270 case BRANCH_TRACK_INHERIT
:
276 if (tracking
.matches
> 1) {
277 int status
= die_message(_("not tracking: ambiguous information for ref '%s'"),
279 if (advice_enabled(ADVICE_AMBIGUOUS_FETCH_REFSPEC
)) {
280 struct strbuf remotes_advice
= STRBUF_INIT
;
281 struct string_list_item
*item
;
283 for_each_string_list_item(item
, &ftb_cb
.ambiguous_remotes
)
285 * TRANSLATORS: This is a line listing a remote with duplicate
286 * refspecs in the advice message below. For RTL languages you'll
287 * probably want to swap the "%s" and leading " " space around.
289 strbuf_addf(&remotes_advice
, _(" %s\n"), item
->string
);
292 * TRANSLATORS: The second argument is a \n-delimited list of
293 * duplicate refspecs, composed above.
295 advise(_("There are multiple remotes whose fetch refspecs map to the remote\n"
296 "tracking ref '%s':\n"
299 "This is typically a configuration error.\n"
301 "To support setting up tracking branches, ensure that\n"
302 "different remotes' fetch refspecs map into different\n"
303 "tracking namespaces."), orig_ref
,
305 strbuf_release(&remotes_advice
);
310 if (tracking
.srcs
->nr
< 1)
311 string_list_append(tracking
.srcs
, orig_ref
);
312 if (install_branch_config_multiple_remotes(config_flags
, new_ref
,
313 tracking
.remote
, tracking
.srcs
) < 0)
317 string_list_clear(&tracking_srcs
, 0);
318 string_list_clear(&ftb_cb
.ambiguous_remotes
, 0);
321 int read_branch_desc(struct strbuf
*buf
, const char *branch_name
)
324 struct strbuf name
= STRBUF_INIT
;
325 strbuf_addf(&name
, "branch.%s.description", branch_name
);
326 if (git_config_get_string(name
.buf
, &v
)) {
327 strbuf_release(&name
);
330 strbuf_addstr(buf
, v
);
332 strbuf_release(&name
);
337 * Check if 'name' can be a valid name for a branch; die otherwise.
338 * Return 1 if the named branch already exists; return 0 otherwise.
339 * Fill ref with the full refname for the branch.
341 int validate_branchname(const char *name
, struct strbuf
*ref
)
343 if (strbuf_check_branch_ref(ref
, name
))
344 die(_("'%s' is not a valid branch name"), name
);
346 return ref_exists(ref
->buf
);
350 * Check if a branch 'name' can be created as a new branch; die otherwise.
351 * 'force' can be used when it is OK for the named branch already exists.
352 * Return 1 if the named branch already exists; return 0 otherwise.
353 * Fill ref with the full refname for the branch.
355 int validate_new_branchname(const char *name
, struct strbuf
*ref
, int force
)
357 struct worktree
**worktrees
;
358 const struct worktree
*wt
;
360 if (!validate_branchname(name
, ref
))
364 die(_("a branch named '%s' already exists"),
365 ref
->buf
+ strlen("refs/heads/"));
367 worktrees
= get_worktrees();
368 wt
= find_shared_symref(worktrees
, "HEAD", ref
->buf
);
369 if (wt
&& !wt
->is_bare
)
370 die(_("cannot force update the branch '%s' "
371 "checked out at '%s'"),
372 ref
->buf
+ strlen("refs/heads/"), wt
->path
);
373 free_worktrees(worktrees
);
378 static int check_tracking_branch(struct remote
*remote
, void *cb_data
)
380 char *tracking_branch
= cb_data
;
381 struct refspec_item query
;
382 memset(&query
, 0, sizeof(struct refspec_item
));
383 query
.dst
= tracking_branch
;
384 return !remote_find_tracking(remote
, &query
);
387 static int validate_remote_tracking_branch(char *ref
)
389 return !for_each_remote(check_tracking_branch
, ref
);
392 static const char upstream_not_branch
[] =
393 N_("cannot set up tracking information; starting point '%s' is not a branch");
394 static const char upstream_missing
[] =
395 N_("the requested upstream branch '%s' does not exist");
396 static const char upstream_advice
[] =
398 "If you are planning on basing your work on an upstream\n"
399 "branch that already exists at the remote, you may need to\n"
400 "run \"git fetch\" to retrieve it.\n"
402 "If you are planning to push out a new local branch that\n"
403 "will track its remote counterpart, you may want to use\n"
404 "\"git push -u\" to set the upstream config as you push.");
407 * DWIMs a user-provided ref to determine the starting point for a
408 * branch and validates it, where:
410 * - r is the repository to validate the branch for
412 * - start_name is the ref that we would like to test. This is
413 * expanded with DWIM and assigned to out_real_ref.
415 * - track is the tracking mode of the new branch. If tracking is
416 * explicitly requested, start_name must be a branch (because
417 * otherwise start_name cannot be tracked)
419 * - out_oid is an out parameter containing the object_id of start_name
421 * - out_real_ref is an out parameter containing the full, 'real' form
422 * of start_name e.g. refs/heads/main instead of main
425 static void dwim_branch_start(struct repository
*r
, const char *start_name
,
426 enum branch_track track
, char **out_real_ref
,
427 struct object_id
*out_oid
)
429 struct commit
*commit
;
430 struct object_id oid
;
432 int explicit_tracking
= 0;
434 if (track
== BRANCH_TRACK_EXPLICIT
|| track
== BRANCH_TRACK_OVERRIDE
)
435 explicit_tracking
= 1;
438 if (get_oid_mb(start_name
, &oid
)) {
439 if (explicit_tracking
) {
440 int code
= die_message(_(upstream_missing
), start_name
);
441 advise_if_enabled(ADVICE_SET_UPSTREAM_FAILURE
,
445 die(_("not a valid object name: '%s'"), start_name
);
448 switch (dwim_ref(start_name
, strlen(start_name
), &oid
, &real_ref
, 0)) {
450 /* Not branching from any existing branch */
451 if (explicit_tracking
)
452 die(_(upstream_not_branch
), start_name
);
455 /* Unique completion -- good, only if it is a real branch */
456 if (!starts_with(real_ref
, "refs/heads/") &&
457 validate_remote_tracking_branch(real_ref
)) {
458 if (explicit_tracking
)
459 die(_(upstream_not_branch
), start_name
);
461 FREE_AND_NULL(real_ref
);
465 die(_("ambiguous object name: '%s'"), start_name
);
469 if ((commit
= lookup_commit_reference(r
, &oid
)) == NULL
)
470 die(_("not a valid branch point: '%s'"), start_name
);
472 *out_real_ref
= real_ref
;
476 oidcpy(out_oid
, &commit
->object
.oid
);
478 FREE_AND_NULL(real_ref
);
481 void create_branch(struct repository
*r
,
482 const char *name
, const char *start_name
,
483 int force
, int clobber_head_ok
, int reflog
,
484 int quiet
, enum branch_track track
, int dry_run
)
486 struct object_id oid
;
488 struct strbuf ref
= STRBUF_INIT
;
490 struct ref_transaction
*transaction
;
491 struct strbuf err
= STRBUF_INIT
;
494 if (track
== BRANCH_TRACK_OVERRIDE
)
495 BUG("'track' cannot be BRANCH_TRACK_OVERRIDE. Did you mean to call dwim_and_setup_tracking()?");
496 if (clobber_head_ok
&& !force
)
497 BUG("'clobber_head_ok' can only be used with 'force'");
499 if (clobber_head_ok
?
500 validate_branchname(name
, &ref
) :
501 validate_new_branchname(name
, &ref
, force
)) {
505 dwim_branch_start(r
, start_name
, track
, &real_ref
, &oid
);
510 log_all_ref_updates
= LOG_REFS_NORMAL
;
513 msg
= xstrfmt("branch: Reset to %s", start_name
);
515 msg
= xstrfmt("branch: Created from %s", start_name
);
516 transaction
= ref_transaction_begin(&err
);
518 ref_transaction_update(transaction
, ref
.buf
,
519 &oid
, forcing
? NULL
: null_oid(),
521 ref_transaction_commit(transaction
, &err
))
523 ref_transaction_free(transaction
);
524 strbuf_release(&err
);
527 if (real_ref
&& track
)
528 setup_tracking(ref
.buf
+ 11, real_ref
, track
, quiet
);
531 strbuf_release(&ref
);
535 void dwim_and_setup_tracking(struct repository
*r
, const char *new_ref
,
536 const char *orig_ref
, enum branch_track track
,
540 dwim_branch_start(r
, orig_ref
, track
, &real_orig_ref
, NULL
);
541 setup_tracking(new_ref
, real_orig_ref
, track
, quiet
);
545 * Creates a branch in a submodule by calling
546 * create_branches_recursively() in a child process. The child process
547 * is necessary because install_branch_config_multiple_remotes() (which
548 * is called by setup_tracking()) does not support writing configs to
551 static int submodule_create_branch(struct repository
*r
,
552 const struct submodule
*submodule
,
553 const char *name
, const char *start_oid
,
554 const char *tracking_name
, int force
,
555 int reflog
, int quiet
,
556 enum branch_track track
, int dry_run
)
559 struct child_process child
= CHILD_PROCESS_INIT
;
560 struct strbuf child_err
= STRBUF_INIT
;
561 struct strbuf out_buf
= STRBUF_INIT
;
562 char *out_prefix
= xstrfmt("submodule '%s': ", submodule
->name
);
565 child
.stdout_to_stderr
= 1;
567 prepare_other_repo_env(&child
.env_array
, r
->gitdir
);
569 * submodule_create_branch() is indirectly invoked by "git
570 * branch", but we cannot invoke "git branch" in the child
571 * process. "git branch" accepts a branch name and start point,
572 * where the start point is assumed to provide both the OID
573 * (start_oid) and the branch to use for tracking
574 * (tracking_name). But when recursing through submodules,
575 * start_oid and tracking name need to be specified separately
576 * (see create_branches_recursively()).
578 strvec_pushl(&child
.args
, "submodule--helper", "create-branch", NULL
);
580 strvec_push(&child
.args
, "--dry-run");
582 strvec_push(&child
.args
, "--force");
584 strvec_push(&child
.args
, "--quiet");
586 strvec_push(&child
.args
, "--create-reflog");
589 case BRANCH_TRACK_NEVER
:
590 strvec_push(&child
.args
, "--no-track");
592 case BRANCH_TRACK_ALWAYS
:
593 case BRANCH_TRACK_EXPLICIT
:
594 strvec_push(&child
.args
, "--track=direct");
596 case BRANCH_TRACK_OVERRIDE
:
597 BUG("BRANCH_TRACK_OVERRIDE cannot be used when creating a branch.");
599 case BRANCH_TRACK_INHERIT
:
600 strvec_push(&child
.args
, "--track=inherit");
602 case BRANCH_TRACK_UNSPECIFIED
:
603 /* Default for "git checkout". Do not pass --track. */
604 case BRANCH_TRACK_REMOTE
:
605 /* Default for "git branch". Do not pass --track. */
609 strvec_pushl(&child
.args
, name
, start_oid
, tracking_name
, NULL
);
611 if ((ret
= start_command(&child
)))
613 ret
= finish_command(&child
);
614 strbuf_read(&child_err
, child
.err
, 0);
615 strbuf_add_lines(&out_buf
, out_prefix
, child_err
.buf
, child_err
.len
);
618 fprintf(stderr
, "%s", out_buf
.buf
);
620 printf("%s", out_buf
.buf
);
622 strbuf_release(&child_err
);
623 strbuf_release(&out_buf
);
627 void create_branches_recursively(struct repository
*r
, const char *name
,
628 const char *start_commitish
,
629 const char *tracking_name
, int force
,
630 int reflog
, int quiet
, enum branch_track track
,
634 char *branch_point
= NULL
;
635 struct object_id super_oid
;
636 struct submodule_entry_list submodule_entry_list
;
638 /* Perform dwim on start_commitish to get super_oid and branch_point. */
639 dwim_branch_start(r
, start_commitish
, BRANCH_TRACK_NEVER
,
640 &branch_point
, &super_oid
);
643 * If we were not given an explicit name to track, then assume we are at
644 * the top level and, just like the non-recursive case, the tracking
645 * name is the branch point.
648 tracking_name
= branch_point
;
650 submodules_of_tree(r
, &super_oid
, &submodule_entry_list
);
652 * Before creating any branches, first check that the branch can
653 * be created in every submodule.
655 for (i
= 0; i
< submodule_entry_list
.entry_nr
; i
++) {
656 if (submodule_entry_list
.entries
[i
].repo
== NULL
) {
657 int code
= die_message(
658 _("submodule '%s': unable to find submodule"),
659 submodule_entry_list
.entries
[i
].submodule
->name
);
660 if (advice_enabled(ADVICE_SUBMODULES_NOT_UPDATED
))
661 advise(_("You may try updating the submodules using 'git checkout %s && git submodule update --init'"),
666 if (submodule_create_branch(
667 submodule_entry_list
.entries
[i
].repo
,
668 submodule_entry_list
.entries
[i
].submodule
, name
,
669 oid_to_hex(&submodule_entry_list
.entries
[i
]
671 tracking_name
, force
, reflog
, quiet
, track
, 1))
672 die(_("submodule '%s': cannot create branch '%s'"),
673 submodule_entry_list
.entries
[i
].submodule
->name
,
677 create_branch(the_repository
, name
, start_commitish
, force
, 0, reflog
, quiet
,
678 BRANCH_TRACK_NEVER
, dry_run
);
682 * NEEDSWORK If tracking was set up in the superproject but not the
683 * submodule, users might expect "git branch --recurse-submodules" to
684 * fail or give a warning, but this is not yet implemented because it is
685 * tedious to determine whether or not tracking was set up in the
689 setup_tracking(name
, tracking_name
, track
, quiet
);
691 for (i
= 0; i
< submodule_entry_list
.entry_nr
; i
++) {
692 if (submodule_create_branch(
693 submodule_entry_list
.entries
[i
].repo
,
694 submodule_entry_list
.entries
[i
].submodule
, name
,
695 oid_to_hex(&submodule_entry_list
.entries
[i
]
697 tracking_name
, force
, reflog
, quiet
, track
, 0))
698 die(_("submodule '%s': cannot create branch '%s'"),
699 submodule_entry_list
.entries
[i
].submodule
->name
,
701 repo_clear(submodule_entry_list
.entries
[i
].repo
);
705 void remove_merge_branch_state(struct repository
*r
)
707 unlink(git_path_merge_head(r
));
708 unlink(git_path_merge_rr(r
));
709 unlink(git_path_merge_msg(r
));
710 unlink(git_path_merge_mode(r
));
711 unlink(git_path_auto_merge(r
));
712 save_autostash(git_path_merge_autostash(r
));
715 void remove_branch_state(struct repository
*r
, int verbose
)
717 sequencer_post_commit_cleanup(r
, verbose
);
718 unlink(git_path_squash_msg(r
));
719 remove_merge_branch_state(r
);
722 void die_if_checked_out(const char *branch
, int ignore_current_worktree
)
724 struct worktree
**worktrees
= get_worktrees();
725 const struct worktree
*wt
;
727 wt
= find_shared_symref(worktrees
, "HEAD", branch
);
728 if (wt
&& (!ignore_current_worktree
|| !wt
->is_current
)) {
729 skip_prefix(branch
, "refs/heads/", &branch
);
730 die(_("'%s' is already checked out at '%s'"), branch
, wt
->path
);
733 free_worktrees(worktrees
);
736 int replace_each_worktree_head_symref(const char *oldref
, const char *newref
,
740 struct worktree
**worktrees
= get_worktrees();
743 for (i
= 0; worktrees
[i
]; i
++) {
744 struct ref_store
*refs
;
746 if (worktrees
[i
]->is_detached
)
748 if (!worktrees
[i
]->head_ref
)
750 if (strcmp(oldref
, worktrees
[i
]->head_ref
))
753 refs
= get_worktree_ref_store(worktrees
[i
]);
754 if (refs_create_symref(refs
, "HEAD", newref
, logmsg
))
755 ret
= error(_("HEAD of working tree %s is not updated"),
759 free_worktrees(worktrees
);