switch: mention the --detach option when dying due to lack of a branch
[git/debian.git] / branch.c
blob6b31df539a5f72e07bc5efb4592f703ddd70d28c
1 #include "git-compat-util.h"
2 #include "cache.h"
3 #include "config.h"
4 #include "branch.h"
5 #include "refs.h"
6 #include "refspec.h"
7 #include "remote.h"
8 #include "sequencer.h"
9 #include "commit.h"
10 #include "worktree.h"
11 #include "submodule-config.h"
12 #include "run-command.h"
14 struct tracking {
15 struct refspec_item spec;
16 struct string_list *srcs;
17 const char *remote;
18 int matches;
21 static int find_tracked_branch(struct remote *remote, void *priv)
23 struct tracking *tracking = priv;
25 if (!remote_find_tracking(remote, &tracking->spec)) {
26 if (++tracking->matches == 1) {
27 string_list_append(tracking->srcs, tracking->spec.src);
28 tracking->remote = remote->name;
29 } else {
30 free(tracking->spec.src);
31 string_list_clear(tracking->srcs, 0);
33 tracking->spec.src = NULL;
36 return 0;
39 static int should_setup_rebase(const char *origin)
41 switch (autorebase) {
42 case AUTOREBASE_NEVER:
43 return 0;
44 case AUTOREBASE_LOCAL:
45 return origin == NULL;
46 case AUTOREBASE_REMOTE:
47 return origin != NULL;
48 case AUTOREBASE_ALWAYS:
49 return 1;
51 return 0;
54 /**
55 * Install upstream tracking configuration for a branch; specifically, add
56 * `branch.<name>.remote` and `branch.<name>.merge` entries.
58 * `flag` contains integer flags for options; currently only
59 * BRANCH_CONFIG_VERBOSE is checked.
61 * `local` is the name of the branch whose configuration we're installing.
63 * `origin` is the name of the remote owning the upstream branches. NULL means
64 * the upstream branches are local to this repo.
66 * `remotes` is a list of refs that are upstream of local
68 static int install_branch_config_multiple_remotes(int flag, const char *local,
69 const char *origin, struct string_list *remotes)
71 const char *shortname = NULL;
72 struct strbuf key = STRBUF_INIT;
73 struct string_list_item *item;
74 int rebasing = should_setup_rebase(origin);
76 if (!remotes->nr)
77 BUG("must provide at least one remote for branch config");
78 if (rebasing && remotes->nr > 1)
79 die(_("cannot inherit upstream tracking configuration of "
80 "multiple refs when rebasing is requested"));
83 * If the new branch is trying to track itself, something has gone
84 * wrong. Warn the user and don't proceed any further.
86 if (!origin)
87 for_each_string_list_item(item, remotes)
88 if (skip_prefix(item->string, "refs/heads/", &shortname)
89 && !strcmp(local, shortname)) {
90 warning(_("not setting branch '%s' as its own upstream"),
91 local);
92 return 0;
95 strbuf_addf(&key, "branch.%s.remote", local);
96 if (git_config_set_gently(key.buf, origin ? origin : ".") < 0)
97 goto out_err;
99 strbuf_reset(&key);
100 strbuf_addf(&key, "branch.%s.merge", local);
102 * We want to overwrite any existing config with all the branches in
103 * "remotes". Override any existing config, then write our branches. If
104 * more than one is provided, use CONFIG_REGEX_NONE to preserve what
105 * we've written so far.
107 if (git_config_set_gently(key.buf, NULL) < 0)
108 goto out_err;
109 for_each_string_list_item(item, remotes)
110 if (git_config_set_multivar_gently(key.buf, item->string, CONFIG_REGEX_NONE, 0) < 0)
111 goto out_err;
113 if (rebasing) {
114 strbuf_reset(&key);
115 strbuf_addf(&key, "branch.%s.rebase", local);
116 if (git_config_set_gently(key.buf, "true") < 0)
117 goto out_err;
119 strbuf_release(&key);
121 if (flag & BRANCH_CONFIG_VERBOSE) {
122 struct strbuf tmp_ref_name = STRBUF_INIT;
123 struct string_list friendly_ref_names = STRING_LIST_INIT_DUP;
125 for_each_string_list_item(item, remotes) {
126 shortname = item->string;
127 skip_prefix(shortname, "refs/heads/", &shortname);
128 if (origin) {
129 strbuf_addf(&tmp_ref_name, "%s/%s",
130 origin, shortname);
131 string_list_append_nodup(
132 &friendly_ref_names,
133 strbuf_detach(&tmp_ref_name, NULL));
134 } else {
135 string_list_append(
136 &friendly_ref_names, shortname);
140 if (remotes->nr == 1) {
142 * Rebasing is only allowed in the case of a single
143 * upstream branch.
145 printf_ln(rebasing ?
146 _("branch '%s' set up to track '%s' by rebasing.") :
147 _("branch '%s' set up to track '%s'."),
148 local, friendly_ref_names.items[0].string);
149 } else {
150 printf_ln(_("branch '%s' set up to track:"), local);
151 for_each_string_list_item(item, &friendly_ref_names)
152 printf_ln(" %s", item->string);
155 string_list_clear(&friendly_ref_names, 0);
158 return 0;
160 out_err:
161 strbuf_release(&key);
162 error(_("unable to write upstream branch configuration"));
164 advise(_("\nAfter fixing the error cause you may try to fix up\n"
165 "the remote tracking information by invoking:"));
166 if (remotes->nr == 1)
167 advise(" git branch --set-upstream-to=%s%s%s",
168 origin ? origin : "",
169 origin ? "/" : "",
170 remotes->items[0].string);
171 else {
172 advise(" git config --add branch.\"%s\".remote %s",
173 local, origin ? origin : ".");
174 for_each_string_list_item(item, remotes)
175 advise(" git config --add branch.\"%s\".merge %s",
176 local, item->string);
179 return -1;
182 int install_branch_config(int flag, const char *local, const char *origin,
183 const char *remote)
185 int ret;
186 struct string_list remotes = STRING_LIST_INIT_DUP;
188 string_list_append(&remotes, remote);
189 ret = install_branch_config_multiple_remotes(flag, local, origin, &remotes);
190 string_list_clear(&remotes, 0);
191 return ret;
194 static int inherit_tracking(struct tracking *tracking, const char *orig_ref)
196 const char *bare_ref;
197 struct branch *branch;
198 int i;
200 bare_ref = orig_ref;
201 skip_prefix(orig_ref, "refs/heads/", &bare_ref);
203 branch = branch_get(bare_ref);
204 if (!branch->remote_name) {
205 warning(_("asked to inherit tracking from '%s', but no remote is set"),
206 bare_ref);
207 return -1;
210 if (branch->merge_nr < 1 || !branch->merge_name || !branch->merge_name[0]) {
211 warning(_("asked to inherit tracking from '%s', but no merge configuration is set"),
212 bare_ref);
213 return -1;
216 tracking->remote = xstrdup(branch->remote_name);
217 for (i = 0; i < branch->merge_nr; i++)
218 string_list_append(tracking->srcs, branch->merge_name[i]);
219 return 0;
223 * Used internally to set the branch.<new_ref>.{remote,merge} config
224 * settings so that branch 'new_ref' tracks 'orig_ref'. Unlike
225 * dwim_and_setup_tracking(), this does not do DWIM, i.e. "origin/main"
226 * will not be expanded to "refs/remotes/origin/main", so it is not safe
227 * for 'orig_ref' to be raw user input.
229 static void setup_tracking(const char *new_ref, const char *orig_ref,
230 enum branch_track track, int quiet)
232 struct tracking tracking;
233 struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
234 int config_flags = quiet ? 0 : BRANCH_CONFIG_VERBOSE;
236 memset(&tracking, 0, sizeof(tracking));
237 tracking.spec.dst = (char *)orig_ref;
238 tracking.srcs = &tracking_srcs;
239 if (track != BRANCH_TRACK_INHERIT)
240 for_each_remote(find_tracked_branch, &tracking);
241 else if (inherit_tracking(&tracking, orig_ref))
242 goto cleanup;
244 if (!tracking.matches)
245 switch (track) {
246 case BRANCH_TRACK_ALWAYS:
247 case BRANCH_TRACK_EXPLICIT:
248 case BRANCH_TRACK_OVERRIDE:
249 case BRANCH_TRACK_INHERIT:
250 break;
251 default:
252 goto cleanup;
255 if (tracking.matches > 1)
256 die(_("not tracking: ambiguous information for ref %s"),
257 orig_ref);
259 if (tracking.srcs->nr < 1)
260 string_list_append(tracking.srcs, orig_ref);
261 if (install_branch_config_multiple_remotes(config_flags, new_ref,
262 tracking.remote, tracking.srcs) < 0)
263 exit(-1);
265 cleanup:
266 string_list_clear(&tracking_srcs, 0);
269 int read_branch_desc(struct strbuf *buf, const char *branch_name)
271 char *v = NULL;
272 struct strbuf name = STRBUF_INIT;
273 strbuf_addf(&name, "branch.%s.description", branch_name);
274 if (git_config_get_string(name.buf, &v)) {
275 strbuf_release(&name);
276 return -1;
278 strbuf_addstr(buf, v);
279 free(v);
280 strbuf_release(&name);
281 return 0;
285 * Check if 'name' can be a valid name for a branch; die otherwise.
286 * Return 1 if the named branch already exists; return 0 otherwise.
287 * Fill ref with the full refname for the branch.
289 int validate_branchname(const char *name, struct strbuf *ref)
291 if (strbuf_check_branch_ref(ref, name))
292 die(_("'%s' is not a valid branch name"), name);
294 return ref_exists(ref->buf);
298 * Check if a branch 'name' can be created as a new branch; die otherwise.
299 * 'force' can be used when it is OK for the named branch already exists.
300 * Return 1 if the named branch already exists; return 0 otherwise.
301 * Fill ref with the full refname for the branch.
303 int validate_new_branchname(const char *name, struct strbuf *ref, int force)
305 struct worktree **worktrees;
306 const struct worktree *wt;
308 if (!validate_branchname(name, ref))
309 return 0;
311 if (!force)
312 die(_("a branch named '%s' already exists"),
313 ref->buf + strlen("refs/heads/"));
315 worktrees = get_worktrees();
316 wt = find_shared_symref(worktrees, "HEAD", ref->buf);
317 if (wt && !wt->is_bare)
318 die(_("cannot force update the branch '%s' "
319 "checked out at '%s'"),
320 ref->buf + strlen("refs/heads/"), wt->path);
321 free_worktrees(worktrees);
323 return 1;
326 static int check_tracking_branch(struct remote *remote, void *cb_data)
328 char *tracking_branch = cb_data;
329 struct refspec_item query;
330 memset(&query, 0, sizeof(struct refspec_item));
331 query.dst = tracking_branch;
332 return !remote_find_tracking(remote, &query);
335 static int validate_remote_tracking_branch(char *ref)
337 return !for_each_remote(check_tracking_branch, ref);
340 static const char upstream_not_branch[] =
341 N_("cannot set up tracking information; starting point '%s' is not a branch");
342 static const char upstream_missing[] =
343 N_("the requested upstream branch '%s' does not exist");
344 static const char upstream_advice[] =
345 N_("\n"
346 "If you are planning on basing your work on an upstream\n"
347 "branch that already exists at the remote, you may need to\n"
348 "run \"git fetch\" to retrieve it.\n"
349 "\n"
350 "If you are planning to push out a new local branch that\n"
351 "will track its remote counterpart, you may want to use\n"
352 "\"git push -u\" to set the upstream config as you push.");
355 * DWIMs a user-provided ref to determine the starting point for a
356 * branch and validates it, where:
358 * - r is the repository to validate the branch for
360 * - start_name is the ref that we would like to test. This is
361 * expanded with DWIM and assigned to out_real_ref.
363 * - track is the tracking mode of the new branch. If tracking is
364 * explicitly requested, start_name must be a branch (because
365 * otherwise start_name cannot be tracked)
367 * - out_oid is an out parameter containing the object_id of start_name
369 * - out_real_ref is an out parameter containing the full, 'real' form
370 * of start_name e.g. refs/heads/main instead of main
373 static void dwim_branch_start(struct repository *r, const char *start_name,
374 enum branch_track track, char **out_real_ref,
375 struct object_id *out_oid)
377 struct commit *commit;
378 struct object_id oid;
379 char *real_ref;
380 int explicit_tracking = 0;
382 if (track == BRANCH_TRACK_EXPLICIT || track == BRANCH_TRACK_OVERRIDE)
383 explicit_tracking = 1;
385 real_ref = NULL;
386 if (get_oid_mb(start_name, &oid)) {
387 if (explicit_tracking) {
388 if (advice_enabled(ADVICE_SET_UPSTREAM_FAILURE)) {
389 error(_(upstream_missing), start_name);
390 advise(_(upstream_advice));
391 exit(1);
393 die(_(upstream_missing), start_name);
395 die(_("not a valid object name: '%s'"), start_name);
398 switch (dwim_ref(start_name, strlen(start_name), &oid, &real_ref, 0)) {
399 case 0:
400 /* Not branching from any existing branch */
401 if (explicit_tracking)
402 die(_(upstream_not_branch), start_name);
403 break;
404 case 1:
405 /* Unique completion -- good, only if it is a real branch */
406 if (!starts_with(real_ref, "refs/heads/") &&
407 validate_remote_tracking_branch(real_ref)) {
408 if (explicit_tracking)
409 die(_(upstream_not_branch), start_name);
410 else
411 FREE_AND_NULL(real_ref);
413 break;
414 default:
415 die(_("ambiguous object name: '%s'"), start_name);
416 break;
419 if ((commit = lookup_commit_reference(r, &oid)) == NULL)
420 die(_("not a valid branch point: '%s'"), start_name);
421 if (out_real_ref) {
422 *out_real_ref = real_ref;
423 real_ref = NULL;
425 if (out_oid)
426 oidcpy(out_oid, &commit->object.oid);
428 FREE_AND_NULL(real_ref);
431 void create_branch(struct repository *r,
432 const char *name, const char *start_name,
433 int force, int clobber_head_ok, int reflog,
434 int quiet, enum branch_track track, int dry_run)
436 struct object_id oid;
437 char *real_ref;
438 struct strbuf ref = STRBUF_INIT;
439 int forcing = 0;
440 struct ref_transaction *transaction;
441 struct strbuf err = STRBUF_INIT;
442 char *msg;
444 if (track == BRANCH_TRACK_OVERRIDE)
445 BUG("'track' cannot be BRANCH_TRACK_OVERRIDE. Did you mean to call dwim_and_setup_tracking()?");
446 if (clobber_head_ok && !force)
447 BUG("'clobber_head_ok' can only be used with 'force'");
449 if (clobber_head_ok ?
450 validate_branchname(name, &ref) :
451 validate_new_branchname(name, &ref, force)) {
452 forcing = 1;
455 dwim_branch_start(r, start_name, track, &real_ref, &oid);
456 if (dry_run)
457 goto cleanup;
459 if (reflog)
460 log_all_ref_updates = LOG_REFS_NORMAL;
462 if (forcing)
463 msg = xstrfmt("branch: Reset to %s", start_name);
464 else
465 msg = xstrfmt("branch: Created from %s", start_name);
466 transaction = ref_transaction_begin(&err);
467 if (!transaction ||
468 ref_transaction_update(transaction, ref.buf,
469 &oid, forcing ? NULL : null_oid(),
470 0, msg, &err) ||
471 ref_transaction_commit(transaction, &err))
472 die("%s", err.buf);
473 ref_transaction_free(transaction);
474 strbuf_release(&err);
475 free(msg);
477 if (real_ref && track)
478 setup_tracking(ref.buf + 11, real_ref, track, quiet);
480 cleanup:
481 strbuf_release(&ref);
482 free(real_ref);
485 void dwim_and_setup_tracking(struct repository *r, const char *new_ref,
486 const char *orig_ref, enum branch_track track,
487 int quiet)
489 char *real_orig_ref;
490 dwim_branch_start(r, orig_ref, track, &real_orig_ref, NULL);
491 setup_tracking(new_ref, real_orig_ref, track, quiet);
495 * Creates a branch in a submodule by calling
496 * create_branches_recursively() in a child process. The child process
497 * is necessary because install_branch_config_multiple_remotes() (which
498 * is called by setup_tracking()) does not support writing configs to
499 * submodules.
501 static int submodule_create_branch(struct repository *r,
502 const struct submodule *submodule,
503 const char *name, const char *start_oid,
504 const char *tracking_name, int force,
505 int reflog, int quiet,
506 enum branch_track track, int dry_run)
508 int ret = 0;
509 struct child_process child = CHILD_PROCESS_INIT;
510 struct strbuf child_err = STRBUF_INIT;
511 struct strbuf out_buf = STRBUF_INIT;
512 char *out_prefix = xstrfmt("submodule '%s': ", submodule->name);
513 child.git_cmd = 1;
514 child.err = -1;
515 child.stdout_to_stderr = 1;
517 prepare_other_repo_env(&child.env_array, r->gitdir);
519 * submodule_create_branch() is indirectly invoked by "git
520 * branch", but we cannot invoke "git branch" in the child
521 * process. "git branch" accepts a branch name and start point,
522 * where the start point is assumed to provide both the OID
523 * (start_oid) and the branch to use for tracking
524 * (tracking_name). But when recursing through submodules,
525 * start_oid and tracking name need to be specified separately
526 * (see create_branches_recursively()).
528 strvec_pushl(&child.args, "submodule--helper", "create-branch", NULL);
529 if (dry_run)
530 strvec_push(&child.args, "--dry-run");
531 if (force)
532 strvec_push(&child.args, "--force");
533 if (quiet)
534 strvec_push(&child.args, "--quiet");
535 if (reflog)
536 strvec_push(&child.args, "--create-reflog");
537 if (track == BRANCH_TRACK_ALWAYS || track == BRANCH_TRACK_EXPLICIT)
538 strvec_push(&child.args, "--track");
540 strvec_pushl(&child.args, name, start_oid, tracking_name, NULL);
542 if ((ret = start_command(&child)))
543 return ret;
544 ret = finish_command(&child);
545 strbuf_read(&child_err, child.err, 0);
546 strbuf_add_lines(&out_buf, out_prefix, child_err.buf, child_err.len);
548 if (ret)
549 fprintf(stderr, "%s", out_buf.buf);
550 else
551 printf("%s", out_buf.buf);
553 strbuf_release(&child_err);
554 strbuf_release(&out_buf);
555 return ret;
558 void create_branches_recursively(struct repository *r, const char *name,
559 const char *start_commitish,
560 const char *tracking_name, int force,
561 int reflog, int quiet, enum branch_track track,
562 int dry_run)
564 int i = 0;
565 char *branch_point = NULL;
566 struct object_id super_oid;
567 struct submodule_entry_list submodule_entry_list;
569 /* Perform dwim on start_commitish to get super_oid and branch_point. */
570 dwim_branch_start(r, start_commitish, BRANCH_TRACK_NEVER,
571 &branch_point, &super_oid);
574 * If we were not given an explicit name to track, then assume we are at
575 * the top level and, just like the non-recursive case, the tracking
576 * name is the branch point.
578 if (!tracking_name)
579 tracking_name = branch_point;
581 submodules_of_tree(r, &super_oid, &submodule_entry_list);
583 * Before creating any branches, first check that the branch can
584 * be created in every submodule.
586 for (i = 0; i < submodule_entry_list.entry_nr; i++) {
587 if (submodule_entry_list.entries[i].repo == NULL) {
588 if (advice_enabled(ADVICE_SUBMODULES_NOT_UPDATED))
589 advise(_("You may try updating the submodules using 'git checkout %s && git submodule update --init'"),
590 start_commitish);
591 die(_("submodule '%s': unable to find submodule"),
592 submodule_entry_list.entries[i].submodule->name);
595 if (submodule_create_branch(
596 submodule_entry_list.entries[i].repo,
597 submodule_entry_list.entries[i].submodule, name,
598 oid_to_hex(&submodule_entry_list.entries[i]
599 .name_entry->oid),
600 tracking_name, force, reflog, quiet, track, 1))
601 die(_("submodule '%s': cannot create branch '%s'"),
602 submodule_entry_list.entries[i].submodule->name,
603 name);
606 create_branch(the_repository, name, start_commitish, force, 0, reflog, quiet,
607 BRANCH_TRACK_NEVER, dry_run);
608 if (dry_run)
609 return;
611 * NEEDSWORK If tracking was set up in the superproject but not the
612 * submodule, users might expect "git branch --recurse-submodules" to
613 * fail or give a warning, but this is not yet implemented because it is
614 * tedious to determine whether or not tracking was set up in the
615 * superproject.
617 setup_tracking(name, tracking_name, track, quiet);
619 for (i = 0; i < submodule_entry_list.entry_nr; i++) {
620 if (submodule_create_branch(
621 submodule_entry_list.entries[i].repo,
622 submodule_entry_list.entries[i].submodule, name,
623 oid_to_hex(&submodule_entry_list.entries[i]
624 .name_entry->oid),
625 tracking_name, force, reflog, quiet, track, 0))
626 die(_("submodule '%s': cannot create branch '%s'"),
627 submodule_entry_list.entries[i].submodule->name,
628 name);
629 repo_clear(submodule_entry_list.entries[i].repo);
633 void remove_merge_branch_state(struct repository *r)
635 unlink(git_path_merge_head(r));
636 unlink(git_path_merge_rr(r));
637 unlink(git_path_merge_msg(r));
638 unlink(git_path_merge_mode(r));
639 unlink(git_path_auto_merge(r));
640 save_autostash(git_path_merge_autostash(r));
643 void remove_branch_state(struct repository *r, int verbose)
645 sequencer_post_commit_cleanup(r, verbose);
646 unlink(git_path_squash_msg(r));
647 remove_merge_branch_state(r);
650 void die_if_checked_out(const char *branch, int ignore_current_worktree)
652 struct worktree **worktrees = get_worktrees();
653 const struct worktree *wt;
655 wt = find_shared_symref(worktrees, "HEAD", branch);
656 if (wt && (!ignore_current_worktree || !wt->is_current)) {
657 skip_prefix(branch, "refs/heads/", &branch);
658 die(_("'%s' is already checked out at '%s'"), branch, wt->path);
661 free_worktrees(worktrees);
664 int replace_each_worktree_head_symref(const char *oldref, const char *newref,
665 const char *logmsg)
667 int ret = 0;
668 struct worktree **worktrees = get_worktrees();
669 int i;
671 for (i = 0; worktrees[i]; i++) {
672 struct ref_store *refs;
674 if (worktrees[i]->is_detached)
675 continue;
676 if (!worktrees[i]->head_ref)
677 continue;
678 if (strcmp(oldref, worktrees[i]->head_ref))
679 continue;
681 refs = get_worktree_ref_store(worktrees[i]);
682 if (refs_create_symref(refs, "HEAD", newref, logmsg))
683 ret = error(_("HEAD of working tree %s is not updated"),
684 worktrees[i]->path);
687 free_worktrees(worktrees);
688 return ret;