blob: 7df982693af14f79a97b5c456a4416c3bd133a51 [file] [log] [blame]
Brian Gesiak303d1d02014-02-28 15:43:33 +09001#include "git-compat-util.h"
Elijah Newren6c6ddf92023-04-11 03:00:39 +00002#include "advice.h"
Brandon Williamsb2141fc2017-06-14 11:07:36 -07003#include "config.h"
Daniel Barkalowe496c002008-02-07 11:40:08 -05004#include "branch.h"
Elijah Newren32a8f512023-03-21 06:26:03 +00005#include "environment.h"
Elijah Newrenf394e092023-03-21 06:25:54 +00006#include "gettext.h"
Elijah Newren41771fa2023-02-24 00:09:27 +00007#include "hex.h"
Elijah Newrendabab1d2023-04-11 00:41:49 -07008#include "object-name.h"
Daniel Barkalowe496c002008-02-07 11:40:08 -05009#include "refs.h"
Brandon Williamsec0cb492018-05-16 15:57:48 -070010#include "refspec.h"
Daniel Barkalowe496c002008-02-07 11:40:08 -050011#include "remote.h"
Phillip Woodb07d9bf2019-04-16 11:18:41 +010012#include "sequencer.h"
Daniel Barkalowe496c002008-02-07 11:40:08 -050013#include "commit.h"
Michael Rappazzoac6c5612015-10-02 07:55:31 -040014#include "worktree.h"
Glen Choo961b1302022-01-28 16:04:45 -080015#include "submodule-config.h"
16#include "run-command.h"
Derrick Stolee31ad6b62022-06-14 19:27:29 +000017#include "strmap.h"
Daniel Barkalowe496c002008-02-07 11:40:08 -050018
19struct tracking {
Brandon Williams0ad4a5f2018-05-16 15:57:49 -070020 struct refspec_item spec;
Josh Steadmond3115662021-12-20 19:30:23 -080021 struct string_list *srcs;
Daniel Barkalowe496c002008-02-07 11:40:08 -050022 const char *remote;
23 int matches;
24};
25
Tao Klerkse4921d82022-04-01 06:05:13 +000026struct find_tracked_branch_cb {
27 struct tracking *tracking;
28 struct string_list ambiguous_remotes;
29};
30
Daniel Barkalowe496c002008-02-07 11:40:08 -050031static int find_tracked_branch(struct remote *remote, void *priv)
32{
Tao Klerkse4921d82022-04-01 06:05:13 +000033 struct find_tracked_branch_cb *ftb = priv;
34 struct tracking *tracking = ftb->tracking;
Daniel Barkalowe496c002008-02-07 11:40:08 -050035
36 if (!remote_find_tracking(remote, &tracking->spec)) {
Tao Klerkse4921d82022-04-01 06:05:13 +000037 switch (++tracking->matches) {
38 case 1:
Josh Steadmond3115662021-12-20 19:30:23 -080039 string_list_append(tracking->srcs, tracking->spec.src);
Daniel Barkalowe496c002008-02-07 11:40:08 -050040 tracking->remote = remote->name;
Tao Klerkse4921d82022-04-01 06:05:13 +000041 break;
42 case 2:
43 /* there are at least two remotes; backfill the first one */
44 string_list_append(&ftb->ambiguous_remotes, tracking->remote);
45 /* fall through */
46 default:
47 string_list_append(&ftb->ambiguous_remotes, remote->name);
Daniel Barkalowe496c002008-02-07 11:40:08 -050048 free(tracking->spec.src);
Josh Steadmond3115662021-12-20 19:30:23 -080049 string_list_clear(tracking->srcs, 0);
Tao Klerkse4921d82022-04-01 06:05:13 +000050 break;
Daniel Barkalowe496c002008-02-07 11:40:08 -050051 }
Tao Klerksbdaf1df2022-04-29 09:56:44 +000052 /* remote_find_tracking() searches by src if present */
Daniel Barkalowe496c002008-02-07 11:40:08 -050053 tracking->spec.src = NULL;
54 }
Daniel Barkalowe496c002008-02-07 11:40:08 -050055 return 0;
56}
57
Junio C Hamanoa9f2c132009-03-03 22:29:55 -080058static int should_setup_rebase(const char *origin)
Dustin Sallingsc998ae92008-05-10 15:36:29 -070059{
60 switch (autorebase) {
61 case AUTOREBASE_NEVER:
62 return 0;
63 case AUTOREBASE_LOCAL:
Junio C Hamanoa9f2c132009-03-03 22:29:55 -080064 return origin == NULL;
Dustin Sallingsc998ae92008-05-10 15:36:29 -070065 case AUTOREBASE_REMOTE:
Junio C Hamanoa9f2c132009-03-03 22:29:55 -080066 return origin != NULL;
Dustin Sallingsc998ae92008-05-10 15:36:29 -070067 case AUTOREBASE_ALWAYS:
68 return 1;
69 }
70 return 0;
71}
72
Josh Steadmona3f40ec2021-12-20 19:30:22 -080073/**
74 * Install upstream tracking configuration for a branch; specifically, add
75 * `branch.<name>.remote` and `branch.<name>.merge` entries.
76 *
77 * `flag` contains integer flags for options; currently only
78 * BRANCH_CONFIG_VERBOSE is checked.
79 *
80 * `local` is the name of the branch whose configuration we're installing.
81 *
82 * `origin` is the name of the remote owning the upstream branches. NULL means
83 * the upstream branches are local to this repo.
84 *
85 * `remotes` is a list of refs that are upstream of local
86 */
87static int install_branch_config_multiple_remotes(int flag, const char *local,
88 const char *origin, struct string_list *remotes)
Junio C Hamanoa9f2c132009-03-03 22:29:55 -080089{
Jeff Kingcf4fff52014-06-18 15:44:19 -040090 const char *shortname = NULL;
Junio C Hamanoa9f2c132009-03-03 22:29:55 -080091 struct strbuf key = STRBUF_INIT;
Josh Steadmona3f40ec2021-12-20 19:30:22 -080092 struct string_list_item *item;
Junio C Hamanoa9f2c132009-03-03 22:29:55 -080093 int rebasing = should_setup_rebase(origin);
94
Josh Steadmona3f40ec2021-12-20 19:30:22 -080095 if (!remotes->nr)
96 BUG("must provide at least one remote for branch config");
97 if (rebasing && remotes->nr > 1)
98 die(_("cannot inherit upstream tracking configuration of "
99 "multiple refs when rebasing is requested"));
100
101 /*
102 * If the new branch is trying to track itself, something has gone
103 * wrong. Warn the user and don't proceed any further.
104 */
105 if (!origin)
106 for_each_string_list_item(item, remotes)
107 if (skip_prefix(item->string, "refs/heads/", &shortname)
108 && !strcmp(local, shortname)) {
Junio C Hamano0669bdf2022-01-10 11:52:54 -0800109 warning(_("not setting branch '%s' as its own upstream"),
Josh Steadmona3f40ec2021-12-20 19:30:22 -0800110 local);
111 return 0;
112 }
Matthieu Moy85e22332010-01-18 22:44:12 +0200113
Junio C Hamanoa9f2c132009-03-03 22:29:55 -0800114 strbuf_addf(&key, "branch.%s.remote", local);
Patrick Steinhardt30598ad2016-02-22 12:23:35 +0100115 if (git_config_set_gently(key.buf, origin ? origin : ".") < 0)
Patrick Steinhardt27852b22016-02-22 12:23:23 +0100116 goto out_err;
Junio C Hamanoa9f2c132009-03-03 22:29:55 -0800117
118 strbuf_reset(&key);
119 strbuf_addf(&key, "branch.%s.merge", local);
Josh Steadmona3f40ec2021-12-20 19:30:22 -0800120 /*
121 * We want to overwrite any existing config with all the branches in
122 * "remotes". Override any existing config, then write our branches. If
123 * more than one is provided, use CONFIG_REGEX_NONE to preserve what
124 * we've written so far.
125 */
126 if (git_config_set_gently(key.buf, NULL) < 0)
Patrick Steinhardt27852b22016-02-22 12:23:23 +0100127 goto out_err;
Josh Steadmona3f40ec2021-12-20 19:30:22 -0800128 for_each_string_list_item(item, remotes)
129 if (git_config_set_multivar_gently(key.buf, item->string, CONFIG_REGEX_NONE, 0) < 0)
130 goto out_err;
Junio C Hamanoa9f2c132009-03-03 22:29:55 -0800131
132 if (rebasing) {
133 strbuf_reset(&key);
134 strbuf_addf(&key, "branch.%s.rebase", local);
Patrick Steinhardt30598ad2016-02-22 12:23:35 +0100135 if (git_config_set_gently(key.buf, "true") < 0)
Patrick Steinhardt27852b22016-02-22 12:23:23 +0100136 goto out_err;
Junio C Hamanoa9f2c132009-03-03 22:29:55 -0800137 }
Nguyễn Thái Ngọc Duyd53a35032012-06-07 19:05:10 +0700138 strbuf_release(&key);
Junio C Hamanoa9f2c132009-03-03 22:29:55 -0800139
Junio C Hamano72f60082009-03-10 01:20:42 -0700140 if (flag & BRANCH_CONFIG_VERBOSE) {
Josh Steadmona3f40ec2021-12-20 19:30:22 -0800141 struct strbuf tmp_ref_name = STRBUF_INIT;
142 struct string_list friendly_ref_names = STRING_LIST_INIT_DUP;
143
144 for_each_string_list_item(item, remotes) {
145 shortname = item->string;
146 skip_prefix(shortname, "refs/heads/", &shortname);
147 if (origin) {
148 strbuf_addf(&tmp_ref_name, "%s/%s",
149 origin, shortname);
150 string_list_append_nodup(
151 &friendly_ref_names,
152 strbuf_detach(&tmp_ref_name, NULL));
153 } else {
154 string_list_append(
155 &friendly_ref_names, shortname);
156 }
Adam9fe0cf32014-03-10 01:32:01 -0400157 }
Josh Steadmona3f40ec2021-12-20 19:30:22 -0800158
159 if (remotes->nr == 1) {
160 /*
161 * Rebasing is only allowed in the case of a single
162 * upstream branch.
163 */
164 printf_ln(rebasing ?
165 _("branch '%s' set up to track '%s' by rebasing.") :
166 _("branch '%s' set up to track '%s'."),
167 local, friendly_ref_names.items[0].string);
168 } else {
169 printf_ln(_("branch '%s' set up to track:"), local);
170 for_each_string_list_item(item, &friendly_ref_names)
171 printf_ln(" %s", item->string);
172 }
173
174 string_list_clear(&friendly_ref_names, 0);
Junio C Hamano72f60082009-03-10 01:20:42 -0700175 }
Patrick Steinhardt27852b22016-02-22 12:23:23 +0100176
177 return 0;
178
179out_err:
180 strbuf_release(&key);
Anders Kaseorg7435e7e2021-12-01 14:15:42 -0800181 error(_("unable to write upstream branch configuration"));
Patrick Steinhardt27852b22016-02-22 12:23:23 +0100182
Josh Steadmona3f40ec2021-12-20 19:30:22 -0800183 advise(_("\nAfter fixing the error cause you may try to fix up\n"
184 "the remote tracking information by invoking:"));
185 if (remotes->nr == 1)
186 advise(" git branch --set-upstream-to=%s%s%s",
187 origin ? origin : "",
188 origin ? "/" : "",
189 remotes->items[0].string);
190 else {
191 advise(" git config --add branch.\"%s\".remote %s",
192 local, origin ? origin : ".");
193 for_each_string_list_item(item, remotes)
194 advise(" git config --add branch.\"%s\".merge %s",
195 local, item->string);
196 }
Patrick Steinhardt27852b22016-02-22 12:23:23 +0100197
198 return -1;
Junio C Hamanoa9f2c132009-03-03 22:29:55 -0800199}
200
Josh Steadmona3f40ec2021-12-20 19:30:22 -0800201int install_branch_config(int flag, const char *local, const char *origin,
202 const char *remote)
203{
204 int ret;
205 struct string_list remotes = STRING_LIST_INIT_DUP;
206
207 string_list_append(&remotes, remote);
208 ret = install_branch_config_multiple_remotes(flag, local, origin, &remotes);
209 string_list_clear(&remotes, 0);
210 return ret;
211}
212
Josh Steadmond3115662021-12-20 19:30:23 -0800213static int inherit_tracking(struct tracking *tracking, const char *orig_ref)
214{
215 const char *bare_ref;
216 struct branch *branch;
217 int i;
218
219 bare_ref = orig_ref;
220 skip_prefix(orig_ref, "refs/heads/", &bare_ref);
221
222 branch = branch_get(bare_ref);
223 if (!branch->remote_name) {
224 warning(_("asked to inherit tracking from '%s', but no remote is set"),
225 bare_ref);
226 return -1;
227 }
228
229 if (branch->merge_nr < 1 || !branch->merge_name || !branch->merge_name[0]) {
230 warning(_("asked to inherit tracking from '%s', but no merge configuration is set"),
231 bare_ref);
232 return -1;
233 }
234
235 tracking->remote = xstrdup(branch->remote_name);
236 for (i = 0; i < branch->merge_nr; i++)
237 string_list_append(tracking->srcs, branch->merge_name[i]);
238 return 0;
239}
240
Daniel Barkalowe496c002008-02-07 11:40:08 -0500241/*
Glen Chooe89f1512022-01-28 16:04:41 -0800242 * Used internally to set the branch.<new_ref>.{remote,merge} config
243 * settings so that branch 'new_ref' tracks 'orig_ref'. Unlike
244 * dwim_and_setup_tracking(), this does not do DWIM, i.e. "origin/main"
245 * will not be expanded to "refs/remotes/origin/main", so it is not safe
246 * for 'orig_ref' to be raw user input.
Daniel Barkalowe496c002008-02-07 11:40:08 -0500247 */
Patrick Steinhardt27852b22016-02-22 12:23:23 +0100248static void setup_tracking(const char *new_ref, const char *orig_ref,
249 enum branch_track track, int quiet)
Daniel Barkalowe496c002008-02-07 11:40:08 -0500250{
Daniel Barkalowe496c002008-02-07 11:40:08 -0500251 struct tracking tracking;
Josh Steadmond3115662021-12-20 19:30:23 -0800252 struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
Jeff Kingf9a482e2012-03-26 19:51:01 -0400253 int config_flags = quiet ? 0 : BRANCH_CONFIG_VERBOSE;
Tao Klerkse4921d82022-04-01 06:05:13 +0000254 struct find_tracked_branch_cb ftb_cb = {
255 .tracking = &tracking,
256 .ambiguous_remotes = STRING_LIST_INIT_DUP,
257 };
Daniel Barkalowe496c002008-02-07 11:40:08 -0500258
Glen Choo75388bf2022-03-29 20:01:16 +0000259 if (!track)
260 BUG("asked to set up tracking, but tracking is disallowed");
261
Daniel Barkalowe496c002008-02-07 11:40:08 -0500262 memset(&tracking, 0, sizeof(tracking));
263 tracking.spec.dst = (char *)orig_ref;
Josh Steadmond3115662021-12-20 19:30:23 -0800264 tracking.srcs = &tracking_srcs;
265 if (track != BRANCH_TRACK_INHERIT)
Tao Klerkse4921d82022-04-01 06:05:13 +0000266 for_each_remote(find_tracked_branch, &ftb_cb);
Josh Steadmond3115662021-12-20 19:30:23 -0800267 else if (inherit_tracking(&tracking, orig_ref))
Glen Choo679e3692022-01-28 16:04:46 -0800268 goto cleanup;
Daniel Barkalowe496c002008-02-07 11:40:08 -0500269
Jay Soffian9ed36cf2008-02-19 11:24:37 -0500270 if (!tracking.matches)
271 switch (track) {
Tao Klerksbdaf1df2022-04-29 09:56:44 +0000272 /* If ref is not remote, still use local */
Jay Soffian9ed36cf2008-02-19 11:24:37 -0500273 case BRANCH_TRACK_ALWAYS:
274 case BRANCH_TRACK_EXPLICIT:
Ilari Liusvaara4fc50062010-01-18 22:44:11 +0200275 case BRANCH_TRACK_OVERRIDE:
Tao Klerksbdaf1df2022-04-29 09:56:44 +0000276 /* Remote matches not evaluated */
Josh Steadmond3115662021-12-20 19:30:23 -0800277 case BRANCH_TRACK_INHERIT:
Jay Soffian9ed36cf2008-02-19 11:24:37 -0500278 break;
Tao Klerksbdaf1df2022-04-29 09:56:44 +0000279 /* Otherwise, if no remote don't track */
Jay Soffian9ed36cf2008-02-19 11:24:37 -0500280 default:
Glen Choo679e3692022-01-28 16:04:46 -0800281 goto cleanup;
Jay Soffian9ed36cf2008-02-19 11:24:37 -0500282 }
283
Tao Klerksbdaf1df2022-04-29 09:56:44 +0000284 /*
285 * This check does not apply to BRANCH_TRACK_INHERIT;
286 * that supports multiple entries in tracking_srcs but
287 * leaves tracking.matches at 0.
288 */
Tao Klerkse4921d82022-04-01 06:05:13 +0000289 if (tracking.matches > 1) {
290 int status = die_message(_("not tracking: ambiguous information for ref '%s'"),
291 orig_ref);
292 if (advice_enabled(ADVICE_AMBIGUOUS_FETCH_REFSPEC)) {
293 struct strbuf remotes_advice = STRBUF_INIT;
294 struct string_list_item *item;
295
296 for_each_string_list_item(item, &ftb_cb.ambiguous_remotes)
297 /*
298 * TRANSLATORS: This is a line listing a remote with duplicate
299 * refspecs in the advice message below. For RTL languages you'll
300 * probably want to swap the "%s" and leading " " space around.
301 */
302 strbuf_addf(&remotes_advice, _(" %s\n"), item->string);
303
304 /*
305 * TRANSLATORS: The second argument is a \n-delimited list of
306 * duplicate refspecs, composed above.
307 */
308 advise(_("There are multiple remotes whose fetch refspecs map to the remote\n"
309 "tracking ref '%s':\n"
310 "%s"
311 "\n"
312 "This is typically a configuration error.\n"
313 "\n"
314 "To support setting up tracking branches, ensure that\n"
315 "different remotes' fetch refspecs map into different\n"
316 "tracking namespaces."), orig_ref,
317 remotes_advice.buf);
318 strbuf_release(&remotes_advice);
319 }
320 exit(status);
321 }
Daniel Barkalowe496c002008-02-07 11:40:08 -0500322
Tao Klerksbdaf1df2022-04-29 09:56:44 +0000323 if (track == BRANCH_TRACK_SIMPLE) {
324 /*
325 * Only track if remote branch name matches.
326 * Reaching into items[0].string is safe because
327 * we know there is at least one and not more than
328 * one entry (because only BRANCH_TRACK_INHERIT can
329 * produce more than one entry).
330 */
331 const char *tracked_branch;
332 if (!skip_prefix(tracking.srcs->items[0].string,
333 "refs/heads/", &tracked_branch) ||
334 strcmp(tracked_branch, new_ref))
335 return;
336 }
337
Josh Steadmond3115662021-12-20 19:30:23 -0800338 if (tracking.srcs->nr < 1)
339 string_list_append(tracking.srcs, orig_ref);
340 if (install_branch_config_multiple_remotes(config_flags, new_ref,
341 tracking.remote, tracking.srcs) < 0)
Glen Choo5391e942022-03-29 20:01:19 +0000342 exit(1);
Daniel Barkalowe496c002008-02-07 11:40:08 -0500343
Glen Choo679e3692022-01-28 16:04:46 -0800344cleanup:
345 string_list_clear(&tracking_srcs, 0);
Tao Klerkse4921d82022-04-01 06:05:13 +0000346 string_list_clear(&ftb_cb.ambiguous_remotes, 0);
Daniel Barkalowe496c002008-02-07 11:40:08 -0500347}
348
Junio C Hamano6f9a3322011-09-21 20:19:38 -0700349int read_branch_desc(struct strbuf *buf, const char *branch_name)
350{
Tanay Abhra540b0f42014-08-07 23:26:42 +0530351 char *v = NULL;
Junio C Hamano6f9a3322011-09-21 20:19:38 -0700352 struct strbuf name = STRBUF_INIT;
353 strbuf_addf(&name, "branch.%s.description", branch_name);
Tanay Abhra540b0f42014-08-07 23:26:42 +0530354 if (git_config_get_string(name.buf, &v)) {
355 strbuf_release(&name);
356 return -1;
357 }
358 strbuf_addstr(buf, v);
359 free(v);
Junio C Hamano6f9a3322011-09-21 20:19:38 -0700360 strbuf_release(&name);
361 return 0;
362}
363
Junio C Hamanobc1c9c02017-10-13 13:45:40 +0900364/*
365 * Check if 'name' can be a valid name for a branch; die otherwise.
366 * Return 1 if the named branch already exists; return 0 otherwise.
367 * Fill ref with the full refname for the branch.
368 */
369int validate_branchname(const char *name, struct strbuf *ref)
Conrad Irwin55c4a672011-08-20 14:49:48 -0700370{
Conrad Irwin55c4a672011-08-20 14:49:48 -0700371 if (strbuf_check_branch_ref(ref, name))
Anders Kaseorg7435e7e2021-12-01 14:15:42 -0800372 die(_("'%s' is not a valid branch name"), name);
Conrad Irwin55c4a672011-08-20 14:49:48 -0700373
Junio C Hamanobc1c9c02017-10-13 13:45:40 +0900374 return ref_exists(ref->buf);
375}
Conrad Irwin55c4a672011-08-20 14:49:48 -0700376
Derrick Stolee31ad6b62022-06-14 19:27:29 +0000377static int initialized_checked_out_branches;
378static struct strmap current_checked_out_branches = STRMAP_INIT;
379
380static void prepare_checked_out_branches(void)
381{
382 int i = 0;
383 struct worktree **worktrees;
384
385 if (initialized_checked_out_branches)
386 return;
387 initialized_checked_out_branches = 1;
388
389 worktrees = get_worktrees();
390
391 while (worktrees[i]) {
Derrick Stolee4b6e18f2022-06-14 19:27:33 +0000392 char *old;
Derrick Stoleed2ba2712022-06-14 19:27:30 +0000393 struct wt_status_state state = { 0 };
Derrick Stolee31ad6b62022-06-14 19:27:29 +0000394 struct worktree *wt = worktrees[i++];
Derrick Stoleeaa7f2fd2022-07-19 18:33:35 +0000395 struct string_list update_refs = STRING_LIST_INIT_DUP;
Derrick Stolee31ad6b62022-06-14 19:27:29 +0000396
397 if (wt->is_bare)
398 continue;
399
Derrick Stolee4b6e18f2022-06-14 19:27:33 +0000400 if (wt->head_ref) {
401 old = strmap_put(&current_checked_out_branches,
402 wt->head_ref,
403 xstrdup(wt->path));
404 free(old);
405 }
Derrick Stoleed2ba2712022-06-14 19:27:30 +0000406
407 if (wt_status_check_rebase(wt, &state) &&
408 (state.rebase_in_progress || state.rebase_interactive_in_progress) &&
409 state.branch) {
410 struct strbuf ref = STRBUF_INIT;
411 strbuf_addf(&ref, "refs/heads/%s", state.branch);
Derrick Stolee4b6e18f2022-06-14 19:27:33 +0000412 old = strmap_put(&current_checked_out_branches,
413 ref.buf,
414 xstrdup(wt->path));
415 free(old);
Derrick Stoleed2ba2712022-06-14 19:27:30 +0000416 strbuf_release(&ref);
417 }
418 wt_status_state_free_buffers(&state);
419
420 if (wt_status_check_bisect(wt, &state) &&
421 state.branch) {
422 struct strbuf ref = STRBUF_INIT;
423 strbuf_addf(&ref, "refs/heads/%s", state.branch);
Derrick Stolee4b6e18f2022-06-14 19:27:33 +0000424 old = strmap_put(&current_checked_out_branches,
425 ref.buf,
426 xstrdup(wt->path));
427 free(old);
Derrick Stoleed2ba2712022-06-14 19:27:30 +0000428 strbuf_release(&ref);
429 }
430 wt_status_state_free_buffers(&state);
Derrick Stoleeaa7f2fd2022-07-19 18:33:35 +0000431
432 if (!sequencer_get_update_refs_state(get_worktree_git_dir(wt),
433 &update_refs)) {
434 struct string_list_item *item;
435 for_each_string_list_item(item, &update_refs) {
436 old = strmap_put(&current_checked_out_branches,
437 item->string,
438 xstrdup(wt->path));
439 free(old);
440 }
441 string_list_clear(&update_refs, 1);
442 }
Derrick Stolee31ad6b62022-06-14 19:27:29 +0000443 }
444
445 free_worktrees(worktrees);
446}
447
448const char *branch_checked_out(const char *refname)
449{
450 prepare_checked_out_branches();
451 return strmap_get(&current_checked_out_branches, refname);
452}
453
Junio C Hamanobc1c9c02017-10-13 13:45:40 +0900454/*
455 * Check if a branch 'name' can be created as a new branch; die otherwise.
456 * 'force' can be used when it is OK for the named branch already exists.
457 * Return 1 if the named branch already exists; return 0 otherwise.
458 * Fill ref with the full refname for the branch.
459 */
460int validate_new_branchname(const char *name, struct strbuf *ref, int force)
461{
Derrick Stoleed2ba2712022-06-14 19:27:30 +0000462 const char *path;
Junio C Hamanobc1c9c02017-10-13 13:45:40 +0900463 if (!validate_branchname(name, ref))
Conrad Irwin55c4a672011-08-20 14:49:48 -0700464 return 0;
Conrad Irwin55c4a672011-08-20 14:49:48 -0700465
Junio C Hamano8280c4c2017-10-13 12:57:02 +0900466 if (!force)
Anders Kaseorg7435e7e2021-12-01 14:15:42 -0800467 die(_("a branch named '%s' already exists"),
Junio C Hamano8280c4c2017-10-13 12:57:02 +0900468 ref->buf + strlen("refs/heads/"));
Conrad Irwin55c4a672011-08-20 14:49:48 -0700469
Derrick Stoleed2ba2712022-06-14 19:27:30 +0000470 if ((path = branch_checked_out(ref->buf)))
Bagas Sanjaya68d924e2022-01-11 19:36:27 +0700471 die(_("cannot force update the branch '%s' "
Anders Kaseorg593a2a52021-12-01 14:15:47 -0800472 "checked out at '%s'"),
Derrick Stoleed2ba2712022-06-14 19:27:30 +0000473 ref->buf + strlen("refs/heads/"), path);
Junio C Hamano8280c4c2017-10-13 12:57:02 +0900474
Conrad Irwin55c4a672011-08-20 14:49:48 -0700475 return 1;
476}
477
Johan Herland41c21f22013-04-21 23:52:05 +0200478static int check_tracking_branch(struct remote *remote, void *cb_data)
479{
480 char *tracking_branch = cb_data;
Brandon Williams0ad4a5f2018-05-16 15:57:49 -0700481 struct refspec_item query;
482 memset(&query, 0, sizeof(struct refspec_item));
Johan Herland41c21f22013-04-21 23:52:05 +0200483 query.dst = tracking_branch;
Per Cederqvist1d7358c2013-09-08 22:58:15 +0200484 return !remote_find_tracking(remote, &query);
Johan Herland41c21f22013-04-21 23:52:05 +0200485}
486
487static int validate_remote_tracking_branch(char *ref)
488{
489 return !for_each_remote(check_tracking_branch, ref);
490}
491
Jeff Kinge2b6aa52013-04-02 15:03:55 -0400492static const char upstream_not_branch[] =
Anders Kaseorg7435e7e2021-12-01 14:15:42 -0800493N_("cannot set up tracking information; starting point '%s' is not a branch");
Jeff Kinga5e91c72013-04-02 15:04:27 -0400494static const char upstream_missing[] =
Jeff Kingcaa20362013-04-02 15:05:12 -0400495N_("the requested upstream branch '%s' does not exist");
496static const char upstream_advice[] =
497N_("\n"
498"If you are planning on basing your work on an upstream\n"
499"branch that already exists at the remote, you may need to\n"
500"run \"git fetch\" to retrieve it.\n"
501"\n"
502"If you are planning to push out a new local branch that\n"
503"will track its remote counterpart, you may want to use\n"
504"\"git push -u\" to set the upstream config as you push.");
Jeff Kinge2b6aa52013-04-02 15:03:55 -0400505
Glen Chooe89f1512022-01-28 16:04:41 -0800506/**
507 * DWIMs a user-provided ref to determine the starting point for a
508 * branch and validates it, where:
509 *
510 * - r is the repository to validate the branch for
511 *
512 * - start_name is the ref that we would like to test. This is
513 * expanded with DWIM and assigned to out_real_ref.
514 *
515 * - track is the tracking mode of the new branch. If tracking is
516 * explicitly requested, start_name must be a branch (because
517 * otherwise start_name cannot be tracked)
518 *
519 * - out_oid is an out parameter containing the object_id of start_name
520 *
521 * - out_real_ref is an out parameter containing the full, 'real' form
522 * of start_name e.g. refs/heads/main instead of main
523 *
524 */
525static void dwim_branch_start(struct repository *r, const char *start_name,
526 enum branch_track track, char **out_real_ref,
527 struct object_id *out_oid)
Daniel Barkalowe496c002008-02-07 11:40:08 -0500528{
Daniel Barkalowe496c002008-02-07 11:40:08 -0500529 struct commit *commit;
brian m. carlson48713bf2017-05-01 02:29:00 +0000530 struct object_id oid;
Jeff King3818b252017-03-28 15:46:36 -0400531 char *real_ref;
Ilari Liusvaara4fc50062010-01-18 22:44:11 +0200532 int explicit_tracking = 0;
533
534 if (track == BRANCH_TRACK_EXPLICIT || track == BRANCH_TRACK_OVERRIDE)
535 explicit_tracking = 1;
Daniel Barkalowe496c002008-02-07 11:40:08 -0500536
Daniel Barkalowe496c002008-02-07 11:40:08 -0500537 real_ref = NULL;
Ævar Arnfjörð Bjarmason4a93b892023-03-28 15:58:58 +0200538 if (repo_get_oid_mb(r, start_name, &oid)) {
Jeff Kingcaa20362013-04-02 15:05:12 -0400539 if (explicit_tracking) {
Glen Choo66966012022-03-31 15:41:18 -0700540 int code = die_message(_(upstream_missing), start_name);
541 advise_if_enabled(ADVICE_SET_UPSTREAM_FAILURE,
542 _(upstream_advice));
543 exit(code);
Jeff Kingcaa20362013-04-02 15:05:12 -0400544 }
Anders Kaseorg7435e7e2021-12-01 14:15:42 -0800545 die(_("not a valid object name: '%s'"), start_name);
Jeff Kinga5e91c72013-04-02 15:04:27 -0400546 }
Daniel Barkalowe496c002008-02-07 11:40:08 -0500547
Ævar Arnfjörð Bjarmason4a93b892023-03-28 15:58:58 +0200548 switch (repo_dwim_ref(r, start_name, strlen(start_name), &oid,
549 &real_ref, 0)) {
Daniel Barkalowe496c002008-02-07 11:40:08 -0500550 case 0:
551 /* Not branching from any existing branch */
Ilari Liusvaara4fc50062010-01-18 22:44:11 +0200552 if (explicit_tracking)
Jeff King1a15d002013-04-02 15:04:51 -0400553 die(_(upstream_not_branch), start_name);
Daniel Barkalowe496c002008-02-07 11:40:08 -0500554 break;
555 case 1:
Johan Herland21b5b1e2011-02-17 00:12:20 +0100556 /* Unique completion -- good, only if it is a real branch */
Christian Couder59556542013-11-30 21:55:40 +0100557 if (!starts_with(real_ref, "refs/heads/") &&
Johan Herland41c21f22013-04-21 23:52:05 +0200558 validate_remote_tracking_branch(real_ref)) {
Johan Herland21b5b1e2011-02-17 00:12:20 +0100559 if (explicit_tracking)
Jeff King1a15d002013-04-02 15:04:51 -0400560 die(_(upstream_not_branch), start_name);
Johan Herland21b5b1e2011-02-17 00:12:20 +0100561 else
Andrzej Huntd8958042021-04-25 14:16:12 +0000562 FREE_AND_NULL(real_ref);
Johan Herland21b5b1e2011-02-17 00:12:20 +0100563 }
Daniel Barkalowe496c002008-02-07 11:40:08 -0500564 break;
565 default:
Anders Kaseorg7435e7e2021-12-01 14:15:42 -0800566 die(_("ambiguous object name: '%s'"), start_name);
Daniel Barkalowe496c002008-02-07 11:40:08 -0500567 break;
568 }
569
Junio C Hamanoafe8a902022-05-02 09:50:37 -0700570 if (!(commit = lookup_commit_reference(r, &oid)))
Anders Kaseorg7435e7e2021-12-01 14:15:42 -0800571 die(_("not a valid branch point: '%s'"), start_name);
Glen Chooe89f1512022-01-28 16:04:41 -0800572 if (out_real_ref) {
573 *out_real_ref = real_ref;
574 real_ref = NULL;
575 }
576 if (out_oid)
577 oidcpy(out_oid, &commit->object.oid);
578
579 FREE_AND_NULL(real_ref);
580}
581
582void create_branch(struct repository *r,
583 const char *name, const char *start_name,
584 int force, int clobber_head_ok, int reflog,
Glen Choo3f3e7602022-01-28 16:04:43 -0800585 int quiet, enum branch_track track, int dry_run)
Glen Chooe89f1512022-01-28 16:04:41 -0800586{
587 struct object_id oid;
588 char *real_ref;
589 struct strbuf ref = STRBUF_INIT;
590 int forcing = 0;
Glen Choobc0893c2022-01-28 16:04:42 -0800591 struct ref_transaction *transaction;
592 struct strbuf err = STRBUF_INIT;
593 char *msg;
Glen Chooe89f1512022-01-28 16:04:41 -0800594
Glen Choobc0893c2022-01-28 16:04:42 -0800595 if (track == BRANCH_TRACK_OVERRIDE)
596 BUG("'track' cannot be BRANCH_TRACK_OVERRIDE. Did you mean to call dwim_and_setup_tracking()?");
597 if (clobber_head_ok && !force)
598 BUG("'clobber_head_ok' can only be used with 'force'");
599
600 if (clobber_head_ok ?
601 validate_branchname(name, &ref) :
602 validate_new_branchname(name, &ref, force)) {
603 forcing = 1;
Glen Chooe89f1512022-01-28 16:04:41 -0800604 }
605
606 dwim_branch_start(r, start_name, track, &real_ref, &oid);
Glen Choo3f3e7602022-01-28 16:04:43 -0800607 if (dry_run)
608 goto cleanup;
Daniel Barkalowe496c002008-02-07 11:40:08 -0500609
Ronnie Sahlbergd43f9902014-04-16 16:21:53 -0700610 if (reflog)
Cornelius Weig341fb282017-01-27 11:09:47 +0100611 log_all_ref_updates = LOG_REFS_NORMAL;
Ronnie Sahlbergd43f9902014-04-16 16:21:53 -0700612
Glen Choobc0893c2022-01-28 16:04:42 -0800613 if (forcing)
614 msg = xstrfmt("branch: Reset to %s", start_name);
615 else
616 msg = xstrfmt("branch: Created from %s", start_name);
617 transaction = ref_transaction_begin(&err);
618 if (!transaction ||
619 ref_transaction_update(transaction, ref.buf,
620 &oid, forcing ? NULL : null_oid(),
621 0, msg, &err) ||
622 ref_transaction_commit(transaction, &err))
623 die("%s", err.buf);
624 ref_transaction_free(transaction);
625 strbuf_release(&err);
626 free(msg);
Ronnie Sahlbergd43f9902014-04-16 16:21:53 -0700627
Daniel Barkalowe496c002008-02-07 11:40:08 -0500628 if (real_ref && track)
Felipe Contreras82a06722013-08-30 16:56:46 -0500629 setup_tracking(ref.buf + 11, real_ref, track, quiet);
Daniel Barkalowe496c002008-02-07 11:40:08 -0500630
Glen Choo3f3e7602022-01-28 16:04:43 -0800631cleanup:
Junio C Hamano8415d5c2009-02-13 23:08:05 -0800632 strbuf_release(&ref);
Jay Soffian9ed36cf2008-02-19 11:24:37 -0500633 free(real_ref);
Daniel Barkalowe496c002008-02-07 11:40:08 -0500634}
Daniel Barkalowc369e7b2008-02-07 11:40:16 -0500635
Glen Chooe89f1512022-01-28 16:04:41 -0800636void dwim_and_setup_tracking(struct repository *r, const char *new_ref,
637 const char *orig_ref, enum branch_track track,
638 int quiet)
639{
640 char *real_orig_ref;
641 dwim_branch_start(r, orig_ref, track, &real_orig_ref, NULL);
642 setup_tracking(new_ref, real_orig_ref, track, quiet);
643}
644
Glen Choo961b1302022-01-28 16:04:45 -0800645/**
646 * Creates a branch in a submodule by calling
647 * create_branches_recursively() in a child process. The child process
648 * is necessary because install_branch_config_multiple_remotes() (which
649 * is called by setup_tracking()) does not support writing configs to
650 * submodules.
651 */
652static int submodule_create_branch(struct repository *r,
653 const struct submodule *submodule,
654 const char *name, const char *start_oid,
655 const char *tracking_name, int force,
656 int reflog, int quiet,
657 enum branch_track track, int dry_run)
658{
659 int ret = 0;
660 struct child_process child = CHILD_PROCESS_INIT;
661 struct strbuf child_err = STRBUF_INIT;
662 struct strbuf out_buf = STRBUF_INIT;
663 char *out_prefix = xstrfmt("submodule '%s': ", submodule->name);
664 child.git_cmd = 1;
665 child.err = -1;
666 child.stdout_to_stderr = 1;
667
Ævar Arnfjörð Bjarmason29fda242022-06-02 11:09:50 +0200668 prepare_other_repo_env(&child.env, r->gitdir);
Glen Choo961b1302022-01-28 16:04:45 -0800669 /*
670 * submodule_create_branch() is indirectly invoked by "git
671 * branch", but we cannot invoke "git branch" in the child
672 * process. "git branch" accepts a branch name and start point,
673 * where the start point is assumed to provide both the OID
674 * (start_oid) and the branch to use for tracking
675 * (tracking_name). But when recursing through submodules,
676 * start_oid and tracking name need to be specified separately
677 * (see create_branches_recursively()).
678 */
679 strvec_pushl(&child.args, "submodule--helper", "create-branch", NULL);
680 if (dry_run)
681 strvec_push(&child.args, "--dry-run");
682 if (force)
683 strvec_push(&child.args, "--force");
684 if (quiet)
685 strvec_push(&child.args, "--quiet");
686 if (reflog)
687 strvec_push(&child.args, "--create-reflog");
Glen Choo75388bf2022-03-29 20:01:16 +0000688
689 switch (track) {
690 case BRANCH_TRACK_NEVER:
691 strvec_push(&child.args, "--no-track");
692 break;
693 case BRANCH_TRACK_ALWAYS:
694 case BRANCH_TRACK_EXPLICIT:
695 strvec_push(&child.args, "--track=direct");
696 break;
697 case BRANCH_TRACK_OVERRIDE:
698 BUG("BRANCH_TRACK_OVERRIDE cannot be used when creating a branch.");
699 break;
700 case BRANCH_TRACK_INHERIT:
701 strvec_push(&child.args, "--track=inherit");
702 break;
703 case BRANCH_TRACK_UNSPECIFIED:
Glen Choo1f888282022-03-31 15:41:17 -0700704 /* Default for "git checkout". Do not pass --track. */
Glen Choo75388bf2022-03-29 20:01:16 +0000705 case BRANCH_TRACK_REMOTE:
Glen Choo1f888282022-03-31 15:41:17 -0700706 /* Default for "git branch". Do not pass --track. */
Tao Klerksbdaf1df2022-04-29 09:56:44 +0000707 case BRANCH_TRACK_SIMPLE:
708 /* Config-driven only. Do not pass --track. */
Glen Choo75388bf2022-03-29 20:01:16 +0000709 break;
710 }
Glen Choo961b1302022-01-28 16:04:45 -0800711
712 strvec_pushl(&child.args, name, start_oid, tracking_name, NULL);
713
714 if ((ret = start_command(&child)))
715 return ret;
716 ret = finish_command(&child);
717 strbuf_read(&child_err, child.err, 0);
718 strbuf_add_lines(&out_buf, out_prefix, child_err.buf, child_err.len);
719
720 if (ret)
721 fprintf(stderr, "%s", out_buf.buf);
722 else
723 printf("%s", out_buf.buf);
724
725 strbuf_release(&child_err);
726 strbuf_release(&out_buf);
727 return ret;
728}
729
730void create_branches_recursively(struct repository *r, const char *name,
731 const char *start_commitish,
732 const char *tracking_name, int force,
733 int reflog, int quiet, enum branch_track track,
734 int dry_run)
735{
736 int i = 0;
737 char *branch_point = NULL;
738 struct object_id super_oid;
739 struct submodule_entry_list submodule_entry_list;
740
741 /* Perform dwim on start_commitish to get super_oid and branch_point. */
742 dwim_branch_start(r, start_commitish, BRANCH_TRACK_NEVER,
743 &branch_point, &super_oid);
744
745 /*
746 * If we were not given an explicit name to track, then assume we are at
747 * the top level and, just like the non-recursive case, the tracking
748 * name is the branch point.
749 */
750 if (!tracking_name)
751 tracking_name = branch_point;
752
753 submodules_of_tree(r, &super_oid, &submodule_entry_list);
754 /*
755 * Before creating any branches, first check that the branch can
756 * be created in every submodule.
757 */
758 for (i = 0; i < submodule_entry_list.entry_nr; i++) {
Junio C Hamanoe6bf70d2022-05-02 10:18:22 -0700759 if (!submodule_entry_list.entries[i].repo) {
Glen Choocfbda6b2022-03-29 20:01:17 +0000760 int code = die_message(
761 _("submodule '%s': unable to find submodule"),
762 submodule_entry_list.entries[i].submodule->name);
Glen Choo961b1302022-01-28 16:04:45 -0800763 if (advice_enabled(ADVICE_SUBMODULES_NOT_UPDATED))
Philippe Blain97cf0c72023-01-16 17:41:48 +0000764 advise(_("You may try updating the submodules using 'git checkout --no-recurse-submodules %s && git submodule update --init'"),
Glen Choo961b1302022-01-28 16:04:45 -0800765 start_commitish);
Glen Choocfbda6b2022-03-29 20:01:17 +0000766 exit(code);
Glen Choo961b1302022-01-28 16:04:45 -0800767 }
768
769 if (submodule_create_branch(
770 submodule_entry_list.entries[i].repo,
771 submodule_entry_list.entries[i].submodule, name,
772 oid_to_hex(&submodule_entry_list.entries[i]
773 .name_entry->oid),
774 tracking_name, force, reflog, quiet, track, 1))
775 die(_("submodule '%s': cannot create branch '%s'"),
776 submodule_entry_list.entries[i].submodule->name,
777 name);
778 }
779
Ævar Arnfjörð Bjarmason4a93b892023-03-28 15:58:58 +0200780 create_branch(r, name, start_commitish, force, 0, reflog, quiet,
Glen Choo961b1302022-01-28 16:04:45 -0800781 BRANCH_TRACK_NEVER, dry_run);
782 if (dry_run)
783 return;
784 /*
785 * NEEDSWORK If tracking was set up in the superproject but not the
786 * submodule, users might expect "git branch --recurse-submodules" to
787 * fail or give a warning, but this is not yet implemented because it is
788 * tedious to determine whether or not tracking was set up in the
789 * superproject.
790 */
Glen Choo75388bf2022-03-29 20:01:16 +0000791 if (track)
792 setup_tracking(name, tracking_name, track, quiet);
Glen Choo961b1302022-01-28 16:04:45 -0800793
794 for (i = 0; i < submodule_entry_list.entry_nr; i++) {
795 if (submodule_create_branch(
796 submodule_entry_list.entries[i].repo,
797 submodule_entry_list.entries[i].submodule, name,
798 oid_to_hex(&submodule_entry_list.entries[i]
799 .name_entry->oid),
800 tracking_name, force, reflog, quiet, track, 0))
801 die(_("submodule '%s': cannot create branch '%s'"),
802 submodule_entry_list.entries[i].submodule->name,
803 name);
804 repo_clear(submodule_entry_list.entries[i].repo);
805 }
806}
807
Nguyễn Thái Ngọc Duyb6433552019-05-09 17:10:27 +0700808void remove_merge_branch_state(struct repository *r)
Daniel Barkalowc369e7b2008-02-07 11:40:16 -0500809{
Nguyễn Thái Ngọc Duy4edce172018-11-10 06:49:00 +0100810 unlink(git_path_merge_head(r));
811 unlink(git_path_merge_rr(r));
812 unlink(git_path_merge_msg(r));
813 unlink(git_path_merge_mode(r));
Elijah Newren52918282021-03-20 00:03:52 +0000814 unlink(git_path_auto_merge(r));
Denton Liua03b5552020-04-07 10:28:07 -0400815 save_autostash(git_path_merge_autostash(r));
Nguyễn Thái Ngọc Duyb6433552019-05-09 17:10:27 +0700816}
817
Junio C Hamanof496b062019-07-09 15:25:44 -0700818void remove_branch_state(struct repository *r, int verbose)
Nguyễn Thái Ngọc Duyb6433552019-05-09 17:10:27 +0700819{
Junio C Hamanof496b062019-07-09 15:25:44 -0700820 sequencer_post_commit_cleanup(r, verbose);
Nguyễn Thái Ngọc Duy4edce172018-11-10 06:49:00 +0100821 unlink(git_path_squash_msg(r));
Nguyễn Thái Ngọc Duyb6433552019-05-09 17:10:27 +0700822 remove_merge_branch_state(r);
Daniel Barkalowc369e7b2008-02-07 11:40:16 -0500823}
Eric Sunshineed89f842015-07-17 19:00:04 -0400824
Nguyễn Thái Ngọc Duy8d9fdd72016-04-22 20:01:33 +0700825void die_if_checked_out(const char *branch, int ignore_current_worktree)
David Turner41af6562015-08-10 13:52:44 -0400826{
Anders Kaseorgc8dd4912021-12-01 14:15:43 -0800827 struct worktree **worktrees = get_worktrees();
David Turner41af6562015-08-10 13:52:44 -0400828
Rubén Justofaa4d592023-02-25 15:22:02 +0100829 for (int i = 0; worktrees[i]; i++) {
830 if (worktrees[i]->is_current && ignore_current_worktree)
831 continue;
832
833 if (is_shared_symref(worktrees[i], "HEAD", branch)) {
834 skip_prefix(branch, "refs/heads/", &branch);
835 die(_("'%s' is already checked out at '%s'"),
836 branch, worktrees[i]->path);
837 }
Anders Kaseorgc8dd4912021-12-01 14:15:43 -0800838 }
839
840 free_worktrees(worktrees);
Eric Sunshineed89f842015-07-17 19:00:04 -0400841}
Kazuki Yamaguchi70999e92016-03-27 23:37:14 +0900842
Kyle Meyer39ee4c62017-02-20 20:10:35 -0500843int replace_each_worktree_head_symref(const char *oldref, const char *newref,
844 const char *logmsg)
Kazuki Yamaguchi70999e92016-03-27 23:37:14 +0900845{
846 int ret = 0;
Eric Sunshine03f24652020-06-19 19:35:44 -0400847 struct worktree **worktrees = get_worktrees();
Kazuki Yamaguchi70999e92016-03-27 23:37:14 +0900848 int i;
849
850 for (i = 0; worktrees[i]; i++) {
Nguyễn Thái Ngọc Duyd026a252017-04-24 17:01:24 +0700851 struct ref_store *refs;
852
Kazuki Yamaguchi70999e92016-03-27 23:37:14 +0900853 if (worktrees[i]->is_detached)
854 continue;
Nguyễn Thái Ngọc Duy31824d12017-08-24 17:41:24 +0700855 if (!worktrees[i]->head_ref)
856 continue;
857 if (strcmp(oldref, worktrees[i]->head_ref))
Kazuki Yamaguchi70999e92016-03-27 23:37:14 +0900858 continue;
859
Nguyễn Thái Ngọc Duyd026a252017-04-24 17:01:24 +0700860 refs = get_worktree_ref_store(worktrees[i]);
861 if (refs_create_symref(refs, "HEAD", newref, logmsg))
862 ret = error(_("HEAD of working tree %s is not updated"),
863 worktrees[i]->path);
Kazuki Yamaguchi70999e92016-03-27 23:37:14 +0900864 }
865
866 free_worktrees(worktrees);
867 return ret;
868}