Volume XXII, number 279Tuesday, October 6, 2026Latest message 38 minutes ago

The Git List

News and archive of git@vger.kernel.org, since April 2005

patchcheckout: add --fetch to fetch remote before resolving start-point

73 messages between Apr 24, 2026 and Jul 23, 2026, from Harald Nordgren via GitGitGadget, Ramsay Jones, D. Ben Knoble, Kristoffer Haugsbakk, Marc Branchaud, Junio C Hamano, Harald Nordgren, Ben Knoble, Phillip Wood, Kristofer Karlsson.

Plain Markdown or JSON for tools and agents. Diffs are folded; open one to read it.

Harald Nordgren via GitGitGadgetApr 24, 2026, 10:03 UTC on lore
From: Harald Nordgren <haraldnordgren@gmail.com>

Add a --fetch option to git checkout and git switch, plus a checkout.autoFetch config to enable it by default. When set and the start-point argument names a configured remote (either bare, like "origin", or prefixed, like "origin/foo"), fetch that remote before resolving the ref. Aborts the checkout if the fetch fails.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
    checkout: add --fetch to fetch remote before resolving start-point
    
    A workflow I run several times a day looks like:
    
    git fetch origin
    git checkout -b new_branch origin/some-branch
    
    
    The first command exists purely to make the second one see an up-to-date
    view of the remote. If I forget it, origin/some-branch points at a stale
    commit, and I end up creating a local branch from the wrong starting
    point.
    
    This series teaches git checkout (and git switch) a new --fetch flag
    that folds the two steps into one:
    
    git checkout --fetch -b new_branch origin/some-branch
    
    
    When the start-point argument names a configured remote — either bare
    (origin, which resolves to the remote's default branch) or in / form —
    git fetch is run before the start-point is resolved. If the fetch fails,
    the checkout aborts and no local branch is created.
    
    A new checkout.autoFetch config option enables the same behavior by
    default, for users who always want it.
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v1
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v1
Pull-Request: https://github.com/git/git/pull/2281
 builtin/checkout.c    | 48 ++++++++++++++++++++++++++++++++++++++--
 t/t7201-co.sh         | 51 +++++++++++++++++++++++++++++++++++++++++++
 t/t9902-completion.sh |  1 +
 3 files changed, 98 insertions(+), 2 deletions(-)
Show changes to 3 files +98 −2

builtin/checkout.c, t/t7201-co.sh, t/t9902-completion.sh

diff --git a/builtin/checkout.c b/builtin/checkout.c
index e031e61886..c8fbc4923b 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -30,7 +30,9 @@
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "setup.h"
+#include "strvec.h"
 #include "submodule.h"
 #include "symlinks.h"
 #include "trace2.h"
@@ -61,6 +63,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int auto_fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -112,6 +115,34 @@ struct branch_info {
 	char *checkout;
 };
 
+static void fetch_remote_for_start_point(const char *arg)
+{
+	const char *slash;
+	char *remote_name;
+	struct remote *remote;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+
+	if (!arg || !*arg)
+		return;
+
+	slash = strchr(arg, '/');
+	if (slash == arg)
+		return;
+	remote_name = slash ? xstrndup(arg, slash - arg) : xstrdup(arg);
+
+	remote = remote_get(remote_name);
+	if (!remote || !remote_is_configured(remote, 1)) {
+		free(remote_name);
+		return;
+	}
+
+	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
+	cmd.git_cmd = 1;
+	free(remote_name);
+	if (run_command(&cmd))
+		die(_("failed to fetch start-point '%s'"), arg);
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1237,6 +1268,10 @@ static int git_checkout_config(const char *var, const char *value,
 		opts->dwim_new_local_branch = git_config_bool(var, value);
 		return 0;
 	}
+	if (!strcmp(var, "checkout.autofetch")) {
+		opts->auto_fetch = git_config_bool(var, value);
+		return 0;
+	}
 
 	if (starts_with(var, "submodule."))
 		return git_default_submodule_config(var, value, NULL);
@@ -1942,8 +1977,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->auto_fetch)
+			fetch_remote_for_start_point(argv[0]);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
@@ -2052,6 +2092,8 @@ int cmd_checkout(int argc,
 		OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
 		OPT_BOOL(0, "auto-advance", &opts.auto_advance,
 			 N_("auto advance to the next file when selecting hunks interactively")),
+		OPT_BOOL(0, "fetch", &opts.auto_fetch,
+			 N_("fetch from the remote first if <start-point> is a remote-tracking ref")),
 		OPT_END()
 	};
 
@@ -2102,6 +2144,8 @@ int cmd_switch(int argc,
 			 N_("second guess 'git switch <no-such-branch>'")),
 		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
 			 N_("throw away local modifications")),
+		OPT_BOOL(0, "fetch", &opts.auto_fetch,
+			 N_("fetch from the remote first if <start-point> is a remote-tracking ref")),
 		OPT_END()
 	};
 
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 9bcf7c0b40..60ddebd9c3 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -801,4 +801,55 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD
+'
+
+test_expect_success 'checkout --fetch with bare remote name fetches the remote' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_new2 &&
+	test_commit -C fetch_upstream u_new2 &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2 &&
+	git checkout --fetch -b local_from_remote fetch_upstream &&
+	git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2
+'
+
+test_expect_success 'checkout --fetch aborts and does not create branch on fetch failure' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout.autoFetch=true enables fetching without --fetch' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_cfg &&
+	test_commit -C fetch_upstream u_cfg &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_cfg &&
+	git -c checkout.autoFetch=true checkout -b local_cfg fetch_upstream/fetch_cfg &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_cfg HEAD
+'
+
+test_expect_success 'switch --fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 2f9a597ec7..dc1d63669f 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -2602,6 +2602,7 @@ test_expect_success 'double dash "git checkout"' '
 	--ignore-other-worktrees Z
 	--recurse-submodules Z
 	--auto-advance Z
+	--fetch Z
 	--progress Z
 	--guess Z
 	--no-guess Z

base-commit: 94f057755b7941b321fd11fec1b2e3ca5313a4e0
-- 
gitgitgadget
Ramsay JonesApr 24, 2026, 13:48 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH] checkout: add --fetch to fetch remote before resolving start-point

On 24/04/2026 11:03 am, Harald Nordgren via GitGitGadget wrote:
Show 10 quoted lines
> From: Harald Nordgren <haraldnordgren@gmail.com>
> 
> Add a --fetch option to git checkout and git switch, plus a
> checkout.autoFetch config to enable it by default. When set and the
> start-point argument names a configured remote (either bare, like
> "origin", or prefixed, like "origin/foo"), fetch that remote before
> resolving the ref. Aborts the checkout if the fetch fails.
> 
> Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
> ---
[snip]
Show 60 quoted lines
>  
> diff --git a/t/t7201-co.sh b/t/t7201-co.sh
> index 9bcf7c0b40..60ddebd9c3 100755
> --- a/t/t7201-co.sh
> +++ b/t/t7201-co.sh
> @@ -801,4 +801,55 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
>  	test_cmp_config "" --default "" branch.main2.merge
>  '
>  
> +test_expect_success 'setup upstream for --fetch tests' '
> +	git checkout main &&
> +	git init fetch_upstream &&
> +	test_commit -C fetch_upstream u_main &&
> +	git remote add fetch_upstream fetch_upstream &&
> +	git fetch fetch_upstream &&
> +	git -C fetch_upstream checkout -b fetch_new &&
> +	test_commit -C fetch_upstream u_new
> +'
> +
> +test_expect_success 'checkout --fetch -b picks up branch created upstream after clone' '
> +	git checkout main &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
> +	git checkout --fetch -b local_new fetch_upstream/fetch_new &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD
> +'
> +
> +test_expect_success 'checkout --fetch with bare remote name fetches the remote' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_new2 &&
> +	test_commit -C fetch_upstream u_new2 &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2 &&
> +	git checkout --fetch -b local_from_remote fetch_upstream &&
> +	git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2
> +'
> +
> +test_expect_success 'checkout --fetch aborts and does not create branch on fetch failure' '
> +	git checkout main &&
> +	test_might_fail git branch -D bogus &&
> +	test_must_fail git checkout --fetch -b bogus fetch_upstream/does_not_exist &&
> +	test_must_fail git rev-parse --verify refs/heads/bogus
> +'
> +
> +test_expect_success 'checkout.autoFetch=true enables fetching without --fetch' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_cfg &&
> +	test_commit -C fetch_upstream u_cfg &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_cfg &&
> +	git -c checkout.autoFetch=true checkout -b local_cfg fetch_upstream/fetch_cfg &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_cfg HEAD
> +'
> +
> +test_expect_success 'switch --fetch -c picks up branch created upstream after clone' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_switch &&
> +	test_commit -C fetch_upstream u_switch &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
> +	git switch --fetch -c local_switch fetch_upstream/fetch_switch &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
> +'
> +

I was just skimming the list (so if this is not appropriate, please just ignore) and, although I think '--no-fetch' will probably countermand the autoFetch config, I do not see a test that confirms it.

Thanks.

ATB, Ramsay Jones

D. Ben KnobleApr 24, 2026, 17:12 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH] checkout: add --fetch to fetch remote before resolving start-point

On Fri, Apr 24, 2026 at 6:08 AM Harald Nordgren via GitGitGadget <gitgitgadget@gmail.com> wrote:

Show 23 quoted lines
>
> From: Harald Nordgren <haraldnordgren@gmail.com>
>
> Add a --fetch option to git checkout and git switch, plus a
> checkout.autoFetch config to enable it by default. When set and the
> start-point argument names a configured remote (either bare, like
> "origin", or prefixed, like "origin/foo"), fetch that remote before
> resolving the ref. Aborts the checkout if the fetch fails.
>
> Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
> ---
>     checkout: add --fetch to fetch remote before resolving start-point
>
>     A workflow I run several times a day looks like:
>
>     git fetch origin
>     git checkout -b new_branch origin/some-branch
>
>
>     The first command exists purely to make the second one see an up-to-date
>     view of the remote. If I forget it, origin/some-branch points at a stale
>     commit, and I end up creating a local branch from the wrong starting
>     point.
When you realize this, "git pull --rebase" should help correct it.
Show 14 quoted lines
>
>     This series teaches git checkout (and git switch) a new --fetch flag
>     that folds the two steps into one:
>
>     git checkout --fetch -b new_branch origin/some-branch
>
>
>     When the start-point argument names a configured remote — either bare
>     (origin, which resolves to the remote's default branch) or in / form —
>     git fetch is run before the start-point is resolved. If the fetch fails,
>     the checkout aborts and no local branch is created.
>
>     A new checkout.autoFetch config option enables the same behavior by
>     default, for users who always want it.

I could certainly see this being convenient. (I don't have any comment on the code at this time.)

Kristoffer HaugsbakkApr 24, 2026, 17:38 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH] checkout: add --fetch to fetch remote before resolving start-point

On Fri, Apr 24, 2026, at 12:03, Harald Nordgren via GitGitGadget wrote:
> From: Harald Nordgren <haraldnordgren@gmail.com>
>
> Add a --fetch option to git checkout and git switch, plus a
> checkout.autoFetch config to enable it by default. When set and the

Why is the config not `checkout.config`? So it’s named the same as the option (modulo snake case/camel case which is not relevant here).

> start-point argument names a configured remote (either bare, like
> "origin", or prefixed, like "origin/foo"),

It’s great that it only fetches when you have a remote-tracking branch or alias for `<remote>/HEAD`. Doing a fetch on every <start-point> would have been bad.

Show 22 quoted lines
> fetch that remote before
> resolving the ref. Aborts the checkout if the fetch fails.
>
> Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
> ---
>     checkout: add --fetch to fetch remote before resolving start-point
>
>     A workflow I run several times a day looks like:
>
>     git fetch origin
>     git checkout -b new_branch origin/some-branch
>
>
>     The first command exists purely to make the second one see an up-to-date
>     view of the remote. If I forget it, origin/some-branch points at a stale
>     commit, and I end up creating a local branch from the wrong starting
>     point.
>
>     This series teaches git checkout (and git switch) a new --fetch flag
>     that folds the two steps into one:
>
>     git checkout --fetch -b new_branch origin/some-branch

The motivation for why this is being proposed maybe might as well go in the commit message. Maybe that’s just me.

The commit message just says that “this thing is added”. Not why.
Show 20 quoted lines
>
>
>     When the start-point argument names a configured remote — either bare
>     (origin, which resolves to the remote's default branch) or in / form —
>     git fetch is run before the start-point is resolved. If the fetch fails,
>     the checkout aborts and no local branch is created.
>
>     A new checkout.autoFetch config option enables the same behavior by
>     default, for users who always want it.
>
> Published-As:
> https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v1
> Fetch-It-Via: git fetch https://github.com/gitgitgadget/git
> pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v1
> Pull-Request: https://github.com/git/git/pull/2281
>
>  builtin/checkout.c    | 48 ++++++++++++++++++++++++++++++++++++++--
>  t/t7201-co.sh         | 51 +++++++++++++++++++++++++++++++++++++++++++
>  t/t9902-completion.sh |  1 +
>  3 files changed, 98 insertions(+), 2 deletions(-)
I guess a later version will have the changes to the documentation.
Show 14 quoted lines
>
> diff --git a/builtin/checkout.c b/builtin/checkout.c
>[snip]
>  		argv += n;
>  		argc -= n;
>  	} else if (!opts->accept_ref && opts->from_treeish) {
> @@ -2052,6 +2092,8 @@ int cmd_checkout(int argc,
>  		OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode
> (default)")),
>  		OPT_BOOL(0, "auto-advance", &opts.auto_advance,
>  			 N_("auto advance to the next file when selecting hunks
> interactively")),
> +		OPT_BOOL(0, "fetch", &opts.auto_fetch,
> +			 N_("fetch from the remote first if <start-point> is a remote-tracking ref")),
s/remote-tracking ref/remote-tracking branch/ ?
git(1) doesn’t have a namespace for tracking refs in general.
Show 9 quoted lines
>  		OPT_END()
>  	};
>
> @@ -2102,6 +2144,8 @@ int cmd_switch(int argc,
>  			 N_("second guess 'git switch <no-such-branch>'")),
>  		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
>  			 N_("throw away local modifications")),
> +		OPT_BOOL(0, "fetch", &opts.auto_fetch,
> +			 N_("fetch from the remote first if <start-point> is a remote-tracking ref")),
Ditto.
>  		OPT_END()
>  	};
>[snip]
Marc BranchaudApr 24, 2026, 17:42 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH] checkout: add --fetch to fetch remote before resolving start-point

On 2026-04-24 04:03, Harald Nordgren via GitGitGadget wrote:
Show 7 quoted lines
> From: Harald Nordgren <haraldnordgren@gmail.com>
> 
> Add a --fetch option to git checkout and git switch, plus a
> checkout.autoFetch config to enable it by default. When set and the
> start-point argument names a configured remote (either bare, like
> "origin", or prefixed, like "origin/foo"), fetch that remote before
> resolving the ref. Aborts the checkout if the fetch fails.

Why tie the behaviour to the nature of the start-point? That seems over-designed and prone to tripping people up. Are you trying to cater to users who have multiple remotes?

I can imagine people who just want to do a checkout of anything after 
fetching -- maybe they want to checkout a new tag, or some other 
detached HEAD, or just an already-existing local branch.  They see that 
checkout has this nifty --fetch option so they think they can combine
	git fetch; git checkout
into a single command ... but no, only if they checkout something in a 
remote's namespace.

I don't personally feel the need for this new option, but I think you'll have a much easier time implementing and maintaining it if you just make --fetch do a plain fetch without caring about what the starting-point is.

		M.
Show 214 quoted lines
> Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
> ---
>      checkout: add --fetch to fetch remote before resolving start-point
>      
>      A workflow I run several times a day looks like:
>      
>      git fetch origin
>      git checkout -b new_branch origin/some-branch
>      
>      
>      The first command exists purely to make the second one see an up-to-date
>      view of the remote. If I forget it, origin/some-branch points at a stale
>      commit, and I end up creating a local branch from the wrong starting
>      point.
>      
>      This series teaches git checkout (and git switch) a new --fetch flag
>      that folds the two steps into one:
>      
>      git checkout --fetch -b new_branch origin/some-branch
>      
>      
>      When the start-point argument names a configured remote — either bare
>      (origin, which resolves to the remote's default branch) or in / form —
>      git fetch is run before the start-point is resolved. If the fetch fails,
>      the checkout aborts and no local branch is created.
>      
>      A new checkout.autoFetch config option enables the same behavior by
>      default, for users who always want it.
> 
> Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v1
> Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v1
> Pull-Request: https://github.com/git/git/pull/2281
> 
>   builtin/checkout.c    | 48 ++++++++++++++++++++++++++++++++++++++--
>   t/t7201-co.sh         | 51 +++++++++++++++++++++++++++++++++++++++++++
>   t/t9902-completion.sh |  1 +
>   3 files changed, 98 insertions(+), 2 deletions(-)
> 
> diff --git a/builtin/checkout.c b/builtin/checkout.c
> index e031e61886..c8fbc4923b 100644
> --- a/builtin/checkout.c
> +++ b/builtin/checkout.c
> @@ -30,7 +30,9 @@
>   #include "repo-settings.h"
>   #include "resolve-undo.h"
>   #include "revision.h"
> +#include "run-command.h"
>   #include "setup.h"
> +#include "strvec.h"
>   #include "submodule.h"
>   #include "symlinks.h"
>   #include "trace2.h"
> @@ -61,6 +63,7 @@ struct checkout_opts {
>   	int count_checkout_paths;
>   	int overlay_mode;
>   	int dwim_new_local_branch;
> +	int auto_fetch;
>   	int discard_changes;
>   	int accept_ref;
>   	int accept_pathspec;
> @@ -112,6 +115,34 @@ struct branch_info {
>   	char *checkout;
>   };
>   
> +static void fetch_remote_for_start_point(const char *arg)
> +{
> +	const char *slash;
> +	char *remote_name;
> +	struct remote *remote;
> +	struct child_process cmd = CHILD_PROCESS_INIT;
> +
> +	if (!arg || !*arg)
> +		return;
> +
> +	slash = strchr(arg, '/');
> +	if (slash == arg)
> +		return;
> +	remote_name = slash ? xstrndup(arg, slash - arg) : xstrdup(arg);
> +
> +	remote = remote_get(remote_name);
> +	if (!remote || !remote_is_configured(remote, 1)) {
> +		free(remote_name);
> +		return;
> +	}
> +
> +	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
> +	cmd.git_cmd = 1;
> +	free(remote_name);
> +	if (run_command(&cmd))
> +		die(_("failed to fetch start-point '%s'"), arg);
> +}
> +
>   static void branch_info_release(struct branch_info *info)
>   {
>   	free(info->name);
> @@ -1237,6 +1268,10 @@ static int git_checkout_config(const char *var, const char *value,
>   		opts->dwim_new_local_branch = git_config_bool(var, value);
>   		return 0;
>   	}
> +	if (!strcmp(var, "checkout.autofetch")) {
> +		opts->auto_fetch = git_config_bool(var, value);
> +		return 0;
> +	}
>   
>   	if (starts_with(var, "submodule."))
>   		return git_default_submodule_config(var, value, NULL);
> @@ -1942,8 +1977,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
>   			opts->dwim_new_local_branch &&
>   			opts->track == BRANCH_TRACK_UNSPECIFIED &&
>   			!opts->new_branch;
> -		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
> -					     &new_branch_info, opts, &rev);
> +		int n;
> +
> +		if (opts->auto_fetch)
> +			fetch_remote_for_start_point(argv[0]);
> +
> +		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
> +					 &new_branch_info, opts, &rev);
>   		argv += n;
>   		argc -= n;
>   	} else if (!opts->accept_ref && opts->from_treeish) {
> @@ -2052,6 +2092,8 @@ int cmd_checkout(int argc,
>   		OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
>   		OPT_BOOL(0, "auto-advance", &opts.auto_advance,
>   			 N_("auto advance to the next file when selecting hunks interactively")),
> +		OPT_BOOL(0, "fetch", &opts.auto_fetch,
> +			 N_("fetch from the remote first if <start-point> is a remote-tracking ref")),
>   		OPT_END()
>   	};
>   
> @@ -2102,6 +2144,8 @@ int cmd_switch(int argc,
>   			 N_("second guess 'git switch <no-such-branch>'")),
>   		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
>   			 N_("throw away local modifications")),
> +		OPT_BOOL(0, "fetch", &opts.auto_fetch,
> +			 N_("fetch from the remote first if <start-point> is a remote-tracking ref")),
>   		OPT_END()
>   	};
>   
> diff --git a/t/t7201-co.sh b/t/t7201-co.sh
> index 9bcf7c0b40..60ddebd9c3 100755
> --- a/t/t7201-co.sh
> +++ b/t/t7201-co.sh
> @@ -801,4 +801,55 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
>   	test_cmp_config "" --default "" branch.main2.merge
>   '
>   
> +test_expect_success 'setup upstream for --fetch tests' '
> +	git checkout main &&
> +	git init fetch_upstream &&
> +	test_commit -C fetch_upstream u_main &&
> +	git remote add fetch_upstream fetch_upstream &&
> +	git fetch fetch_upstream &&
> +	git -C fetch_upstream checkout -b fetch_new &&
> +	test_commit -C fetch_upstream u_new
> +'
> +
> +test_expect_success 'checkout --fetch -b picks up branch created upstream after clone' '
> +	git checkout main &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
> +	git checkout --fetch -b local_new fetch_upstream/fetch_new &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD
> +'
> +
> +test_expect_success 'checkout --fetch with bare remote name fetches the remote' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_new2 &&
> +	test_commit -C fetch_upstream u_new2 &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2 &&
> +	git checkout --fetch -b local_from_remote fetch_upstream &&
> +	git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2
> +'
> +
> +test_expect_success 'checkout --fetch aborts and does not create branch on fetch failure' '
> +	git checkout main &&
> +	test_might_fail git branch -D bogus &&
> +	test_must_fail git checkout --fetch -b bogus fetch_upstream/does_not_exist &&
> +	test_must_fail git rev-parse --verify refs/heads/bogus
> +'
> +
> +test_expect_success 'checkout.autoFetch=true enables fetching without --fetch' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_cfg &&
> +	test_commit -C fetch_upstream u_cfg &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_cfg &&
> +	git -c checkout.autoFetch=true checkout -b local_cfg fetch_upstream/fetch_cfg &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_cfg HEAD
> +'
> +
> +test_expect_success 'switch --fetch -c picks up branch created upstream after clone' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_switch &&
> +	test_commit -C fetch_upstream u_switch &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
> +	git switch --fetch -c local_switch fetch_upstream/fetch_switch &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
> +'
> +
>   test_done
> diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
> index 2f9a597ec7..dc1d63669f 100755
> --- a/t/t9902-completion.sh
> +++ b/t/t9902-completion.sh
> @@ -2602,6 +2602,7 @@ test_expect_success 'double dash "git checkout"' '
>   	--ignore-other-worktrees Z
>   	--recurse-submodules Z
>   	--auto-advance Z
> +	--fetch Z
>   	--progress Z
>   	--guess Z
>   	--no-guess Z
> 
> base-commit: 94f057755b7941b321fd11fec1b2e3ca5313a4e0
Junio C HamanoApr 24, 2026, 22:21 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH] checkout: add --fetch to fetch remote before resolving start-point

"Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
Show 10 quoted lines
> From: Harald Nordgren <haraldnordgren@gmail.com>
>
> Add a --fetch option to git checkout and git switch, plus a
> checkout.autoFetch config to enable it by default. When set and the
> start-point argument names a configured remote (either bare, like
> "origin", or prefixed, like "origin/foo"), fetch that remote before
> resolving the ref. Aborts the checkout if the fetch fails.
>
> Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
> ---

It is true that "checkout" does funny things to special case the remote-tracking branches, like setting up the branch.<name>.merge configuration or even inferring the name of the local branch to be created.

But I have to say that this one, especially the configuration variable, goes way too far. The usual uses of remote-tracking branch names, e.g.,

    git log -1 origin/master
    git grep frotz origin/master
    git rev-list --count origin/maint..origin/master

to name a specific object all assume and rely on the stability of them. Should the configuration cause a fetch to happen before any of these uses of remote-tracking branches for consistency?

Junio C HamanoApr 25, 2026, 02:54 UTC in reply to Junio C Hamano on lore

Re: [PATCH] checkout: add --fetch to fetch remote before resolving start-point

Junio C Hamano <gitster@pobox.com> writes:
Show 20 quoted lines
> "Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
>
>> From: Harald Nordgren <haraldnordgren@gmail.com>
>>
>> Add a --fetch option to git checkout and git switch, plus a
>> checkout.autoFetch config to enable it by default. When set and the
>> start-point argument names a configured remote (either bare, like
>> "origin", or prefixed, like "origin/foo"), fetch that remote before
>> resolving the ref. Aborts the checkout if the fetch fails.
>>
>> Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
>> ---
>
> It is true that "checkout" does funny things to special case the
> remote-tracking branches, like setting up the branch.<name>.merge
> configuration or even inferring the name of the local branch to be
> created.  
> ...
> ...  Should the configuration cause a fetch to happen before any
> of these uses of remote-tracking branches for consistency?

The last one was a rhetorical question. I do not want to see such a configuration variable to implicitly trigger fetching at all.

I am somewhat sympathetic to the desire "I want to be sure that I start the new branch in a state as fresh as possible". It is tied to the "--track" option of "git checkout -b topic --track origin/main". If you are merely starting at a single arbitrary commit, instead of anticipating to having to repeatedly sync with the remote-tracking branch that will subsequently move, there is no point jumping to a "freshest" commit that you haven't even seen let alone inspected (i.e., you do not even know if it is a good base to build on).

So instead of introducing a totally new option that can only be used only when "--track" is given, it might make more sense to introduce this as a variant of "--track", perhaps "--track=fetch,[in]direct" or something like that. And extend branch.autosetup{Merge,Rebase} that controls what happens when a branch is created with "checkout -t -b" or "branch --track" so that the remote-tracking branch gets updated, perhaps.

As to "git checkout origin/main" (nothing else on the command line), it has "magic" compared to "git checkout origin/main~0" already by treating the parameter not just as a SHA-1 expression that names a commit object but as a remote-tracking branch (this is necessary for "-t"). So I am not fundamentally opposed to the idea to give an option to treat that form specifically.

Having said all that, quite honestly, I prefer not to see any of the above changes, including the original patch. It leaves too many usability questions unaddressed. For a starter, if you interact with a repository with two or more branches, should

   $ git checkout --track=fetch -b topic origin/main

update an unrelated remote-tracking branch origin/maint from the same remote? As I already said, most Git tools _depend_ on the stability of remote-tracking branches---the desire to update the origin/main when a new branch that builds on origin/main is created may be a valid one, but it is unclear if that warrants updating other remote-tracking branches only because they come from the same remote repository. There may be a dozen other UI/usability issues that will be introduced if we start to "fetch from remote" automatically, but I won't even try to be exhaustive while I am still on a leave ;-)

Harald NordgrenApr 25, 2026, 17:24 UTC in reply to D. Ben Knoble on lore

Comments on Phillip's review

> When you realize this, "git pull --rebase" should help correct it.
Sure. I always run with

``` git config --global pull.rebase=true ```

I love rebasing and recomdend it to all colleagues that will listen, but it still sucks to expose yourself to a possible merge conflict when you realize you worked hours on top of a stale main branch.

> I could certainly see this being convenient.
🙌🏻
Harald
Harald NordgrenApr 25, 2026, 17:41 UTC in reply to Kristoffer Haugsbakk on lore

Comments on Phillip's review

Show 5 quoted lines
> > Add a --fetch option to git checkout and git switch, plus a
> > checkout.autoFetch config to enable it by default. When set and the
> 
> Why is the config not `checkout.config`? So it’s named the same as the
> option (modulo snake case/camel case which is not relevant here).
Will rename the config to 'checkout.fetch'.
> The motivation for why this is being proposed maybe might as well go in
> the commit message. Maybe that’s just me.
> 
> The commit message just says that “this thing is added”. Not why.
I will update it.
> I guess a later version will have the changes to the documentation.
I forgot that, will add it!
> s/remote-tracking ref/remote-tracking branch/ ?
> 
> git(1) doesn’t have a namespace for tracking refs in general.
👍
Harald
Harald NordgrenApr 25, 2026, 17:44 UTC in reply to Harald Nordgren on lore

Wrong subject line

I know you are not Ben. Forgot to change the subject line from a previous message.
Harald
Harald NordgrenApr 25, 2026, 17:44 UTC in reply to Harald Nordgren on lore

Wrong subject line

I know you are not Ben. Forgot to change the subject line from a previous message.
Harald
Harald NordgrenApr 25, 2026, 17:48 UTC in reply to Marc Branchaud on lore

Wrong subject line

I know you are not Ben. Forgot to change the subject line from a previous message.
Harald
Harald NordgrenApr 25, 2026, 17:58 UTC in reply to Junio C Hamano on lore

Multiple remotes

> The last one was a rhetorical question.  I do not want to see such a
> configuration variable to implicitly trigger fetching at all.
🤣

Good to clarify that when working with me so that I don't go ahead and implement that!

Show 6 quoted lines
> If you are merely starting at a single arbitrary
> commit, instead of anticipating to having to repeatedly sync with
> the remote-tracking branch that will subsequently move, there is no
> point jumping to a "freshest" commit that you haven't even seen let
> alone inspected (i.e., you do not even know if it is a good base to
> build on).

Not sure I understand this sentiment. For better or worse, the latest commit will decide what you have to work with -- unless we expect it to be reverted or forced pushed over.

What better starting point is there?
Show 8 quoted lines
> For a starter, if you interact
> with a repository with two or more branches, should
> 
>    $ git checkout --track=fetch -b topic origin/main
> 
> update an unrelated remote-tracking branch origin/maint from the
> same remote?  As I already said, most Git tools _depend_ on the
> stability of remote-tracking branches

This is an interesting question, and it's very likely that I am missing some nuance here. However, with that said what option does the developer have, you have to accept that the upstream changes constantly when others are working on it. What good does it do to keep the "head in the sand" any longer than necessary?

I'm not sure there is a way to fetch only 'origin/main' and avoid 'origin/maint'? Maybe, maybe, if that exists it could be useful here.

> still on a leave
Enjoy your vacation! I don't expect any response from you until you're back!
Harald
Harald Nordgren via GitGitGadgetApr 25, 2026, 18:12 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v2] checkout: add --fetch to fetch remote before resolving start-point

From: Harald Nordgren <haraldnordgren@gmail.com>
A common workflow is:
    git fetch origin
    git checkout -b new_branch origin/some-branch

The first command exists purely so the second sees an up-to-date view of the remote. If it is forgotten, origin/some-branch points at a stale commit and the new local branch is created from the wrong start point.

Teach checkout (and switch) a --fetch flag that folds the two steps into one:

    git checkout --fetch -b new_branch origin/some-branch

When --fetch is given and <start-point> names a configured remote (either bare, like "origin", or prefixed, like "origin/foo"), fetch that remote before resolving the ref. Abort the checkout if the fetch fails.

Also add a checkout.fetch config to enable this by default.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
    checkout: add --fetch to fetch remote before resolving start-point
    
     * Rename the config from checkout.autoFetch to checkout.fetch, so it
       matches the --fetch option name.
    
     * Rename the internal struct field from auto_fetch to fetch for
       consistency with the option and config names.
    
     * Reword the commit message to lead with the problem (forgetting 'git
       fetch' and ending up with a stale start-point) before describing the
       solution.
    
     * Document --fetch / --no-fetch in git-checkout and git-switch, and
       document checkout.fetch in the config reference.
    
     * Use "remote-tracking branch" instead of "remote-tracking ref" in the
       option help text.
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v2
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v2
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v1:
 1:  e2fa50ff40 ! 1:  13074c9fea checkout: add --fetch to fetch remote before resolving start-point
     @@ Metadata
       ## Commit message ##
          checkout: add --fetch to fetch remote before resolving start-point
      
     -    Add a --fetch option to git checkout and git switch, plus a
     -    checkout.autoFetch config to enable it by default. When set and the
     -    start-point argument names a configured remote (either bare, like
     -    "origin", or prefixed, like "origin/foo"), fetch that remote before
     -    resolving the ref. Aborts the checkout if the fetch fails.
     +    A common workflow is:
     +
     +        git fetch origin
     +        git checkout -b new_branch origin/some-branch
     +
     +    The first command exists purely so the second sees an up-to-date view
     +    of the remote. If it is forgotten, origin/some-branch points at a stale
     +    commit and the new local branch is created from the wrong start point.
     +
     +    Teach checkout (and switch) a --fetch flag that folds the two steps
     +    into one:
     +
     +        git checkout --fetch -b new_branch origin/some-branch
     +
     +    When --fetch is given and <start-point> names a configured remote
     +    (either bare, like "origin", or prefixed, like "origin/foo"), fetch
     +    that remote before resolving the ref. Abort the checkout if the fetch
     +    fails.
     +
     +    Also add a checkout.fetch config to enable this by default.
      
          Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
      
     + ## Documentation/config/checkout.adoc ##
     +@@ Documentation/config/checkout.adoc: commands or functionality in the future.
     + 	option in `git checkout` and `git switch`. See
     + 	linkgit:git-switch[1] and linkgit:git-checkout[1].
     + 
     ++`checkout.fetch`::
     ++	Provides the default value for the `--fetch` or `--no-fetch`
     ++	option in `git checkout` and `git switch`. See
     ++	linkgit:git-switch[1] and linkgit:git-checkout[1].
     ++
     + `checkout.workers`::
     + 	The number of parallel workers to use when updating the working tree.
     + 	The default is one, i.e. sequential execution. If set to a value less
     +
     + ## Documentation/git-checkout.adoc ##
     +@@ Documentation/git-checkout.adoc: linkgit:git-config[1].
     + The default behavior can be set via the `checkout.guess` configuration
     + variable.
     + 
     ++`--fetch`::
     ++`--no-fetch`::
     ++	If _<start-point>_ names a configured remote -- either bare,
     ++	like `origin` (which resolves to the remote's default branch),
     ++	or in _<remote>/<branch>_ form -- run `git fetch` on that
     ++	remote before resolving _<start-point>_. If the fetch fails,
     ++	the checkout is aborted and no local branch is created.
     +++
     ++The default behavior can be set via the `checkout.fetch` configuration
     ++variable.
     ++
     + `-l`::
     + 	Create the new branch's reflog; see linkgit:git-branch[1] for
     + 	details.
     +
     + ## Documentation/git-switch.adoc ##
     +@@ Documentation/git-switch.adoc: ambiguous but exists on the 'origin' remote. See also
     + The default behavior can be set via the `checkout.guess` configuration
     + variable.
     + 
     ++`--fetch`::
     ++`--no-fetch`::
     ++	If _<start-point>_ names a configured remote -- either bare,
     ++	like `origin` (which resolves to the remote's default branch),
     ++	or in _<remote>/<branch>_ form -- run `git fetch` on that
     ++	remote before resolving _<start-point>_. If the fetch fails,
     ++	the switch is aborted and no local branch is created.
     +++
     ++The default behavior can be set via the `checkout.fetch` configuration
     ++variable.
     ++
     + `-f`::
     + `--force`::
     + 	An alias for `--discard-changes`.
     +
       ## builtin/checkout.c ##
      @@
       #include "repo-settings.h"
     @@ builtin/checkout.c: struct checkout_opts {
       	int count_checkout_paths;
       	int overlay_mode;
       	int dwim_new_local_branch;
     -+	int auto_fetch;
     ++	int fetch;
       	int discard_changes;
       	int accept_ref;
       	int accept_pathspec;
     @@ builtin/checkout.c: static int git_checkout_config(const char *var, const char *
       		opts->dwim_new_local_branch = git_config_bool(var, value);
       		return 0;
       	}
     -+	if (!strcmp(var, "checkout.autofetch")) {
     -+		opts->auto_fetch = git_config_bool(var, value);
     ++	if (!strcmp(var, "checkout.fetch")) {
     ++		opts->fetch = git_config_bool(var, value);
      +		return 0;
      +	}
       
     @@ builtin/checkout.c: static int checkout_main(int argc, const char **argv, const
      -					     &new_branch_info, opts, &rev);
      +		int n;
      +
     -+		if (opts->auto_fetch)
     ++		if (opts->fetch)
      +			fetch_remote_for_start_point(argv[0]);
      +
      +		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
     @@ builtin/checkout.c: int cmd_checkout(int argc,
       		OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
       		OPT_BOOL(0, "auto-advance", &opts.auto_advance,
       			 N_("auto advance to the next file when selecting hunks interactively")),
     -+		OPT_BOOL(0, "fetch", &opts.auto_fetch,
     -+			 N_("fetch from the remote first if <start-point> is a remote-tracking ref")),
     ++		OPT_BOOL(0, "fetch", &opts.fetch,
     ++			 N_("fetch from the remote first if <start-point> is a remote-tracking branch")),
       		OPT_END()
       	};
       
     @@ builtin/checkout.c: int cmd_switch(int argc,
       			 N_("second guess 'git switch <no-such-branch>'")),
       		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
       			 N_("throw away local modifications")),
     -+		OPT_BOOL(0, "fetch", &opts.auto_fetch,
     -+			 N_("fetch from the remote first if <start-point> is a remote-tracking ref")),
     ++		OPT_BOOL(0, "fetch", &opts.fetch,
     ++			 N_("fetch from the remote first if <start-point> is a remote-tracking branch")),
       		OPT_END()
       	};
       
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_must_fail git rev-parse --verify refs/heads/bogus
      +'
      +
     -+test_expect_success 'checkout.autoFetch=true enables fetching without --fetch' '
     ++test_expect_success 'checkout.fetch=true enables fetching without --fetch' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_cfg &&
      +	test_commit -C fetch_upstream u_cfg &&
      +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_cfg &&
     -+	git -c checkout.autoFetch=true checkout -b local_cfg fetch_upstream/fetch_cfg &&
     ++	git -c checkout.fetch=true checkout -b local_cfg fetch_upstream/fetch_cfg &&
      +	test_cmp_rev refs/remotes/fetch_upstream/fetch_cfg HEAD
      +'
      +
 Documentation/config/checkout.adoc |  5 +++
 Documentation/git-checkout.adoc    | 11 +++++++
 Documentation/git-switch.adoc      | 11 +++++++
 builtin/checkout.c                 | 48 ++++++++++++++++++++++++++--
 t/t7201-co.sh                      | 51 ++++++++++++++++++++++++++++++
 t/t9902-completion.sh              |  1 +
 6 files changed, 125 insertions(+), 2 deletions(-)
Show changes to 6 files +125 −2

Documentation/config/checkout.adoc, Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh, t/t9902-completion.sh

diff --git a/Documentation/config/checkout.adoc b/Documentation/config/checkout.adoc
index e35d212969..c95f72b38e 100644
--- a/Documentation/config/checkout.adoc
+++ b/Documentation/config/checkout.adoc
@@ -22,6 +22,11 @@ commands or functionality in the future.
 	option in `git checkout` and `git switch`. See
 	linkgit:git-switch[1] and linkgit:git-checkout[1].
 
+`checkout.fetch`::
+	Provides the default value for the `--fetch` or `--no-fetch`
+	option in `git checkout` and `git switch`. See
+	linkgit:git-switch[1] and linkgit:git-checkout[1].
+
 `checkout.workers`::
 	The number of parallel workers to use when updating the working tree.
 	The default is one, i.e. sequential execution. If set to a value less
diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index 43ccf47cf6..f20e2f4c8c 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -201,6 +201,17 @@ linkgit:git-config[1].
 The default behavior can be set via the `checkout.guess` configuration
 variable.
 
+`--fetch`::
+`--no-fetch`::
+	If _<start-point>_ names a configured remote -- either bare,
+	like `origin` (which resolves to the remote's default branch),
+	or in _<remote>/<branch>_ form -- run `git fetch` on that
+	remote before resolving _<start-point>_. If the fetch fails,
+	the checkout is aborted and no local branch is created.
++
+The default behavior can be set via the `checkout.fetch` configuration
+variable.
+
 `-l`::
 	Create the new branch's reflog; see linkgit:git-branch[1] for
 	details.
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index 87707e9265..3826ed9066 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -110,6 +110,17 @@ ambiguous but exists on the 'origin' remote. See also
 The default behavior can be set via the `checkout.guess` configuration
 variable.
 
+`--fetch`::
+`--no-fetch`::
+	If _<start-point>_ names a configured remote -- either bare,
+	like `origin` (which resolves to the remote's default branch),
+	or in _<remote>/<branch>_ form -- run `git fetch` on that
+	remote before resolving _<start-point>_. If the fetch fails,
+	the switch is aborted and no local branch is created.
++
+The default behavior can be set via the `checkout.fetch` configuration
+variable.
+
 `-f`::
 `--force`::
 	An alias for `--discard-changes`.
diff --git a/builtin/checkout.c b/builtin/checkout.c
index e031e61886..b2a34f0f00 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -30,7 +30,9 @@
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "setup.h"
+#include "strvec.h"
 #include "submodule.h"
 #include "symlinks.h"
 #include "trace2.h"
@@ -61,6 +63,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -112,6 +115,34 @@ struct branch_info {
 	char *checkout;
 };
 
+static void fetch_remote_for_start_point(const char *arg)
+{
+	const char *slash;
+	char *remote_name;
+	struct remote *remote;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+
+	if (!arg || !*arg)
+		return;
+
+	slash = strchr(arg, '/');
+	if (slash == arg)
+		return;
+	remote_name = slash ? xstrndup(arg, slash - arg) : xstrdup(arg);
+
+	remote = remote_get(remote_name);
+	if (!remote || !remote_is_configured(remote, 1)) {
+		free(remote_name);
+		return;
+	}
+
+	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
+	cmd.git_cmd = 1;
+	free(remote_name);
+	if (run_command(&cmd))
+		die(_("failed to fetch start-point '%s'"), arg);
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1237,6 +1268,10 @@ static int git_checkout_config(const char *var, const char *value,
 		opts->dwim_new_local_branch = git_config_bool(var, value);
 		return 0;
 	}
+	if (!strcmp(var, "checkout.fetch")) {
+		opts->fetch = git_config_bool(var, value);
+		return 0;
+	}
 
 	if (starts_with(var, "submodule."))
 		return git_default_submodule_config(var, value, NULL);
@@ -1942,8 +1977,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0]);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
@@ -2052,6 +2092,8 @@ int cmd_checkout(int argc,
 		OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
 		OPT_BOOL(0, "auto-advance", &opts.auto_advance,
 			 N_("auto advance to the next file when selecting hunks interactively")),
+		OPT_BOOL(0, "fetch", &opts.fetch,
+			 N_("fetch from the remote first if <start-point> is a remote-tracking branch")),
 		OPT_END()
 	};
 
@@ -2102,6 +2144,8 @@ int cmd_switch(int argc,
 			 N_("second guess 'git switch <no-such-branch>'")),
 		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
 			 N_("throw away local modifications")),
+		OPT_BOOL(0, "fetch", &opts.fetch,
+			 N_("fetch from the remote first if <start-point> is a remote-tracking branch")),
 		OPT_END()
 	};
 
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 9bcf7c0b40..f5729f0831 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -801,4 +801,55 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD
+'
+
+test_expect_success 'checkout --fetch with bare remote name fetches the remote' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_new2 &&
+	test_commit -C fetch_upstream u_new2 &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2 &&
+	git checkout --fetch -b local_from_remote fetch_upstream &&
+	git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2
+'
+
+test_expect_success 'checkout --fetch aborts and does not create branch on fetch failure' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout.fetch=true enables fetching without --fetch' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_cfg &&
+	test_commit -C fetch_upstream u_cfg &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_cfg &&
+	git -c checkout.fetch=true checkout -b local_cfg fetch_upstream/fetch_cfg &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_cfg HEAD
+'
+
+test_expect_success 'switch --fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 2f9a597ec7..dc1d63669f 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -2602,6 +2602,7 @@ test_expect_success 'double dash "git checkout"' '
 	--ignore-other-worktrees Z
 	--recurse-submodules Z
 	--auto-advance Z
+	--fetch Z
 	--progress Z
 	--guess Z
 	--no-guess Z

base-commit: 94f057755b7941b321fd11fec1b2e3ca5313a4e0
-- 
gitgitgadget
Ben KnobleApr 25, 2026, 21:57 UTC in reply to Harald Nordgren on lore

Re: Multiple remotes

Show 42 quoted lines
> Le 25 avr. 2026 à 13:58, Harald Nordgren <haraldnordgren@gmail.com> a écrit :
> 
> 
>> 
>> The last one was a rhetorical question.  I do not want to see such a
>> configuration variable to implicitly trigger fetching at all.
> 
> 🤣
> 
> Good to clarify that when working with me so that I don't go ahead and
> implement that!
> 
>> If you are merely starting at a single arbitrary
>> commit, instead of anticipating to having to repeatedly sync with
>> the remote-tracking branch that will subsequently move, there is no
>> point jumping to a "freshest" commit that you haven't even seen let
>> alone inspected (i.e., you do not even know if it is a good base to
>> build on).
> 
> Not sure I understand this sentiment. For better or worse, the latest
> commit will decide what you have to work with -- unless we expect it to be
> reverted or forced pushed over.
> 
> What better starting point is there?
> 
>> For a starter, if you interact
>> with a repository with two or more branches, should
>> 
>>   $ git checkout --track=fetch -b topic origin/main
>> 
>> update an unrelated remote-tracking branch origin/maint from the
>> same remote?  As I already said, most Git tools _depend_ on the
>> stability of remote-tracking branches
> 
> This is an interesting question, and it's very likely that I am missing
> some nuance here. However, with that said what option does the developer
> have, you have to accept that the upstream changes constantly when others
> are working on it. What good does it do to keep the "head in the sand" any
> longer than necessary?
> 
> I'm not sure there is a way to fetch only 'origin/main' and avoid
> 'origin/maint'? Maybe, maybe, if that exists it could be useful here.
Isn’t that exactly what
    git fetch origin main
does? (Might need to expand the refspec.)
Show 8 quoted lines
> 
>> still on a leave
> 
> Enjoy your vacation! I don't expect any response from you until you're back!
> 
> 
> Harald
> 
Harald NordgrenApr 25, 2026, 22:54 UTC in reply to Ben Knoble on lore

gh

Show 5 quoted lines
> Isn’t that exactly what
> 
>     git fetch origin main
> 
> does? (Might need to expand the refspec.)
Very good point, I will update it!
Harald
Kristoffer HaugsbakkApr 26, 2026, 07:07 UTC in reply to Harald Nordgren on lore

Re: Wrong subject line

On Sat, Apr 25, 2026, at 19:44, Harald Nordgren wrote:
> I know you are not Ben. Forgot to change the subject line from a
> previous message.
You mean I’m not Phillip. ;)
    Subject: Comments on Phillip's review

I don’t understand why you change the email subjects so often. Right now I had three “Wrong subject line” in my inbox with lost threading (webmail client) with the only way to distinguish them being that I was the the CC on this one.

Most of the time whole 100-email threads like patch series never change the subject. And to me it is easier to keep track of those “RE: [PATCH v5] florb: drop glorb” than if someone changes the subject to e.g. “Regarding memory leaks” because someone found a memory leak in a review. Because that was a reply to an email from two days ago, but I’ve been a away for a week so I think it’s a new thread about something else.

That’s just my experience. My amateur webmail setup doesn’t really matter here since I just dip in/interrupt threads when I feel like it.

Harald Nordgren via GitGitGadgetApr 26, 2026, 07:24 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v3] checkout: add --fetch to fetch remote before resolving start-point

From: Harald Nordgren <haraldnordgren@gmail.com>
A common workflow is:
    git fetch origin
    git checkout -b new_branch origin/some-branch

The first command exists purely so the second sees an up-to-date view of the remote. If it is forgotten, origin/some-branch points at a stale commit and the new local branch is created from the wrong start point.

Teach checkout (and switch) a --fetch flag that folds the two steps into one:

    git checkout --fetch -b new_branch origin/some-branch

When --fetch is given and <start-point> is in <remote>/<branch> form, run "git fetch <remote> <branch>" before resolving the ref. This narrows the fetch to the requested branch so that other remote-tracking branches are left untouched -- many tools rely on the stability of remote-tracking refs between explicit fetches. If <start-point> is a bare remote name like "origin" (which resolves to that remote's default branch), "git fetch <remote>" is run instead, since the target branch is not known up front. Abort the checkout if the fetch fails.

Also add a checkout.fetch config to enable this by default.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
    checkout: add --fetch to fetch remote before resolving start-point
    
    When <start-point> is in <remote>/<branch> form, only fetch that one
    branch instead of the whole remote, so unrelated remote-tracking
    branches stay stable. The bare-remote form (e.g. "origin") still fetches
    everything.
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v3
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v3
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v2:
 1:  13074c9fea ! 1:  df7b63862c checkout: add --fetch to fetch remote before resolving start-point
     @@ Commit message
      
              git checkout --fetch -b new_branch origin/some-branch
      
     -    When --fetch is given and <start-point> names a configured remote
     -    (either bare, like "origin", or prefixed, like "origin/foo"), fetch
     -    that remote before resolving the ref. Abort the checkout if the fetch
     -    fails.
     +    When --fetch is given and <start-point> is in <remote>/<branch> form,
     +    run "git fetch <remote> <branch>" before resolving the ref. This
     +    narrows the fetch to the requested branch so that other
     +    remote-tracking branches are left untouched -- many tools rely on the
     +    stability of remote-tracking refs between explicit fetches. If
     +    <start-point> is a bare remote name like "origin" (which resolves to
     +    that remote's default branch), "git fetch <remote>" is run instead,
     +    since the target branch is not known up front. Abort the checkout if
     +    the fetch fails.
      
          Also add a checkout.fetch config to enable this by default.
      
     @@ Documentation/git-checkout.adoc: linkgit:git-config[1].
       
      +`--fetch`::
      +`--no-fetch`::
     -+	If _<start-point>_ names a configured remote -- either bare,
     -+	like `origin` (which resolves to the remote's default branch),
     -+	or in _<remote>/<branch>_ form -- run `git fetch` on that
     -+	remote before resolving _<start-point>_. If the fetch fails,
     -+	the checkout is aborted and no local branch is created.
     ++	If _<start-point>_ refers to a remote-tracking branch, fetch
     ++	from that remote before resolving it. When _<start-point>_ is
     ++	in _<remote>/<branch>_ form, only that branch is updated; when
     ++	it is a bare remote name (e.g. `origin`), the whole remote is
     ++	fetched. If the fetch fails, the checkout is aborted.
      ++
      +The default behavior can be set via the `checkout.fetch` configuration
      +variable.
     @@ Documentation/git-switch.adoc: ambiguous but exists on the 'origin' remote. See
       
      +`--fetch`::
      +`--no-fetch`::
     -+	If _<start-point>_ names a configured remote -- either bare,
     -+	like `origin` (which resolves to the remote's default branch),
     -+	or in _<remote>/<branch>_ form -- run `git fetch` on that
     -+	remote before resolving _<start-point>_. If the fetch fails,
     -+	the switch is aborted and no local branch is created.
     ++	If _<start-point>_ refers to a remote-tracking branch, fetch
     ++	from that remote before resolving it. When _<start-point>_ is
     ++	in _<remote>/<branch>_ form, only that branch is updated; when
     ++	it is a bare remote name (e.g. `origin`), the whole remote is
     ++	fetched. If the fetch fails, the switch is aborted.
      ++
      +The default behavior can be set via the `checkout.fetch` configuration
      +variable.
     @@ builtin/checkout.c: struct branch_info {
      +	}
      +
      +	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
     ++	if (slash && slash[1])
     ++		strvec_push(&cmd.args, slash + 1);
      +	cmd.git_cmd = 1;
      +	free(remote_name);
      +	if (run_command(&cmd))
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD
      +'
      +
     ++test_expect_success 'checkout --fetch <remote>/<branch> leaves other tracking branches untouched' '
     ++	git checkout main &&
     ++	git -C fetch_upstream checkout -b fetch_target &&
     ++	test_commit -C fetch_upstream u_target_pre &&
     ++	git -C fetch_upstream checkout -b fetch_other &&
     ++	test_commit -C fetch_upstream u_other_pre &&
     ++	git fetch fetch_upstream &&
     ++	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
     ++	git -C fetch_upstream checkout fetch_target &&
     ++	test_commit -C fetch_upstream u_target_post &&
     ++	git -C fetch_upstream checkout fetch_other &&
     ++	test_commit -C fetch_upstream u_other_post &&
     ++	git checkout --fetch -b local_target fetch_upstream/fetch_target &&
     ++	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
     ++	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
     ++'
     ++
      +test_expect_success 'checkout --fetch with bare remote name fetches the remote' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_new2 &&
 Documentation/config/checkout.adoc |  5 +++
 Documentation/git-checkout.adoc    | 11 +++++
 Documentation/git-switch.adoc      | 11 +++++
 builtin/checkout.c                 | 50 +++++++++++++++++++++-
 t/t7201-co.sh                      | 68 ++++++++++++++++++++++++++++++
 t/t9902-completion.sh              |  1 +
 6 files changed, 144 insertions(+), 2 deletions(-)
Show changes to 6 files +144 −2

Documentation/config/checkout.adoc, Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh, t/t9902-completion.sh

diff --git a/Documentation/config/checkout.adoc b/Documentation/config/checkout.adoc
index e35d212969..c95f72b38e 100644
--- a/Documentation/config/checkout.adoc
+++ b/Documentation/config/checkout.adoc
@@ -22,6 +22,11 @@ commands or functionality in the future.
 	option in `git checkout` and `git switch`. See
 	linkgit:git-switch[1] and linkgit:git-checkout[1].
 
+`checkout.fetch`::
+	Provides the default value for the `--fetch` or `--no-fetch`
+	option in `git checkout` and `git switch`. See
+	linkgit:git-switch[1] and linkgit:git-checkout[1].
+
 `checkout.workers`::
 	The number of parallel workers to use when updating the working tree.
 	The default is one, i.e. sequential execution. If set to a value less
diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index 43ccf47cf6..f5cc1ced74 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -201,6 +201,17 @@ linkgit:git-config[1].
 The default behavior can be set via the `checkout.guess` configuration
 variable.
 
+`--fetch`::
+`--no-fetch`::
+	If _<start-point>_ refers to a remote-tracking branch, fetch
+	from that remote before resolving it. When _<start-point>_ is
+	in _<remote>/<branch>_ form, only that branch is updated; when
+	it is a bare remote name (e.g. `origin`), the whole remote is
+	fetched. If the fetch fails, the checkout is aborted.
++
+The default behavior can be set via the `checkout.fetch` configuration
+variable.
+
 `-l`::
 	Create the new branch's reflog; see linkgit:git-branch[1] for
 	details.
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index 87707e9265..29743bafea 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -110,6 +110,17 @@ ambiguous but exists on the 'origin' remote. See also
 The default behavior can be set via the `checkout.guess` configuration
 variable.
 
+`--fetch`::
+`--no-fetch`::
+	If _<start-point>_ refers to a remote-tracking branch, fetch
+	from that remote before resolving it. When _<start-point>_ is
+	in _<remote>/<branch>_ form, only that branch is updated; when
+	it is a bare remote name (e.g. `origin`), the whole remote is
+	fetched. If the fetch fails, the switch is aborted.
++
+The default behavior can be set via the `checkout.fetch` configuration
+variable.
+
 `-f`::
 `--force`::
 	An alias for `--discard-changes`.
diff --git a/builtin/checkout.c b/builtin/checkout.c
index e031e61886..8d810fe2fa 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -30,7 +30,9 @@
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "setup.h"
+#include "strvec.h"
 #include "submodule.h"
 #include "symlinks.h"
 #include "trace2.h"
@@ -61,6 +63,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -112,6 +115,36 @@ struct branch_info {
 	char *checkout;
 };
 
+static void fetch_remote_for_start_point(const char *arg)
+{
+	const char *slash;
+	char *remote_name;
+	struct remote *remote;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+
+	if (!arg || !*arg)
+		return;
+
+	slash = strchr(arg, '/');
+	if (slash == arg)
+		return;
+	remote_name = slash ? xstrndup(arg, slash - arg) : xstrdup(arg);
+
+	remote = remote_get(remote_name);
+	if (!remote || !remote_is_configured(remote, 1)) {
+		free(remote_name);
+		return;
+	}
+
+	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
+	if (slash && slash[1])
+		strvec_push(&cmd.args, slash + 1);
+	cmd.git_cmd = 1;
+	free(remote_name);
+	if (run_command(&cmd))
+		die(_("failed to fetch start-point '%s'"), arg);
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1237,6 +1270,10 @@ static int git_checkout_config(const char *var, const char *value,
 		opts->dwim_new_local_branch = git_config_bool(var, value);
 		return 0;
 	}
+	if (!strcmp(var, "checkout.fetch")) {
+		opts->fetch = git_config_bool(var, value);
+		return 0;
+	}
 
 	if (starts_with(var, "submodule."))
 		return git_default_submodule_config(var, value, NULL);
@@ -1942,8 +1979,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0]);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
@@ -2052,6 +2094,8 @@ int cmd_checkout(int argc,
 		OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
 		OPT_BOOL(0, "auto-advance", &opts.auto_advance,
 			 N_("auto advance to the next file when selecting hunks interactively")),
+		OPT_BOOL(0, "fetch", &opts.fetch,
+			 N_("fetch from the remote first if <start-point> is a remote-tracking branch")),
 		OPT_END()
 	};
 
@@ -2102,6 +2146,8 @@ int cmd_switch(int argc,
 			 N_("second guess 'git switch <no-such-branch>'")),
 		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
 			 N_("throw away local modifications")),
+		OPT_BOOL(0, "fetch", &opts.fetch,
+			 N_("fetch from the remote first if <start-point> is a remote-tracking branch")),
 		OPT_END()
 	};
 
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 9bcf7c0b40..cf2ceb4052 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -801,4 +801,72 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD
+'
+
+test_expect_success 'checkout --fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
+'
+
+test_expect_success 'checkout --fetch with bare remote name fetches the remote' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_new2 &&
+	test_commit -C fetch_upstream u_new2 &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2 &&
+	git checkout --fetch -b local_from_remote fetch_upstream &&
+	git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2
+'
+
+test_expect_success 'checkout --fetch aborts and does not create branch on fetch failure' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout.fetch=true enables fetching without --fetch' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_cfg &&
+	test_commit -C fetch_upstream u_cfg &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_cfg &&
+	git -c checkout.fetch=true checkout -b local_cfg fetch_upstream/fetch_cfg &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_cfg HEAD
+'
+
+test_expect_success 'switch --fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 2f9a597ec7..dc1d63669f 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -2602,6 +2602,7 @@ test_expect_success 'double dash "git checkout"' '
 	--ignore-other-worktrees Z
 	--recurse-submodules Z
 	--auto-advance Z
+	--fetch Z
 	--progress Z
 	--guess Z
 	--no-guess Z

base-commit: 94f057755b7941b321fd11fec1b2e3ca5313a4e0
-- 
gitgitgadget
Harald NordgrenApr 26, 2026, 15:15 UTC in reply to Kristoffer Haugsbakk on lore

Re: [PATCH] remote: add --set-head option to 'git remote add'

Show 12 quoted lines
> I don’t understand why you change the email subjects so often. Right now
> I had three “Wrong subject line” in my inbox with lost threading
> (webmail client) with the only way to distinguish them being that I was
> the the CC on this one.
> 
> Most of the time whole 100-email threads like patch series never change
> the subject. And to me it is easier to keep track of those “RE: [PATCH
> v5] florb: drop glorb” than if someone changes the subject to e.g.
> “Regarding memory leaks” because someone found a memory leak in a
> review. Because that was a reply to an email from two days ago, but I’ve
> been a away for a week so I think it’s a new thread about
> something else.

I got some feedback before, not from you, that subject lines should be more varied, probably there is a golden middle that I need to find.

And I fundamentally agree with you.
Harald
Ramsay JonesApr 26, 2026, 15:54 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH v3] checkout: add --fetch to fetch remote before resolving start-point

On 26/04/2026 8:24 am, Harald Nordgren via GitGitGadget wrote:
> From: Harald Nordgren <haraldnordgren@gmail.com>
> 
[snip]
Show 77 quoted lines
> diff --git a/t/t7201-co.sh b/t/t7201-co.sh
> index 9bcf7c0b40..cf2ceb4052 100755
> --- a/t/t7201-co.sh
> +++ b/t/t7201-co.sh
> @@ -801,4 +801,72 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
>  	test_cmp_config "" --default "" branch.main2.merge
>  '
>  
> +test_expect_success 'setup upstream for --fetch tests' '
> +	git checkout main &&
> +	git init fetch_upstream &&
> +	test_commit -C fetch_upstream u_main &&
> +	git remote add fetch_upstream fetch_upstream &&
> +	git fetch fetch_upstream &&
> +	git -C fetch_upstream checkout -b fetch_new &&
> +	test_commit -C fetch_upstream u_new
> +'
> +
> +test_expect_success 'checkout --fetch -b picks up branch created upstream after clone' '
> +	git checkout main &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
> +	git checkout --fetch -b local_new fetch_upstream/fetch_new &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD
> +'
> +
> +test_expect_success 'checkout --fetch <remote>/<branch> leaves other tracking branches untouched' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_target &&
> +	test_commit -C fetch_upstream u_target_pre &&
> +	git -C fetch_upstream checkout -b fetch_other &&
> +	test_commit -C fetch_upstream u_other_pre &&
> +	git fetch fetch_upstream &&
> +	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
> +	git -C fetch_upstream checkout fetch_target &&
> +	test_commit -C fetch_upstream u_target_post &&
> +	git -C fetch_upstream checkout fetch_other &&
> +	test_commit -C fetch_upstream u_other_post &&
> +	git checkout --fetch -b local_target fetch_upstream/fetch_target &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
> +	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
> +'
> +
> +test_expect_success 'checkout --fetch with bare remote name fetches the remote' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_new2 &&
> +	test_commit -C fetch_upstream u_new2 &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2 &&
> +	git checkout --fetch -b local_from_remote fetch_upstream &&
> +	git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2
> +'
> +
> +test_expect_success 'checkout --fetch aborts and does not create branch on fetch failure' '
> +	git checkout main &&
> +	test_might_fail git branch -D bogus &&
> +	test_must_fail git checkout --fetch -b bogus fetch_upstream/does_not_exist &&
> +	test_must_fail git rev-parse --verify refs/heads/bogus
> +'
> +
> +test_expect_success 'checkout.fetch=true enables fetching without --fetch' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_cfg &&
> +	test_commit -C fetch_upstream u_cfg &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_cfg &&
> +	git -c checkout.fetch=true checkout -b local_cfg fetch_upstream/fetch_cfg &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_cfg HEAD
> +'
> +
> +test_expect_success 'switch --fetch -c picks up branch created upstream after clone' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_switch &&
> +	test_commit -C fetch_upstream u_switch &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
> +	git switch --fetch -c local_switch fetch_upstream/fetch_switch &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
> +'
> +
>  test_done
Still just skimming the list, so ... ;)

I seem to have missed v2 (but I guess the config name changed in v2), but it seems that there is still no test that confirms '--no-fetch' can countermand the config variable (or, indeed, an earlier command-line '--fetch' etc,.).

[I would have no use for this facility (I have _never_ used git-pull for similar reasons) since I would find it odd to 'mash' git-fetch into git-checkout/switch! :) ]

ATB, Ramsay Jones

Harald Nordgren via GitGitGadgetApr 26, 2026, 18:32 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v4] checkout: add --fetch to fetch remote before resolving start-point

From: Harald Nordgren <haraldnordgren@gmail.com>
A common workflow is:
    git fetch origin
    git checkout -b new_branch origin/some-branch

The first command exists purely so the second sees an up-to-date view of the remote. If it is forgotten, origin/some-branch points at a stale commit and the new local branch is created from the wrong start point.

Teach checkout (and switch) a --fetch flag that folds the two steps into one:

    git checkout --fetch -b new_branch origin/some-branch

When --fetch is given and <start-point> is in <remote>/<branch> form, run "git fetch <remote> <branch>" before resolving the ref. This narrows the fetch to the requested branch so that other remote-tracking branches are left untouched -- many tools rely on the stability of remote-tracking refs between explicit fetches. If <start-point> is a bare remote name like "origin" (which resolves to that remote's default branch), "git fetch <remote>" is run instead, since the target branch is not known up front. Abort the checkout if the fetch fails.

Also add a checkout.fetch config to enable this by default.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
    checkout: add --fetch to fetch remote before resolving start-point
    
    Adding tests to confirm that '--no-fetch' can countermand the config.
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v4
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v4
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v3:
 1:  df7b63862c ! 1:  150ccbb621 checkout: add --fetch to fetch remote before resolving start-point
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_cmp_rev refs/remotes/fetch_upstream/fetch_cfg HEAD
      +'
      +
     ++test_expect_success '--no-fetch overrides checkout.fetch=true' '
     ++	git checkout main &&
     ++	git -C fetch_upstream checkout -b fetch_nofetch &&
     ++	test_commit -C fetch_upstream u_nofetch &&
     ++	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_nofetch &&
     ++	test_must_fail git -c checkout.fetch=true checkout --no-fetch \
     ++		-b local_nofetch fetch_upstream/fetch_nofetch &&
     ++	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_nofetch &&
     ++	test_must_fail git rev-parse --verify refs/heads/local_nofetch
     ++'
     ++
     ++test_expect_success '--no-fetch overrides earlier --fetch on command line' '
     ++	git checkout main &&
     ++	git -C fetch_upstream checkout -b fetch_override &&
     ++	test_commit -C fetch_upstream u_override &&
     ++	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_override &&
     ++	test_must_fail git checkout --fetch --no-fetch \
     ++		-b local_override fetch_upstream/fetch_override &&
     ++	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_override &&
     ++	test_must_fail git rev-parse --verify refs/heads/local_override
     ++'
     ++
      +test_expect_success 'switch --fetch -c picks up branch created upstream after clone' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_switch &&
 Documentation/config/checkout.adoc |  5 ++
 Documentation/git-checkout.adoc    | 11 ++++
 Documentation/git-switch.adoc      | 11 ++++
 builtin/checkout.c                 | 50 ++++++++++++++++-
 t/t7201-co.sh                      | 90 ++++++++++++++++++++++++++++++
 t/t9902-completion.sh              |  1 +
 6 files changed, 166 insertions(+), 2 deletions(-)
Show changes to 6 files +166 −2

Documentation/config/checkout.adoc, Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh, t/t9902-completion.sh

diff --git a/Documentation/config/checkout.adoc b/Documentation/config/checkout.adoc
index e35d212969..c95f72b38e 100644
--- a/Documentation/config/checkout.adoc
+++ b/Documentation/config/checkout.adoc
@@ -22,6 +22,11 @@ commands or functionality in the future.
 	option in `git checkout` and `git switch`. See
 	linkgit:git-switch[1] and linkgit:git-checkout[1].
 
+`checkout.fetch`::
+	Provides the default value for the `--fetch` or `--no-fetch`
+	option in `git checkout` and `git switch`. See
+	linkgit:git-switch[1] and linkgit:git-checkout[1].
+
 `checkout.workers`::
 	The number of parallel workers to use when updating the working tree.
 	The default is one, i.e. sequential execution. If set to a value less
diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index 43ccf47cf6..f5cc1ced74 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -201,6 +201,17 @@ linkgit:git-config[1].
 The default behavior can be set via the `checkout.guess` configuration
 variable.
 
+`--fetch`::
+`--no-fetch`::
+	If _<start-point>_ refers to a remote-tracking branch, fetch
+	from that remote before resolving it. When _<start-point>_ is
+	in _<remote>/<branch>_ form, only that branch is updated; when
+	it is a bare remote name (e.g. `origin`), the whole remote is
+	fetched. If the fetch fails, the checkout is aborted.
++
+The default behavior can be set via the `checkout.fetch` configuration
+variable.
+
 `-l`::
 	Create the new branch's reflog; see linkgit:git-branch[1] for
 	details.
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index 87707e9265..29743bafea 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -110,6 +110,17 @@ ambiguous but exists on the 'origin' remote. See also
 The default behavior can be set via the `checkout.guess` configuration
 variable.
 
+`--fetch`::
+`--no-fetch`::
+	If _<start-point>_ refers to a remote-tracking branch, fetch
+	from that remote before resolving it. When _<start-point>_ is
+	in _<remote>/<branch>_ form, only that branch is updated; when
+	it is a bare remote name (e.g. `origin`), the whole remote is
+	fetched. If the fetch fails, the switch is aborted.
++
+The default behavior can be set via the `checkout.fetch` configuration
+variable.
+
 `-f`::
 `--force`::
 	An alias for `--discard-changes`.
diff --git a/builtin/checkout.c b/builtin/checkout.c
index e031e61886..8d810fe2fa 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -30,7 +30,9 @@
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "setup.h"
+#include "strvec.h"
 #include "submodule.h"
 #include "symlinks.h"
 #include "trace2.h"
@@ -61,6 +63,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -112,6 +115,36 @@ struct branch_info {
 	char *checkout;
 };
 
+static void fetch_remote_for_start_point(const char *arg)
+{
+	const char *slash;
+	char *remote_name;
+	struct remote *remote;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+
+	if (!arg || !*arg)
+		return;
+
+	slash = strchr(arg, '/');
+	if (slash == arg)
+		return;
+	remote_name = slash ? xstrndup(arg, slash - arg) : xstrdup(arg);
+
+	remote = remote_get(remote_name);
+	if (!remote || !remote_is_configured(remote, 1)) {
+		free(remote_name);
+		return;
+	}
+
+	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
+	if (slash && slash[1])
+		strvec_push(&cmd.args, slash + 1);
+	cmd.git_cmd = 1;
+	free(remote_name);
+	if (run_command(&cmd))
+		die(_("failed to fetch start-point '%s'"), arg);
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1237,6 +1270,10 @@ static int git_checkout_config(const char *var, const char *value,
 		opts->dwim_new_local_branch = git_config_bool(var, value);
 		return 0;
 	}
+	if (!strcmp(var, "checkout.fetch")) {
+		opts->fetch = git_config_bool(var, value);
+		return 0;
+	}
 
 	if (starts_with(var, "submodule."))
 		return git_default_submodule_config(var, value, NULL);
@@ -1942,8 +1979,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0]);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
@@ -2052,6 +2094,8 @@ int cmd_checkout(int argc,
 		OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
 		OPT_BOOL(0, "auto-advance", &opts.auto_advance,
 			 N_("auto advance to the next file when selecting hunks interactively")),
+		OPT_BOOL(0, "fetch", &opts.fetch,
+			 N_("fetch from the remote first if <start-point> is a remote-tracking branch")),
 		OPT_END()
 	};
 
@@ -2102,6 +2146,8 @@ int cmd_switch(int argc,
 			 N_("second guess 'git switch <no-such-branch>'")),
 		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
 			 N_("throw away local modifications")),
+		OPT_BOOL(0, "fetch", &opts.fetch,
+			 N_("fetch from the remote first if <start-point> is a remote-tracking branch")),
 		OPT_END()
 	};
 
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 9bcf7c0b40..731be2680a 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -801,4 +801,94 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD
+'
+
+test_expect_success 'checkout --fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
+'
+
+test_expect_success 'checkout --fetch with bare remote name fetches the remote' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_new2 &&
+	test_commit -C fetch_upstream u_new2 &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2 &&
+	git checkout --fetch -b local_from_remote fetch_upstream &&
+	git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2
+'
+
+test_expect_success 'checkout --fetch aborts and does not create branch on fetch failure' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout.fetch=true enables fetching without --fetch' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_cfg &&
+	test_commit -C fetch_upstream u_cfg &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_cfg &&
+	git -c checkout.fetch=true checkout -b local_cfg fetch_upstream/fetch_cfg &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_cfg HEAD
+'
+
+test_expect_success '--no-fetch overrides checkout.fetch=true' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_nofetch &&
+	test_commit -C fetch_upstream u_nofetch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_nofetch &&
+	test_must_fail git -c checkout.fetch=true checkout --no-fetch \
+		-b local_nofetch fetch_upstream/fetch_nofetch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_nofetch &&
+	test_must_fail git rev-parse --verify refs/heads/local_nofetch
+'
+
+test_expect_success '--no-fetch overrides earlier --fetch on command line' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_override &&
+	test_commit -C fetch_upstream u_override &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_override &&
+	test_must_fail git checkout --fetch --no-fetch \
+		-b local_override fetch_upstream/fetch_override &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_override &&
+	test_must_fail git rev-parse --verify refs/heads/local_override
+'
+
+test_expect_success 'switch --fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 2f9a597ec7..dc1d63669f 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -2602,6 +2602,7 @@ test_expect_success 'double dash "git checkout"' '
 	--ignore-other-worktrees Z
 	--recurse-submodules Z
 	--auto-advance Z
+	--fetch Z
 	--progress Z
 	--guess Z
 	--no-guess Z

base-commit: 94f057755b7941b321fd11fec1b2e3ca5313a4e0
-- 
gitgitgadget
Junio C HamanoApr 28, 2026, 01:47 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH v4] checkout: add --fetch to fetch remote before resolving start-point

"Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
> From: Harald Nordgren <haraldnordgren@gmail.com>
Show 7 quoted lines
> A common workflow is:
>
>     git fetch origin
>     git checkout -b new_branch origin/some-branch
>
> The first command exists purely so the second sees an up-to-date view
> of the remote.
This is only half true, isn't it?

Git is among projects that encourage forking only from a well-known point in history (like the latest released version), not at a random "tip of the day" commit from the upstream.

Such projects also tend to discourage people from constantly pulling updated upstream into their unfinished topic branch, or rebase their unfinished topic branch on top of updated upstream, only to "catch up", and instead encourage them to make a trial merge to notice when the base got too stale to cause eventual merge to conflict too much, and when it happens, make such a back-merge, but otherwise keep working on the stable base and avoid such "catching up".

And when working with such a project, what users who do the above is forgetting is to inspect origin/master between the two steps to see if it is a good commit to start your topic at.

> If it is forgotten, origin/some-branch points at a stale commit
> and the new local branch is created from the wrong start point.

So this part is not quite true. What makes your topic begin at a wrong starting point is not that you forget to fetch, but you forget to verify what you fetched and think if it is a good starting point.

And for that verification to happen, you do not want "checkout" and "fetch" mixed into one.

On the other hand, if you are allowed to fork at anywhere (as opposed to a latest release), then not fetching and building on top of slightly older codebase is not such a huge deal, as you're likely to be making the "catch up" changes on top of your unfinished work later anyway.

So as I already said before, I am fairly negative on this topic. It feels more like a knob to allow and actively encourage people to be more sloppy than anything else.

I may have already pointed this out (but I do not remember), but this option would not make any sense when --track is not in effect, so instead of adding a brand new option, making it an extension to the existing --track option might make it slightly more palatable.

Harald NordgrenApr 28, 2026, 08:44 UTC in reply to Junio C Hamano on lore

Re: [PATCH] checkout: add --fetch to fetch remote before resolving start-point

I hope you had a good leave and is back with renewed energy! ☀️
> Git is among projects that encourage forking only from a well-known
> point in history (like the latest released version), not at a random
> "tip of the day" commit from the upstream.

Are you talking about the Git project that we are working on right now, or talking about how people use Git "in the wild"?

Because how people use Git in the wild can be a bit different, and merge conflicts arguably the worst part of collaborating with a team using Git. In my early days as a professional coder, snubbed my toe countless times on forgetting to pull in the latest changes, before starting to work on something.

I respect that things work differently in a neatly ordered project like Git itself, where you do a great work of organizing, but all other projects are not like that. My advice to a junior developer is to pull in the latest changes when starting and to rebase obsessively to prevent a large merge conflict down the road.

> So instead of introducing a totally new option that can only be used
> only when "--track" is given, it might make more sense to introduce
> this as a variant of "--track", perhaps "--track=fetch,[in]direct"
> or something like that. 
> I may have already pointed this out (but I do not remember), but
> this option would not make any sense when --track is not in effect,
> so instead of adding a brand new option, making it an extension to
> the existing --track option might make it slightly more palatable.
Fair enough. You did point it out and I will give that a try!
Harald
Harald Nordgren via GitGitGadgetApr 28, 2026, 09:03 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v5] checkout: extend --track with a "fetch" mode to refresh start-point

From: Harald Nordgren <haraldnordgren@gmail.com>
A common workflow is:
    git fetch origin
    git checkout -b new_branch --track origin/some-branch

The first command exists so the second sees an up-to-date view of the remote. If it is forgotten, origin/some-branch points at a stale commit and the new local branch is created from the wrong start point. This only matters when the user is setting up tracking and expects the new branch to start at the freshest tip; for a one-off checkout of an arbitrary commit there is no reason to "freshen" the start-point.

Tie the new behavior to --track for that reason: extend its argument to take a comma-separated list, where "fetch" can be combined with the existing "direct" (default) and "inherit" modes. Examples:

    git checkout --track=fetch -b new_branch origin/some-branch
    git checkout --track=fetch,inherit -b new_branch some_local_branch
    git switch --track=fetch -c new_branch origin/some-branch

When "fetch" is requested and <start-point> is in <remote>/<branch> form, run "git fetch <remote> <branch>" before resolving the ref. This narrows the fetch to the requested branch so that other remote-tracking branches are left untouched -- many tools rely on the stability of remote-tracking refs between explicit fetches. If <start-point> is a bare remote name like "origin" (which resolves to that remote's default branch), "git fetch <remote>" is run instead, since the target branch is not known up front. Abort the checkout if the fetch fails.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
    checkout: add --fetch to fetch remote before resolving start-point
    
     * Folded --fetch into --track. The standalone --fetch/--no-fetch flags
       are gone; the same behavior is now requested via --track=fetch
       (combinable as --track=fetch,inherit).
     * Removed the checkout.fetch config. Since fetching is tied to --track,
       there's no separate config knob anymore.
     * Docs reworked accordingly. --track's syntax is now
       (direct|inherit|fetch)[,...] in both git-checkout and git-switch man
       pages, with the fetch behavior described under it. The old --fetch
       and checkout.fetch sections are deleted.
     * New parser callback in checkout.c. A small parse_opt_checkout_track
       splits the comma-separated argument with string_list_split and sets
       opts->track and opts->fetch together.
     * Tests updated and trimmed. All test invocations switched from --fetch
       to --track=fetch. Dropped the checkout.fetch=true and --no-fetch
       override tests (those features no longer exist). Added a
       --track=fetch,inherit test, a --track=bogus error test, and stronger
       config-assertion checks on the basic test. Two redundant tests
       (fetch,direct and order-insensitivity) were removed.
     * Completion list cleaned up. --fetch removed from the expected git
       checkout option list.
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v5
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v5
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v4:
 1:  150ccbb621 ! 1:  8ebc2f94b9 checkout: add --fetch to fetch remote before resolving start-point
     @@ Metadata
      Author: Harald Nordgren <haraldnordgren@gmail.com>
      
       ## Commit message ##
     -    checkout: add --fetch to fetch remote before resolving start-point
     +    checkout: extend --track with a "fetch" mode to refresh start-point
      
          A common workflow is:
      
              git fetch origin
     -        git checkout -b new_branch origin/some-branch
     +        git checkout -b new_branch --track origin/some-branch
      
     -    The first command exists purely so the second sees an up-to-date view
     -    of the remote. If it is forgotten, origin/some-branch points at a stale
     -    commit and the new local branch is created from the wrong start point.
     +    The first command exists so the second sees an up-to-date view of the
     +    remote. If it is forgotten, origin/some-branch points at a stale
     +    commit and the new local branch is created from the wrong start
     +    point. This only matters when the user is setting up tracking and
     +    expects the new branch to start at the freshest tip; for a one-off
     +    checkout of an arbitrary commit there is no reason to "freshen" the
     +    start-point.
      
     -    Teach checkout (and switch) a --fetch flag that folds the two steps
     -    into one:
     +    Tie the new behavior to --track for that reason: extend its argument
     +    to take a comma-separated list, where "fetch" can be combined with the
     +    existing "direct" (default) and "inherit" modes. Examples:
      
     -        git checkout --fetch -b new_branch origin/some-branch
     +        git checkout --track=fetch -b new_branch origin/some-branch
     +        git checkout --track=fetch,inherit -b new_branch some_local_branch
     +        git switch --track=fetch -c new_branch origin/some-branch
      
     -    When --fetch is given and <start-point> is in <remote>/<branch> form,
     -    run "git fetch <remote> <branch>" before resolving the ref. This
     +    When "fetch" is requested and <start-point> is in <remote>/<branch>
     +    form, run "git fetch <remote> <branch>" before resolving the ref. This
          narrows the fetch to the requested branch so that other
          remote-tracking branches are left untouched -- many tools rely on the
          stability of remote-tracking refs between explicit fetches. If
     @@ Commit message
          since the target branch is not known up front. Abort the checkout if
          the fetch fails.
      
     -    Also add a checkout.fetch config to enable this by default.
     -
          Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
      
     - ## Documentation/config/checkout.adoc ##
     -@@ Documentation/config/checkout.adoc: commands or functionality in the future.
     - 	option in `git checkout` and `git switch`. See
     - 	linkgit:git-switch[1] and linkgit:git-checkout[1].
     - 
     -+`checkout.fetch`::
     -+	Provides the default value for the `--fetch` or `--no-fetch`
     -+	option in `git checkout` and `git switch`. See
     -+	linkgit:git-switch[1] and linkgit:git-checkout[1].
     -+
     - `checkout.workers`::
     - 	The number of parallel workers to use when updating the working tree.
     - 	The default is one, i.e. sequential execution. If set to a value less
     -
       ## Documentation/git-checkout.adoc ##
     -@@ Documentation/git-checkout.adoc: linkgit:git-config[1].
     - The default behavior can be set via the `checkout.guess` configuration
     - variable.
     +@@ Documentation/git-checkout.adoc: of it").
     + 	resets _<branch>_ to the start point instead of failing.
       
     -+`--fetch`::
     -+`--no-fetch`::
     -+	If _<start-point>_ refers to a remote-tracking branch, fetch
     -+	from that remote before resolving it. When _<start-point>_ is
     -+	in _<remote>/<branch>_ form, only that branch is updated; when
     -+	it is a bare remote name (e.g. `origin`), the whole remote is
     -+	fetched. If the fetch fails, the checkout is aborted.
     + `-t`::
     +-`--track[=(direct|inherit)]`::
     ++`--track[=(direct|inherit|fetch)[,...]]`::
     + 	When creating a new branch, set up "upstream" configuration. See
     + 	`--track` in linkgit:git-branch[1] for details. As a convenience,
     + 	--track without -b implies branch creation.
     + +
     ++The argument is a comma-separated list. `direct` (the default) and
     ++`inherit` select the tracking mode. Adding `fetch` requests that the
     ++remote be fetched before _<start-point>_ is resolved, so the new branch
     ++starts from a fresh tip: when _<start-point>_ is in
     ++_<remote>/<branch>_ form, only that branch is updated; when it is a
     ++bare remote name (e.g. `origin`), the whole remote is fetched. If the
     ++fetch fails, the checkout is aborted.
      ++
     -+The default behavior can be set via the `checkout.fetch` configuration
     -+variable.
     -+
     - `-l`::
     - 	Create the new branch's reflog; see linkgit:git-branch[1] for
     - 	details.
     + If no `-b` option is given, the name of the new branch will be
     + derived from the remote-tracking branch, by looking at the local part of
     + the refspec configured for the corresponding remote, and then stripping
      
       ## Documentation/git-switch.adoc ##
     -@@ Documentation/git-switch.adoc: ambiguous but exists on the 'origin' remote. See also
     - The default behavior can be set via the `checkout.guess` configuration
     - variable.
     +@@ Documentation/git-switch.adoc: should result in deletion of the path).
     + 	attached to a terminal, regardless of `--quiet`.
       
     -+`--fetch`::
     -+`--no-fetch`::
     -+	If _<start-point>_ refers to a remote-tracking branch, fetch
     -+	from that remote before resolving it. When _<start-point>_ is
     -+	in _<remote>/<branch>_ form, only that branch is updated; when
     -+	it is a bare remote name (e.g. `origin`), the whole remote is
     -+	fetched. If the fetch fails, the switch is aborted.
     + `-t`::
     +-`--track[ (direct|inherit)]`::
     ++`--track[=(direct|inherit|fetch)[,...]]`::
     + 	When creating a new branch, set up "upstream" configuration.
     + 	`-c` is implied. See `--track` in linkgit:git-branch[1] for
     + 	details.
     + +
     ++The argument is a comma-separated list. `direct` (the default) and
     ++`inherit` select the tracking mode. Adding `fetch` requests that the
     ++remote be fetched before _<start-point>_ is resolved, so the new branch
     ++starts from a fresh tip: when _<start-point>_ is in
     ++_<remote>/<branch>_ form, only that branch is updated; when it is a
     ++bare remote name (e.g. `origin`), the whole remote is fetched. If the
     ++fetch fails, the switch is aborted.
      ++
     -+The default behavior can be set via the `checkout.fetch` configuration
     -+variable.
     -+
     - `-f`::
     - `--force`::
     - 	An alias for `--discard-changes`.
     + If no `-c` option is given, the name of the new branch will be derived
     + from the remote-tracking branch, by looking at the local part of the
     + refspec configured for the corresponding remote, and then stripping
      
       ## builtin/checkout.c ##
      @@
     @@ builtin/checkout.c: struct branch_info {
      +	if (run_command(&cmd))
      +		die(_("failed to fetch start-point '%s'"), arg);
      +}
     ++
     ++static int parse_opt_checkout_track(const struct option *opt,
     ++				    const char *arg, int unset)
     ++{
     ++	struct checkout_opts *opts = opt->value;
     ++	struct string_list tokens = STRING_LIST_INIT_DUP;
     ++	struct string_list_item *item;
     ++	int ret = 0;
     ++
     ++	if (unset) {
     ++		opts->track = BRANCH_TRACK_NEVER;
     ++		opts->fetch = 0;
     ++		return 0;
     ++	}
     ++
     ++	opts->track = BRANCH_TRACK_EXPLICIT;
     ++	if (!arg)
     ++		return 0;
     ++
     ++	string_list_split(&tokens, arg, ",", -1);
     ++	for_each_string_list_item(item, &tokens) {
     ++		if (!strcmp(item->string, "fetch")) {
     ++			opts->fetch = 1;
     ++		} else if (!strcmp(item->string, "direct")) {
     ++			opts->track = BRANCH_TRACK_EXPLICIT;
     ++		} else if (!strcmp(item->string, "inherit")) {
     ++			opts->track = BRANCH_TRACK_INHERIT;
     ++		} else {
     ++			ret = error(_("option `%s' expects \"%s\", \"%s\", "
     ++				      "or \"%s\""),
     ++				    "--track", "direct", "inherit", "fetch");
     ++			break;
     ++		}
     ++	}
     ++
     ++	string_list_clear(&tokens, 0);
     ++	return ret;
     ++}
      +
       static void branch_info_release(struct branch_info *info)
       {
     @@ builtin/checkout.c: static int git_checkout_config(const char *var, const char *
       		opts->dwim_new_local_branch = git_config_bool(var, value);
       		return 0;
       	}
     -+	if (!strcmp(var, "checkout.fetch")) {
     -+		opts->fetch = git_config_bool(var, value);
     -+		return 0;
     -+	}
     - 
     +-
       	if (starts_with(var, "submodule."))
       		return git_default_submodule_config(var, value, NULL);
     + 
     +@@ builtin/checkout.c: static struct option *add_common_switch_branch_options(
     + {
     + 	struct option options[] = {
     + 		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
     +-		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
     ++		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
     + 			N_("set branch tracking configuration"),
     + 			PARSE_OPT_OPTARG,
     +-			parse_opt_tracking_mode),
     ++			parse_opt_checkout_track),
     + 		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
     + 			   PARSE_OPT_NOCOMPLETE),
     + 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
      @@ builtin/checkout.c: static int checkout_main(int argc, const char **argv, const char *prefix,
       			opts->dwim_new_local_branch &&
       			opts->track == BRANCH_TRACK_UNSPECIFIED &&
     @@ builtin/checkout.c: static int checkout_main(int argc, const char **argv, const
       		argv += n;
       		argc -= n;
       	} else if (!opts->accept_ref && opts->from_treeish) {
     -@@ builtin/checkout.c: int cmd_checkout(int argc,
     - 		OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
     - 		OPT_BOOL(0, "auto-advance", &opts.auto_advance,
     - 			 N_("auto advance to the next file when selecting hunks interactively")),
     -+		OPT_BOOL(0, "fetch", &opts.fetch,
     -+			 N_("fetch from the remote first if <start-point> is a remote-tracking branch")),
     - 		OPT_END()
     - 	};
     - 
     -@@ builtin/checkout.c: int cmd_switch(int argc,
     - 			 N_("second guess 'git switch <no-such-branch>'")),
     - 		OPT_BOOL(0, "discard-changes", &opts.discard_changes,
     - 			 N_("throw away local modifications")),
     -+		OPT_BOOL(0, "fetch", &opts.fetch,
     -+			 N_("fetch from the remote first if <start-point> is a remote-tracking branch")),
     - 		OPT_END()
     - 	};
     - 
      
       ## t/t7201-co.sh ##
      @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
       	test_cmp_config "" --default "" branch.main2.merge
       '
       
     -+test_expect_success 'setup upstream for --fetch tests' '
     ++test_expect_success 'setup upstream for --track=fetch tests' '
      +	git checkout main &&
      +	git init fetch_upstream &&
      +	test_commit -C fetch_upstream u_main &&
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_commit -C fetch_upstream u_new
      +'
      +
     -+test_expect_success 'checkout --fetch -b picks up branch created upstream after clone' '
     ++test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
      +	git checkout main &&
      +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
     -+	git checkout --fetch -b local_new fetch_upstream/fetch_new &&
     -+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD
     ++	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
     ++	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
     ++	test_cmp_config fetch_upstream branch.local_new.remote &&
     ++	test_cmp_config refs/heads/fetch_new branch.local_new.merge
      +'
      +
     -+test_expect_success 'checkout --fetch <remote>/<branch> leaves other tracking branches untouched' '
     ++test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_target &&
      +	test_commit -C fetch_upstream u_target_pre &&
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_commit -C fetch_upstream u_target_post &&
      +	git -C fetch_upstream checkout fetch_other &&
      +	test_commit -C fetch_upstream u_other_post &&
     -+	git checkout --fetch -b local_target fetch_upstream/fetch_target &&
     ++	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
      +	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
      +	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
      +'
      +
     -+test_expect_success 'checkout --fetch with bare remote name fetches the remote' '
     ++test_expect_success 'checkout --track=fetch with bare remote name fetches the remote' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_new2 &&
      +	test_commit -C fetch_upstream u_new2 &&
      +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2 &&
     -+	git checkout --fetch -b local_from_remote fetch_upstream &&
     ++	git checkout --track=fetch -b local_from_remote fetch_upstream &&
      +	git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2
      +'
      +
     -+test_expect_success 'checkout --fetch aborts and does not create branch on fetch failure' '
     ++test_expect_success 'checkout --track=fetch aborts and does not create branch on fetch failure' '
      +	git checkout main &&
      +	test_might_fail git branch -D bogus &&
     -+	test_must_fail git checkout --fetch -b bogus fetch_upstream/does_not_exist &&
     ++	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
      +	test_must_fail git rev-parse --verify refs/heads/bogus
      +'
      +
     -+test_expect_success 'checkout.fetch=true enables fetching without --fetch' '
     ++test_expect_success 'checkout --track=fetch,inherit fetches and inherits' '
      +	git checkout main &&
     -+	git -C fetch_upstream checkout -b fetch_cfg &&
     -+	test_commit -C fetch_upstream u_cfg &&
     -+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_cfg &&
     -+	git -c checkout.fetch=true checkout -b local_cfg fetch_upstream/fetch_cfg &&
     -+	test_cmp_rev refs/remotes/fetch_upstream/fetch_cfg HEAD
     -+'
     -+
     -+test_expect_success '--no-fetch overrides checkout.fetch=true' '
     ++	git -C fetch_upstream checkout -b fetch_inherit &&
     ++	test_commit -C fetch_upstream u_inherit &&
     ++	git fetch fetch_upstream fetch_inherit &&
     ++	git checkout -b base_inherit fetch_upstream/fetch_inherit &&
     ++	test_commit -C fetch_upstream u_inherit2 &&
      +	git checkout main &&
     -+	git -C fetch_upstream checkout -b fetch_nofetch &&
     -+	test_commit -C fetch_upstream u_nofetch &&
     -+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_nofetch &&
     -+	test_must_fail git -c checkout.fetch=true checkout --no-fetch \
     -+		-b local_nofetch fetch_upstream/fetch_nofetch &&
     -+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_nofetch &&
     -+	test_must_fail git rev-parse --verify refs/heads/local_nofetch
     ++	git checkout --track=fetch,inherit -b local_inherit base_inherit &&
     ++	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD &&
     ++	test_cmp_config fetch_upstream branch.local_inherit.remote &&
     ++	test_cmp_config refs/heads/fetch_inherit branch.local_inherit.merge
      +'
      +
     -+test_expect_success '--no-fetch overrides earlier --fetch on command line' '
     ++test_expect_success 'checkout --track=bogus reports an error' '
      +	git checkout main &&
     -+	git -C fetch_upstream checkout -b fetch_override &&
     -+	test_commit -C fetch_upstream u_override &&
     -+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_override &&
     -+	test_must_fail git checkout --fetch --no-fetch \
     -+		-b local_override fetch_upstream/fetch_override &&
     -+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_override &&
     -+	test_must_fail git rev-parse --verify refs/heads/local_override
     ++	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
     ++	test_grep "expects" err
      +'
      +
     -+test_expect_success 'switch --fetch -c picks up branch created upstream after clone' '
     ++test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_switch &&
      +	test_commit -C fetch_upstream u_switch &&
      +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
     -+	git switch --fetch -c local_switch fetch_upstream/fetch_switch &&
     ++	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
      +	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
      +'
      +
       test_done
     -
     - ## t/t9902-completion.sh ##
     -@@ t/t9902-completion.sh: test_expect_success 'double dash "git checkout"' '
     - 	--ignore-other-worktrees Z
     - 	--recurse-submodules Z
     - 	--auto-advance Z
     -+	--fetch Z
     - 	--progress Z
     - 	--guess Z
     - 	--no-guess Z
 Documentation/git-checkout.adoc | 10 +++-
 Documentation/git-switch.adoc   | 10 +++-
 builtin/checkout.c              | 85 +++++++++++++++++++++++++++++++--
 t/t7201-co.sh                   | 81 +++++++++++++++++++++++++++++++
 4 files changed, 179 insertions(+), 7 deletions(-)
Show changes to 4 files +179 −7

Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh

diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index 43ccf47cf6..3b8292612d 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -158,11 +158,19 @@ of it").
 	resets _<branch>_ to the start point instead of failing.
 
 `-t`::
-`--track[=(direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration. See
 	`--track` in linkgit:git-branch[1] for details. As a convenience,
 	--track without -b implies branch creation.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode. Adding `fetch` requests that the
+remote be fetched before _<start-point>_ is resolved, so the new branch
+starts from a fresh tip: when _<start-point>_ is in
+_<remote>/<branch>_ form, only that branch is updated; when it is a
+bare remote name (e.g. `origin`), the whole remote is fetched. If the
+fetch fails, the checkout is aborted.
++
 If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index 87707e9265..35a03e8a52 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -154,11 +154,19 @@ should result in deletion of the path).
 	attached to a terminal, regardless of `--quiet`.
 
 `-t`::
-`--track[ (direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration.
 	`-c` is implied. See `--track` in linkgit:git-branch[1] for
 	details.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode. Adding `fetch` requests that the
+remote be fetched before _<start-point>_ is resolved, so the new branch
+starts from a fresh tip: when _<start-point>_ is in
+_<remote>/<branch>_ form, only that branch is updated; when it is a
+bare remote name (e.g. `origin`), the whole remote is fetched. If the
+fetch fails, the switch is aborted.
++
 If no `-c` option is given, the name of the new branch will be derived
 from the remote-tracking branch, by looking at the local part of the
 refspec configured for the corresponding remote, and then stripping
diff --git a/builtin/checkout.c b/builtin/checkout.c
index e031e61886..de4d7c00c7 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -30,7 +30,9 @@
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "setup.h"
+#include "strvec.h"
 #include "submodule.h"
 #include "symlinks.h"
 #include "trace2.h"
@@ -61,6 +63,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -112,6 +115,74 @@ struct branch_info {
 	char *checkout;
 };
 
+static void fetch_remote_for_start_point(const char *arg)
+{
+	const char *slash;
+	char *remote_name;
+	struct remote *remote;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+
+	if (!arg || !*arg)
+		return;
+
+	slash = strchr(arg, '/');
+	if (slash == arg)
+		return;
+	remote_name = slash ? xstrndup(arg, slash - arg) : xstrdup(arg);
+
+	remote = remote_get(remote_name);
+	if (!remote || !remote_is_configured(remote, 1)) {
+		free(remote_name);
+		return;
+	}
+
+	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
+	if (slash && slash[1])
+		strvec_push(&cmd.args, slash + 1);
+	cmd.git_cmd = 1;
+	free(remote_name);
+	if (run_command(&cmd))
+		die(_("failed to fetch start-point '%s'"), arg);
+}
+
+static int parse_opt_checkout_track(const struct option *opt,
+				    const char *arg, int unset)
+{
+	struct checkout_opts *opts = opt->value;
+	struct string_list tokens = STRING_LIST_INIT_DUP;
+	struct string_list_item *item;
+	int ret = 0;
+
+	if (unset) {
+		opts->track = BRANCH_TRACK_NEVER;
+		opts->fetch = 0;
+		return 0;
+	}
+
+	opts->track = BRANCH_TRACK_EXPLICIT;
+	if (!arg)
+		return 0;
+
+	string_list_split(&tokens, arg, ",", -1);
+	for_each_string_list_item(item, &tokens) {
+		if (!strcmp(item->string, "fetch")) {
+			opts->fetch = 1;
+		} else if (!strcmp(item->string, "direct")) {
+			opts->track = BRANCH_TRACK_EXPLICIT;
+		} else if (!strcmp(item->string, "inherit")) {
+			opts->track = BRANCH_TRACK_INHERIT;
+		} else {
+			ret = error(_("option `%s' expects \"%s\", \"%s\", "
+				      "or \"%s\""),
+				    "--track", "direct", "inherit", "fetch");
+			break;
+		}
+	}
+
+	string_list_clear(&tokens, 0);
+	return ret;
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1237,7 +1308,6 @@ static int git_checkout_config(const char *var, const char *value,
 		opts->dwim_new_local_branch = git_config_bool(var, value);
 		return 0;
 	}
-
 	if (starts_with(var, "submodule."))
 		return git_default_submodule_config(var, value, NULL);
 
@@ -1734,10 +1804,10 @@ static struct option *add_common_switch_branch_options(
 {
 	struct option options[] = {
 		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
-		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
+		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
 			N_("set branch tracking configuration"),
 			PARSE_OPT_OPTARG,
-			parse_opt_tracking_mode),
+			parse_opt_checkout_track),
 		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
@@ -1942,8 +2012,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0]);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 9bcf7c0b40..39236dca12 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -801,4 +801,85 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --track=fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
+	test_cmp_config fetch_upstream branch.local_new.remote &&
+	test_cmp_config refs/heads/fetch_new branch.local_new.merge
+'
+
+test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
+'
+
+test_expect_success 'checkout --track=fetch with bare remote name fetches the remote' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_new2 &&
+	test_commit -C fetch_upstream u_new2 &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2 &&
+	git checkout --track=fetch -b local_from_remote fetch_upstream &&
+	git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2
+'
+
+test_expect_success 'checkout --track=fetch aborts and does not create branch on fetch failure' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout --track=fetch,inherit fetches and inherits' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit &&
+	git fetch fetch_upstream fetch_inherit &&
+	git checkout -b base_inherit fetch_upstream/fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit2 &&
+	git checkout main &&
+	git checkout --track=fetch,inherit -b local_inherit base_inherit &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD &&
+	test_cmp_config fetch_upstream branch.local_inherit.remote &&
+	test_cmp_config refs/heads/fetch_inherit branch.local_inherit.merge
+'
+
+test_expect_success 'checkout --track=bogus reports an error' '
+	git checkout main &&
+	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
+	test_grep "expects" err
+'
+
+test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done

base-commit: 94f057755b7941b321fd11fec1b2e3ca5313a4e0
-- 
gitgitgadget
Junio C HamanoMay 3, 2026, 20:59 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH v5] checkout: extend --track with a "fetch" mode to refresh start-point

"Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
Show 11 quoted lines
> From: Harald Nordgren <haraldnordgren@gmail.com>
>
> A common workflow is:
>
>     git fetch origin
>     git checkout -b new_branch --track origin/some-branch
>
> The first command exists so the second sees an up-to-date view of the
> remote. If it is forgotten, origin/some-branch points at a stale
> commit and the new local branch is created from the wrong start
> point.

As I pointed out multiple times, I prefer not to see this called "wrong". Even if you did not "forget", somebody may be pushing after you fetched and you may end up forking from a "stale" commit. So not fetching is not inherently "wrong", simply because that is how real world works. Multiple people working in a distributed environment does not give you absolute garantee that you will be "up to date", ever, which makes it wrong to call anything that is not "up to date" a "wrong starting point".

> This only matters when the user is setting up tracking and
> expects the new branch to start at the freshest tip; for a one-off
> checkout of an arbitrary commit there is no reason to "freshen" the
> start-point.
I do not think "arbitrary" fits in this workflow description.

If anything, "I'd take anything that the remote repository happens to have at the tip, even without having a chance to sanity checke if that is a good starting point" is more appropriate workflow to be described with a word "arbitrary commit".

If you are checking out without forking from there, you'd more likely be checking out the "latest" you have fetched from the other side, often knowing exactly what it is after checking it with "git show origin/$topic".

> Tie the new behavior to --track for that reason:

Notice that the reader hasn't heard what "the new behaviour" is up to this point yet?

How about rewriting everything up to and including this "Tie the new ..." line perhaps like so:

    If you want to fork your topic branch from the very latest of
    the tip of a branch your remote has, you would do:
	git fetch origin some-branch
	git checkout -b new_branch --track origin/some-branch
    Extend the "--track" option of "git checkout" and allow users to
    write
	git checkout --track=fetch -b new_branch origin/some_branch
    to (1) fetch 'some-branch' from the remote 'origin', updating
    the remote-tracking branch 'origin/some-branch', (2) arrange
    subsequent 'git pull' on 'new_branch' to interact with
    'origin/some_branch' and (3) fork 'new_branch' from it.
   
    In the value of the '--track' option, 'fetch' can be combined
    with ...
Harald Nordgren via GitGitGadgetMay 3, 2026, 22:31 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v6] checkout: extend --track with a "fetch" mode to refresh start-point

From: Harald Nordgren <haraldnordgren@gmail.com>

If you want to fork your topic branch from the very latest of the tip of a branch your remote has, you would do:

    git fetch origin some-branch
    git checkout -b new_branch --track origin/some-branch

Extend the "--track" option of "git checkout" and allow users to write

    git checkout -b new_branch --track=fetch origin/some-branch

to (1) fetch 'some-branch' from the remote 'origin', updating the remote-tracking branch 'origin/some-branch', (2) arrange subsequent 'git pull' on 'new_branch' to interact with 'origin/some-branch' and (3) fork 'new_branch' from it.

In the value of the '--track' option, 'fetch' can be combined with the existing 'direct' (default) and 'inherit' modes via a comma-separated list. Examples:

    git checkout -b new_branch --track=fetch,inherit some_local_branch
    git switch -c new_branch --track=fetch origin/some-branch

When "fetch" is requested and <start-point> is in <remote>/<branch> form, run "git fetch <remote> <branch>" before resolving the ref, so that other remote-tracking branches are left untouched. If <start-point> is a bare remote name like "origin" (which resolves to that remote's default branch), "git fetch <remote>" is run instead, since the target branch is not known up front. Abort the checkout if the fetch fails.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
    checkout: add --fetch to fetch remote before resolving start-point
    
    Commit message only, no code/doc/test changes. Restructured the opening
    around the user-visible workflow before introducing '--track=fetch',
    reordered all example invocations to ' -b/-c --track[=...] ', dropped
    the "wrong/stale start-point" and "arbitrary commit" framings, and
    trimmed the over-explanation of the narrowed fetch.
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v6
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v6
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v5:
 1:  8ebc2f94b9 ! 1:  1b42c648b9 checkout: extend --track with a "fetch" mode to refresh start-point
     @@ Metadata
       ## Commit message ##
          checkout: extend --track with a "fetch" mode to refresh start-point
      
     -    A common workflow is:
     +    If you want to fork your topic branch from the very latest of the
     +    tip of a branch your remote has, you would do:
      
     -        git fetch origin
     +        git fetch origin some-branch
              git checkout -b new_branch --track origin/some-branch
      
     -    The first command exists so the second sees an up-to-date view of the
     -    remote. If it is forgotten, origin/some-branch points at a stale
     -    commit and the new local branch is created from the wrong start
     -    point. This only matters when the user is setting up tracking and
     -    expects the new branch to start at the freshest tip; for a one-off
     -    checkout of an arbitrary commit there is no reason to "freshen" the
     -    start-point.
     +    Extend the "--track" option of "git checkout" and allow users to
     +    write
      
     -    Tie the new behavior to --track for that reason: extend its argument
     -    to take a comma-separated list, where "fetch" can be combined with the
     -    existing "direct" (default) and "inherit" modes. Examples:
     +        git checkout -b new_branch --track=fetch origin/some-branch
      
     -        git checkout --track=fetch -b new_branch origin/some-branch
     -        git checkout --track=fetch,inherit -b new_branch some_local_branch
     -        git switch --track=fetch -c new_branch origin/some-branch
     +    to (1) fetch 'some-branch' from the remote 'origin', updating the
     +    remote-tracking branch 'origin/some-branch', (2) arrange subsequent
     +    'git pull' on 'new_branch' to interact with 'origin/some-branch' and
     +    (3) fork 'new_branch' from it.
     +
     +    In the value of the '--track' option, 'fetch' can be combined with
     +    the existing 'direct' (default) and 'inherit' modes via a
     +    comma-separated list. Examples:
     +
     +        git checkout -b new_branch --track=fetch,inherit some_local_branch
     +        git switch -c new_branch --track=fetch origin/some-branch
      
          When "fetch" is requested and <start-point> is in <remote>/<branch>
     -    form, run "git fetch <remote> <branch>" before resolving the ref. This
     -    narrows the fetch to the requested branch so that other
     -    remote-tracking branches are left untouched -- many tools rely on the
     -    stability of remote-tracking refs between explicit fetches. If
     +    form, run "git fetch <remote> <branch>" before resolving the ref, so
     +    that other remote-tracking branches are left untouched. If
          <start-point> is a bare remote name like "origin" (which resolves to
          that remote's default branch), "git fetch <remote>" is run instead,
          since the target branch is not known up front. Abort the checkout if
 Documentation/git-checkout.adoc | 10 +++-
 Documentation/git-switch.adoc   | 10 +++-
 builtin/checkout.c              | 85 +++++++++++++++++++++++++++++++--
 t/t7201-co.sh                   | 81 +++++++++++++++++++++++++++++++
 4 files changed, 179 insertions(+), 7 deletions(-)
Show changes to 4 files +179 −7

Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh

diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index 43ccf47cf6..3b8292612d 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -158,11 +158,19 @@ of it").
 	resets _<branch>_ to the start point instead of failing.
 
 `-t`::
-`--track[=(direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration. See
 	`--track` in linkgit:git-branch[1] for details. As a convenience,
 	--track without -b implies branch creation.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode. Adding `fetch` requests that the
+remote be fetched before _<start-point>_ is resolved, so the new branch
+starts from a fresh tip: when _<start-point>_ is in
+_<remote>/<branch>_ form, only that branch is updated; when it is a
+bare remote name (e.g. `origin`), the whole remote is fetched. If the
+fetch fails, the checkout is aborted.
++
 If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index 87707e9265..35a03e8a52 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -154,11 +154,19 @@ should result in deletion of the path).
 	attached to a terminal, regardless of `--quiet`.
 
 `-t`::
-`--track[ (direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration.
 	`-c` is implied. See `--track` in linkgit:git-branch[1] for
 	details.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode. Adding `fetch` requests that the
+remote be fetched before _<start-point>_ is resolved, so the new branch
+starts from a fresh tip: when _<start-point>_ is in
+_<remote>/<branch>_ form, only that branch is updated; when it is a
+bare remote name (e.g. `origin`), the whole remote is fetched. If the
+fetch fails, the switch is aborted.
++
 If no `-c` option is given, the name of the new branch will be derived
 from the remote-tracking branch, by looking at the local part of the
 refspec configured for the corresponding remote, and then stripping
diff --git a/builtin/checkout.c b/builtin/checkout.c
index e031e61886..de4d7c00c7 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -30,7 +30,9 @@
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "setup.h"
+#include "strvec.h"
 #include "submodule.h"
 #include "symlinks.h"
 #include "trace2.h"
@@ -61,6 +63,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -112,6 +115,74 @@ struct branch_info {
 	char *checkout;
 };
 
+static void fetch_remote_for_start_point(const char *arg)
+{
+	const char *slash;
+	char *remote_name;
+	struct remote *remote;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+
+	if (!arg || !*arg)
+		return;
+
+	slash = strchr(arg, '/');
+	if (slash == arg)
+		return;
+	remote_name = slash ? xstrndup(arg, slash - arg) : xstrdup(arg);
+
+	remote = remote_get(remote_name);
+	if (!remote || !remote_is_configured(remote, 1)) {
+		free(remote_name);
+		return;
+	}
+
+	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
+	if (slash && slash[1])
+		strvec_push(&cmd.args, slash + 1);
+	cmd.git_cmd = 1;
+	free(remote_name);
+	if (run_command(&cmd))
+		die(_("failed to fetch start-point '%s'"), arg);
+}
+
+static int parse_opt_checkout_track(const struct option *opt,
+				    const char *arg, int unset)
+{
+	struct checkout_opts *opts = opt->value;
+	struct string_list tokens = STRING_LIST_INIT_DUP;
+	struct string_list_item *item;
+	int ret = 0;
+
+	if (unset) {
+		opts->track = BRANCH_TRACK_NEVER;
+		opts->fetch = 0;
+		return 0;
+	}
+
+	opts->track = BRANCH_TRACK_EXPLICIT;
+	if (!arg)
+		return 0;
+
+	string_list_split(&tokens, arg, ",", -1);
+	for_each_string_list_item(item, &tokens) {
+		if (!strcmp(item->string, "fetch")) {
+			opts->fetch = 1;
+		} else if (!strcmp(item->string, "direct")) {
+			opts->track = BRANCH_TRACK_EXPLICIT;
+		} else if (!strcmp(item->string, "inherit")) {
+			opts->track = BRANCH_TRACK_INHERIT;
+		} else {
+			ret = error(_("option `%s' expects \"%s\", \"%s\", "
+				      "or \"%s\""),
+				    "--track", "direct", "inherit", "fetch");
+			break;
+		}
+	}
+
+	string_list_clear(&tokens, 0);
+	return ret;
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1237,7 +1308,6 @@ static int git_checkout_config(const char *var, const char *value,
 		opts->dwim_new_local_branch = git_config_bool(var, value);
 		return 0;
 	}
-
 	if (starts_with(var, "submodule."))
 		return git_default_submodule_config(var, value, NULL);
 
@@ -1734,10 +1804,10 @@ static struct option *add_common_switch_branch_options(
 {
 	struct option options[] = {
 		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
-		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
+		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
 			N_("set branch tracking configuration"),
 			PARSE_OPT_OPTARG,
-			parse_opt_tracking_mode),
+			parse_opt_checkout_track),
 		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
@@ -1942,8 +2012,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0]);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 9bcf7c0b40..39236dca12 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -801,4 +801,85 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --track=fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
+	test_cmp_config fetch_upstream branch.local_new.remote &&
+	test_cmp_config refs/heads/fetch_new branch.local_new.merge
+'
+
+test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
+'
+
+test_expect_success 'checkout --track=fetch with bare remote name fetches the remote' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_new2 &&
+	test_commit -C fetch_upstream u_new2 &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2 &&
+	git checkout --track=fetch -b local_from_remote fetch_upstream &&
+	git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2
+'
+
+test_expect_success 'checkout --track=fetch aborts and does not create branch on fetch failure' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout --track=fetch,inherit fetches and inherits' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit &&
+	git fetch fetch_upstream fetch_inherit &&
+	git checkout -b base_inherit fetch_upstream/fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit2 &&
+	git checkout main &&
+	git checkout --track=fetch,inherit -b local_inherit base_inherit &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD &&
+	test_cmp_config fetch_upstream branch.local_inherit.remote &&
+	test_cmp_config refs/heads/fetch_inherit branch.local_inherit.merge
+'
+
+test_expect_success 'checkout --track=bogus reports an error' '
+	git checkout main &&
+	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
+	test_grep "expects" err
+'
+
+test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done

base-commit: 94f057755b7941b321fd11fec1b2e3ca5313a4e0
-- 
gitgitgadget
Harald NordgrenMay 3, 2026, 22:32 UTC in reply to Junio C Hamano on lore

[PATCH] checkout: add --autostash option for branch switching

> How about rewriting everything up to and including this "Tie the new
> ..." line perhaps like so:
Done!
Harald
Harald NordgrenMay 7, 2026, 20:12 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v6] checkout: extend --track with a "fetch" mode to refresh start-point

Is this ready to move to next?
Harald
Phillip WoodMay 8, 2026, 13:15 UTC in reply to Harald Nordgren on lore

Re: [PATCH v6] checkout: extend --track with a "fetch" mode to refresh start-point

Hi Harald
On 07/05/2026 21:12, Harald Nordgren wrote:
> Is this ready to move to next?

I'm not particularly enthusiastic one way or the other about adding this, but so long as we only try to fetch when the user explicitly asks for it I don't particularly object. However having had a quick scan of the implementation I have a few comments

* "--track=inherit,direct" is nonsense and should be rejected
* currently "--track" has "last one wins" behavior so
   "--track=inherit --track=direct" behaves like "--track=direct". We
   should probably keep that so that "--track=fetch --track=direct"
   behaves like "--track=direct", not "--track=fetch,direct"
* if "git fetch" fails and the remote tracking ref already exists then
   we should print a warning and carry on rather than dying which is more
   convenient if the user or remote server are offline.
* "git checkout --track=fetch origin/branch" should respect
   remote.origin.fetch so that we fetch the ref that we're going to
   checkout. I wonder if we can share this logic with the code that
   sets the upstream branch.
* "git checkout --track=fetch origin" should only fetch the remote
   ref that we're going to checkout, not all the refs from origin. i.e.
   it should read origin/HEAD to work out what to fetch.
Thanks
Phillip
Harald NordgrenMay 8, 2026, 22:40 UTC in reply to Phillip Wood on lore
Show 19 quoted lines
> * "--track=inherit,direct" is nonsense and should be rejected
> 
> * currently "--track" has "last one wins" behavior so
>   "--track=inherit --track=direct" behaves like "--track=direct". We
>   should probably keep that so that "--track=fetch --track=direct"
>   behaves like "--track=direct", not "--track=fetch,direct"
> 
> * if "git fetch" fails and the remote tracking ref already exists then
>   we should print a warning and carry on rather than dying which is more
>   convenient if the user or remote server are offline.
> 
> * "git checkout --track=fetch origin/branch" should respect
>   remote.origin.fetch so that we fetch the ref that we're going to
>   checkout. I wonder if we can share this logic with the code that
>   sets the upstream branch.
> 
> * "git checkout --track=fetch origin" should only fetch the remote
>   ref that we're going to checkout, not all the refs from origin. i.e.
>   it should read origin/HEAD to work out what to fetch.
Good points!
Harald
Harald Nordgren via GitGitGadgetMay 8, 2026, 22:52 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v7] checkout: extend --track with a "fetch" mode to refresh start-point

From: Harald Nordgren <haraldnordgren@gmail.com>

If you want to fork your topic branch from the very latest of the tip of a branch your remote has, you would do:

    git fetch origin some-branch
    git checkout -b new_branch --track origin/some-branch

Extend the "--track" option of "git checkout" and allow users to write

    git checkout -b new_branch --track=fetch origin/some-branch

to (1) fetch 'some-branch' from the remote 'origin', updating the remote-tracking branch 'origin/some-branch', (2) arrange subsequent 'git pull' on 'new_branch' to interact with 'origin/some-branch' and (3) fork 'new_branch' from it.

In the value of the '--track' option, 'fetch' can be combined with the existing 'direct' (default) and 'inherit' modes via a comma-separated list. Examples:

    git checkout -b new_branch --track=fetch,inherit some_local_branch
    git switch -c new_branch --track=fetch origin/some-branch

When "fetch" is requested and <start-point> is in <remote>/<branch> form, run "git fetch <remote> <branch>" before resolving the ref, so that other remote-tracking branches are left untouched. If <start-point> is a bare remote name like "origin" (which resolves to that remote's default branch), "git fetch <remote>" is run instead, since the target branch is not known up front. Abort the checkout if the fetch fails.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
    checkout: add --fetch to fetch remote before resolving start-point
    
     * Reject --track=inherit,direct as mutually exclusive modes.
     * Make repeated --track= last-one-wins: --track=fetch --track=direct
       behaves like --track=direct.
     * On fetch failure, warn and proceed from the existing remote-tracking
       ref instead of aborting (friendlier when offline); only abort when
       there is no existing ref.
     * For --track=fetch <remote>/<branch>, resolve the source ref through
       the configured remote.<name>.fetch refspec so custom refspecs fetch
       the correct ref.
     * For --track=fetch <remote>, read <remote>/HEAD and fetch only that
       branch instead of the whole remote.
     * Tests and docs updated accordingly.
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v7
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v7
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v6:
 1:  1b42c648b9 ! 1:  de375d55f1 checkout: extend --track with a "fetch" mode to refresh start-point
     @@ Documentation/git-checkout.adoc: of it").
       	--track without -b implies branch creation.
       +
      +The argument is a comma-separated list. `direct` (the default) and
     -+`inherit` select the tracking mode. Adding `fetch` requests that the
     -+remote be fetched before _<start-point>_ is resolved, so the new branch
     -+starts from a fresh tip: when _<start-point>_ is in
     -+_<remote>/<branch>_ form, only that branch is updated; when it is a
     -+bare remote name (e.g. `origin`), the whole remote is fetched. If the
     -+fetch fails, the checkout is aborted.
     ++`inherit` select the tracking mode and are mutually exclusive. Adding
     ++`fetch` requests that the remote be fetched before _<start-point>_ is
     ++resolved, so the new branch starts from a fresh tip: when
     ++_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
     ++updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
     ++only the remote's default branch is updated. If the fetch fails and the
     ++corresponding remote-tracking ref already exists, a warning is printed
     ++and the checkout proceeds from the existing tip; otherwise the checkout
     ++is aborted.
      ++
       If no `-b` option is given, the name of the new branch will be
       derived from the remote-tracking branch, by looking at the local part of
     @@ Documentation/git-switch.adoc: should result in deletion of the path).
       	details.
       +
      +The argument is a comma-separated list. `direct` (the default) and
     -+`inherit` select the tracking mode. Adding `fetch` requests that the
     -+remote be fetched before _<start-point>_ is resolved, so the new branch
     -+starts from a fresh tip: when _<start-point>_ is in
     -+_<remote>/<branch>_ form, only that branch is updated; when it is a
     -+bare remote name (e.g. `origin`), the whole remote is fetched. If the
     -+fetch fails, the switch is aborted.
     ++`inherit` select the tracking mode and are mutually exclusive. Adding
     ++`fetch` requests that the remote be fetched before _<start-point>_ is
     ++resolved, so the new branch starts from a fresh tip: when
     ++_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
     ++updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
     ++only the remote's default branch is updated. If the fetch fails and the
     ++corresponding remote-tracking ref already exists, a warning is printed
     ++and the switch proceeds from the existing tip; otherwise the switch is
     ++aborted.
      ++
       If no `-c` option is given, the name of the new branch will be derived
       from the remote-tracking branch, by looking at the local part of the
     @@ Documentation/git-switch.adoc: should result in deletion of the path).
      
       ## builtin/checkout.c ##
      @@
     + #include "preload-index.h"
     + #include "read-cache.h"
     + #include "refs.h"
     ++#include "refspec.h"
     + #include "remote.h"
       #include "repo-settings.h"
       #include "resolve-undo.h"
       #include "revision.h"
     @@ builtin/checkout.c: struct branch_info {
       	char *checkout;
       };
       
     -+static void fetch_remote_for_start_point(const char *arg)
     ++static int resolve_fetch_target(const char *arg, char **remote_out,
     ++				char **src_ref_out)
      +{
      +	const char *slash;
      +	char *remote_name;
      +	struct remote *remote;
     -+	struct child_process cmd = CHILD_PROCESS_INIT;
     ++	struct refspec_item query = { 0 };
     ++	struct strbuf dst = STRBUF_INIT;
     ++	const char *rest;
     ++
     ++	*remote_out = NULL;
     ++	*src_ref_out = NULL;
      +
      +	if (!arg || !*arg)
     -+		return;
     ++		return -1;
      +
      +	slash = strchr(arg, '/');
      +	if (slash == arg)
     -+		return;
     ++		return -1;
      +	remote_name = slash ? xstrndup(arg, slash - arg) : xstrdup(arg);
      +
      +	remote = remote_get(remote_name);
      +	if (!remote || !remote_is_configured(remote, 1)) {
      +		free(remote_name);
     ++		return -1;
     ++	}
     ++
     ++	rest = (slash && slash[1]) ? slash + 1 : NULL;
     ++	if (!rest) {
     ++		struct object_id oid;
     ++		const char *head_target;
     ++		const char *short_target;
     ++
     ++		strbuf_addf(&dst, "refs/remotes/%s/HEAD", remote_name);
     ++		head_target = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
     ++						      dst.buf,
     ++						      RESOLVE_REF_READING |
     ++						      RESOLVE_REF_NO_RECURSE,
     ++						      &oid, NULL);
     ++		strbuf_reset(&dst);
     ++		if (head_target &&
     ++		    skip_prefix(head_target, "refs/remotes/", &short_target) &&
     ++		    skip_prefix(short_target, remote_name, &short_target) &&
     ++		    *short_target == '/')
     ++			rest = short_target + 1;
     ++	}
     ++
     ++	if (rest) {
     ++		strbuf_addf(&dst, "refs/remotes/%s/%s", remote_name, rest);
     ++		query.dst = dst.buf;
     ++		if (!remote_find_tracking(remote, &query) && query.src) {
     ++			*src_ref_out = xstrdup(query.src);
     ++			free(query.src);
     ++		} else {
     ++			*src_ref_out = xstrdup(rest);
     ++		}
     ++	}
     ++
     ++	strbuf_release(&dst);
     ++	*remote_out = remote_name;
     ++	return 0;
     ++}
     ++
     ++static void fetch_remote_for_start_point(const char *arg)
     ++{
     ++	char *remote_name = NULL;
     ++	char *src_ref = NULL;
     ++	struct child_process cmd = CHILD_PROCESS_INIT;
     ++	struct strbuf dst_ref = STRBUF_INIT;
     ++	int have_existing_ref = 0;
     ++
     ++	if (resolve_fetch_target(arg, &remote_name, &src_ref))
      +		return;
     ++
     ++	if (src_ref) {
     ++		const char *short_src = src_ref;
     ++		struct object_id oid;
     ++
     ++		skip_prefix(short_src, "refs/heads/", &short_src);
     ++		strbuf_addf(&dst_ref, "refs/remotes/%s/%s", remote_name, short_src);
     ++		if (!refs_read_ref(get_main_ref_store(the_repository),
     ++				   dst_ref.buf, &oid))
     ++			have_existing_ref = 1;
      +	}
      +
      +	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
     -+	if (slash && slash[1])
     -+		strvec_push(&cmd.args, slash + 1);
     ++	if (src_ref)
     ++		strvec_push(&cmd.args, src_ref);
      +	cmd.git_cmd = 1;
     ++	if (run_command(&cmd)) {
     ++		if (have_existing_ref)
     ++			warning(_("failed to fetch start-point '%s'; "
     ++				  "using existing '%s'"),
     ++				arg, dst_ref.buf);
     ++		else
     ++			die(_("failed to fetch start-point '%s'"), arg);
     ++	}
     ++
      +	free(remote_name);
     -+	if (run_command(&cmd))
     -+		die(_("failed to fetch start-point '%s'"), arg);
     ++	free(src_ref);
     ++	strbuf_release(&dst_ref);
      +}
      +
      +static int parse_opt_checkout_track(const struct option *opt,
     @@ builtin/checkout.c: struct branch_info {
      +	struct checkout_opts *opts = opt->value;
      +	struct string_list tokens = STRING_LIST_INIT_DUP;
      +	struct string_list_item *item;
     ++	int saw_direct = 0, saw_inherit = 0;
      +	int ret = 0;
      +
     ++	opts->fetch = 0;
     ++
      +	if (unset) {
      +		opts->track = BRANCH_TRACK_NEVER;
     -+		opts->fetch = 0;
      +		return 0;
      +	}
      +
     @@ builtin/checkout.c: struct branch_info {
      +		if (!strcmp(item->string, "fetch")) {
      +			opts->fetch = 1;
      +		} else if (!strcmp(item->string, "direct")) {
     ++			saw_direct = 1;
      +			opts->track = BRANCH_TRACK_EXPLICIT;
      +		} else if (!strcmp(item->string, "inherit")) {
     ++			saw_inherit = 1;
      +			opts->track = BRANCH_TRACK_INHERIT;
      +		} else {
      +			ret = error(_("option `%s' expects \"%s\", \"%s\", "
      +				      "or \"%s\""),
      +				    "--track", "direct", "inherit", "fetch");
     -+			break;
     ++			goto out;
      +		}
      +	}
      +
     ++	if (saw_direct && saw_inherit)
     ++		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
     ++			    "--track", "direct", "inherit");
     ++
     ++out:
      +	string_list_clear(&tokens, 0);
      +	return ret;
      +}
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
      +'
      +
     -+test_expect_success 'checkout --track=fetch with bare remote name fetches the remote' '
     ++test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
      +	git checkout main &&
     -+	git -C fetch_upstream checkout -b fetch_new2 &&
     -+	test_commit -C fetch_upstream u_new2 &&
     -+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2 &&
     ++	git -C fetch_upstream checkout main &&
     ++	git remote set-head fetch_upstream main &&
     ++	git -C fetch_upstream checkout -b fetch_unrelated &&
     ++	test_commit -C fetch_upstream u_unrelated_pre &&
     ++	git fetch fetch_upstream fetch_unrelated &&
     ++	unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
     ++	git -C fetch_upstream checkout main &&
     ++	test_commit -C fetch_upstream u_main_post &&
     ++	git -C fetch_upstream checkout fetch_unrelated &&
     ++	test_commit -C fetch_upstream u_unrelated_post &&
      +	git checkout --track=fetch -b local_from_remote fetch_upstream &&
     -+	git rev-parse --verify refs/remotes/fetch_upstream/fetch_new2
     ++	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
     ++	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
      +'
      +
     -+test_expect_success 'checkout --track=fetch aborts and does not create branch on fetch failure' '
     ++test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
      +	git checkout main &&
      +	test_might_fail git branch -D bogus &&
      +	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
      +	test_must_fail git rev-parse --verify refs/heads/bogus
      +'
      +
     ++test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
     ++	git checkout main &&
     ++	git -C fetch_upstream checkout -b fetch_offline &&
     ++	test_commit -C fetch_upstream u_offline &&
     ++	git fetch fetch_upstream fetch_offline &&
     ++	saved_url=$(git config remote.fetch_upstream.url) &&
     ++	test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
     ++	git config remote.fetch_upstream.url ./does-not-exist &&
     ++	git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
     ++	test_grep "failed to fetch" err &&
     ++	test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
     ++'
     ++
     ++test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
     ++	git checkout main &&
     ++	git -C fetch_upstream checkout -b fetch_refspec &&
     ++	test_commit -C fetch_upstream u_refspec &&
     ++	git fetch fetch_upstream fetch_refspec &&
     ++	git remote add fetch_custom ./fetch_upstream &&
     ++	test_when_finished "git remote remove fetch_custom" &&
     ++	git config --replace-all remote.fetch_custom.fetch \
     ++		"+refs/heads/*:refs/remotes/custom-ns/*" &&
     ++	git fetch fetch_custom &&
     ++	test_commit -C fetch_upstream u_refspec_post &&
     ++	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
     ++	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
     ++'
     ++
     ++test_expect_success 'checkout --track=inherit,direct is rejected' '
     ++	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
     ++	test_grep "cannot combine" err
     ++'
     ++
     ++test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
     ++	git checkout main &&
     ++	git -C fetch_upstream checkout -b fetch_lastwin &&
     ++	test_commit -C fetch_upstream u_lastwin &&
     ++	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
     ++	test_must_fail git checkout --track=fetch --track=direct \
     ++		-b local_lastwin fetch_upstream/fetch_lastwin &&
     ++	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
     ++'
     ++
      +test_expect_success 'checkout --track=fetch,inherit fetches and inherits' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_inherit &&
 Documentation/git-checkout.adoc |  13 ++-
 Documentation/git-switch.adoc   |  13 ++-
 builtin/checkout.c              | 168 +++++++++++++++++++++++++++++++-
 t/t7201-co.sh                   | 132 +++++++++++++++++++++++++
 4 files changed, 319 insertions(+), 7 deletions(-)
Show changes to 4 files +319 −7

Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh

diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index 43ccf47cf6..28f17f427e 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -158,11 +158,22 @@ of it").
 	resets _<branch>_ to the start point instead of failing.
 
 `-t`::
-`--track[=(direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration. See
 	`--track` in linkgit:git-branch[1] for details. As a convenience,
 	--track without -b implies branch creation.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
+only the remote's default branch is updated. If the fetch fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the checkout proceeds from the existing tip; otherwise the checkout
+is aborted.
++
 If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index 87707e9265..3f54cf39e9 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -154,11 +154,22 @@ should result in deletion of the path).
 	attached to a terminal, regardless of `--quiet`.
 
 `-t`::
-`--track[ (direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration.
 	`-c` is implied. See `--track` in linkgit:git-branch[1] for
 	details.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
+only the remote's default branch is updated. If the fetch fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the switch proceeds from the existing tip; otherwise the switch is
+aborted.
++
 If no `-c` option is given, the name of the new branch will be derived
 from the remote-tracking branch, by looking at the local part of the
 refspec configured for the corresponding remote, and then stripping
diff --git a/builtin/checkout.c b/builtin/checkout.c
index e031e61886..8f8d1ecffe 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -26,11 +26,14 @@
 #include "preload-index.h"
 #include "read-cache.h"
 #include "refs.h"
+#include "refspec.h"
 #include "remote.h"
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "setup.h"
+#include "strvec.h"
 #include "submodule.h"
 #include "symlinks.h"
 #include "trace2.h"
@@ -61,6 +64,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -112,6 +116,156 @@ struct branch_info {
 	char *checkout;
 };
 
+static int resolve_fetch_target(const char *arg, char **remote_out,
+				char **src_ref_out)
+{
+	const char *slash;
+	char *remote_name;
+	struct remote *remote;
+	struct refspec_item query = { 0 };
+	struct strbuf dst = STRBUF_INIT;
+	const char *rest;
+
+	*remote_out = NULL;
+	*src_ref_out = NULL;
+
+	if (!arg || !*arg)
+		return -1;
+
+	slash = strchr(arg, '/');
+	if (slash == arg)
+		return -1;
+	remote_name = slash ? xstrndup(arg, slash - arg) : xstrdup(arg);
+
+	remote = remote_get(remote_name);
+	if (!remote || !remote_is_configured(remote, 1)) {
+		free(remote_name);
+		return -1;
+	}
+
+	rest = (slash && slash[1]) ? slash + 1 : NULL;
+	if (!rest) {
+		struct object_id oid;
+		const char *head_target;
+		const char *short_target;
+
+		strbuf_addf(&dst, "refs/remotes/%s/HEAD", remote_name);
+		head_target = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
+						      dst.buf,
+						      RESOLVE_REF_READING |
+						      RESOLVE_REF_NO_RECURSE,
+						      &oid, NULL);
+		strbuf_reset(&dst);
+		if (head_target &&
+		    skip_prefix(head_target, "refs/remotes/", &short_target) &&
+		    skip_prefix(short_target, remote_name, &short_target) &&
+		    *short_target == '/')
+			rest = short_target + 1;
+	}
+
+	if (rest) {
+		strbuf_addf(&dst, "refs/remotes/%s/%s", remote_name, rest);
+		query.dst = dst.buf;
+		if (!remote_find_tracking(remote, &query) && query.src) {
+			*src_ref_out = xstrdup(query.src);
+			free(query.src);
+		} else {
+			*src_ref_out = xstrdup(rest);
+		}
+	}
+
+	strbuf_release(&dst);
+	*remote_out = remote_name;
+	return 0;
+}
+
+static void fetch_remote_for_start_point(const char *arg)
+{
+	char *remote_name = NULL;
+	char *src_ref = NULL;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+	struct strbuf dst_ref = STRBUF_INIT;
+	int have_existing_ref = 0;
+
+	if (resolve_fetch_target(arg, &remote_name, &src_ref))
+		return;
+
+	if (src_ref) {
+		const char *short_src = src_ref;
+		struct object_id oid;
+
+		skip_prefix(short_src, "refs/heads/", &short_src);
+		strbuf_addf(&dst_ref, "refs/remotes/%s/%s", remote_name, short_src);
+		if (!refs_read_ref(get_main_ref_store(the_repository),
+				   dst_ref.buf, &oid))
+			have_existing_ref = 1;
+	}
+
+	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
+	if (src_ref)
+		strvec_push(&cmd.args, src_ref);
+	cmd.git_cmd = 1;
+	if (run_command(&cmd)) {
+		if (have_existing_ref)
+			warning(_("failed to fetch start-point '%s'; "
+				  "using existing '%s'"),
+				arg, dst_ref.buf);
+		else
+			die(_("failed to fetch start-point '%s'"), arg);
+	}
+
+	free(remote_name);
+	free(src_ref);
+	strbuf_release(&dst_ref);
+}
+
+static int parse_opt_checkout_track(const struct option *opt,
+				    const char *arg, int unset)
+{
+	struct checkout_opts *opts = opt->value;
+	struct string_list tokens = STRING_LIST_INIT_DUP;
+	struct string_list_item *item;
+	int saw_direct = 0, saw_inherit = 0;
+	int ret = 0;
+
+	opts->fetch = 0;
+
+	if (unset) {
+		opts->track = BRANCH_TRACK_NEVER;
+		return 0;
+	}
+
+	opts->track = BRANCH_TRACK_EXPLICIT;
+	if (!arg)
+		return 0;
+
+	string_list_split(&tokens, arg, ",", -1);
+	for_each_string_list_item(item, &tokens) {
+		if (!strcmp(item->string, "fetch")) {
+			opts->fetch = 1;
+		} else if (!strcmp(item->string, "direct")) {
+			saw_direct = 1;
+			opts->track = BRANCH_TRACK_EXPLICIT;
+		} else if (!strcmp(item->string, "inherit")) {
+			saw_inherit = 1;
+			opts->track = BRANCH_TRACK_INHERIT;
+		} else {
+			ret = error(_("option `%s' expects \"%s\", \"%s\", "
+				      "or \"%s\""),
+				    "--track", "direct", "inherit", "fetch");
+			goto out;
+		}
+	}
+
+	if (saw_direct && saw_inherit)
+		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
+			    "--track", "direct", "inherit");
+
+out:
+	string_list_clear(&tokens, 0);
+	return ret;
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1237,7 +1391,6 @@ static int git_checkout_config(const char *var, const char *value,
 		opts->dwim_new_local_branch = git_config_bool(var, value);
 		return 0;
 	}
-
 	if (starts_with(var, "submodule."))
 		return git_default_submodule_config(var, value, NULL);
 
@@ -1734,10 +1887,10 @@ static struct option *add_common_switch_branch_options(
 {
 	struct option options[] = {
 		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
-		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
+		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
 			N_("set branch tracking configuration"),
 			PARSE_OPT_OPTARG,
-			parse_opt_tracking_mode),
+			parse_opt_checkout_track),
 		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
@@ -1942,8 +2095,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0]);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 9bcf7c0b40..19ac6a1a2e 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -801,4 +801,136 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --track=fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
+	test_cmp_config fetch_upstream branch.local_new.remote &&
+	test_cmp_config refs/heads/fetch_new branch.local_new.merge
+'
+
+test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
+'
+
+test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
+	git checkout main &&
+	git -C fetch_upstream checkout main &&
+	git remote set-head fetch_upstream main &&
+	git -C fetch_upstream checkout -b fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_pre &&
+	git fetch fetch_upstream fetch_unrelated &&
+	unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_main_post &&
+	git -C fetch_upstream checkout fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_post &&
+	git checkout --track=fetch -b local_from_remote fetch_upstream &&
+	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
+'
+
+test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_offline &&
+	test_commit -C fetch_upstream u_offline &&
+	git fetch fetch_upstream fetch_offline &&
+	saved_url=$(git config remote.fetch_upstream.url) &&
+	test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
+	git config remote.fetch_upstream.url ./does-not-exist &&
+	git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
+	test_grep "failed to fetch" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
+'
+
+test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_refspec &&
+	test_commit -C fetch_upstream u_refspec &&
+	git fetch fetch_upstream fetch_refspec &&
+	git remote add fetch_custom ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_custom" &&
+	git config --replace-all remote.fetch_custom.fetch \
+		"+refs/heads/*:refs/remotes/custom-ns/*" &&
+	git fetch fetch_custom &&
+	test_commit -C fetch_upstream u_refspec_post &&
+	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
+	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
+'
+
+test_expect_success 'checkout --track=inherit,direct is rejected' '
+	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
+	test_grep "cannot combine" err
+'
+
+test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_lastwin &&
+	test_commit -C fetch_upstream u_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
+	test_must_fail git checkout --track=fetch --track=direct \
+		-b local_lastwin fetch_upstream/fetch_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
+'
+
+test_expect_success 'checkout --track=fetch,inherit fetches and inherits' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit &&
+	git fetch fetch_upstream fetch_inherit &&
+	git checkout -b base_inherit fetch_upstream/fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit2 &&
+	git checkout main &&
+	git checkout --track=fetch,inherit -b local_inherit base_inherit &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD &&
+	test_cmp_config fetch_upstream branch.local_inherit.remote &&
+	test_cmp_config refs/heads/fetch_inherit branch.local_inherit.merge
+'
+
+test_expect_success 'checkout --track=bogus reports an error' '
+	git checkout main &&
+	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
+	test_grep "expects" err
+'
+
+test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done

base-commit: 94f057755b7941b321fd11fec1b2e3ca5313a4e0
-- 
gitgitgadget
Phillip WoodMay 11, 2026, 13:16 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH v7] checkout: extend --track with a "fetch" mode to refresh start-point

Hi Harald
On 08/05/2026 23:52, Harald Nordgren via GitGitGadget wrote:
Show 22 quoted lines
> From: Harald Nordgren <haraldnordgren@gmail.com>
> 
> +static void fetch_remote_for_start_point(const char *arg)
> +{
> +	char *remote_name = NULL;
> +	char *src_ref = NULL;
> +	struct child_process cmd = CHILD_PROCESS_INIT;
> +	struct strbuf dst_ref = STRBUF_INIT;
> +	int have_existing_ref = 0;
> +
> +	if (resolve_fetch_target(arg, &remote_name, &src_ref))
> +		return;
> +
> +	if (src_ref) {
> +		const char *short_src = src_ref;
> +		struct object_id oid;
> +
> +		skip_prefix(short_src, "refs/heads/", &short_src);
> +		strbuf_addf(&dst_ref, "refs/remotes/%s/%s", remote_name, short_src);
> +		if (!refs_read_ref(get_main_ref_store(the_repository),
> +				   dst_ref.buf, &oid))
> +			have_existing_ref = 1;

src_ref is the name of the branch on the remote server, not the name of the remote tracking ref which is given by arg. If arg is a remote name then we need to resolve refs/remotes/$arg/HEAD to find the branch to check, otherwise we should be checking refs/remotes/$arg

I've only given this version a quick scan through, but I didn't notice any other issues.

Thanks
Phillip
Show 250 quoted lines
> +	}
> +
> +	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
> +	if (src_ref)
> +		strvec_push(&cmd.args, src_ref);
> +	cmd.git_cmd = 1;
> +	if (run_command(&cmd)) {
> +		if (have_existing_ref)
> +			warning(_("failed to fetch start-point '%s'; "
> +				  "using existing '%s'"),
> +				arg, dst_ref.buf);
> +		else
> +			die(_("failed to fetch start-point '%s'"), arg);
> +	}
> +
> +	free(remote_name);
> +	free(src_ref);
> +	strbuf_release(&dst_ref);
> +}
> +
> +static int parse_opt_checkout_track(const struct option *opt,
> +				    const char *arg, int unset)
> +{
> +	struct checkout_opts *opts = opt->value;
> +	struct string_list tokens = STRING_LIST_INIT_DUP;
> +	struct string_list_item *item;
> +	int saw_direct = 0, saw_inherit = 0;
> +	int ret = 0;
> +
> +	opts->fetch = 0;
> +
> +	if (unset) {
> +		opts->track = BRANCH_TRACK_NEVER;
> +		return 0;
> +	}
> +
> +	opts->track = BRANCH_TRACK_EXPLICIT;
> +	if (!arg)
> +		return 0;
> +
> +	string_list_split(&tokens, arg, ",", -1);
> +	for_each_string_list_item(item, &tokens) {
> +		if (!strcmp(item->string, "fetch")) {
> +			opts->fetch = 1;
> +		} else if (!strcmp(item->string, "direct")) {
> +			saw_direct = 1;
> +			opts->track = BRANCH_TRACK_EXPLICIT;
> +		} else if (!strcmp(item->string, "inherit")) {
> +			saw_inherit = 1;
> +			opts->track = BRANCH_TRACK_INHERIT;
> +		} else {
> +			ret = error(_("option `%s' expects \"%s\", \"%s\", "
> +				      "or \"%s\""),
> +				    "--track", "direct", "inherit", "fetch");
> +			goto out;
> +		}
> +	}
> +
> +	if (saw_direct && saw_inherit)
> +		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
> +			    "--track", "direct", "inherit");
> +
> +out:
> +	string_list_clear(&tokens, 0);
> +	return ret;
> +}
> +
>   static void branch_info_release(struct branch_info *info)
>   {
>   	free(info->name);
> @@ -1237,7 +1391,6 @@ static int git_checkout_config(const char *var, const char *value,
>   		opts->dwim_new_local_branch = git_config_bool(var, value);
>   		return 0;
>   	}
> -
>   	if (starts_with(var, "submodule."))
>   		return git_default_submodule_config(var, value, NULL);
>   
> @@ -1734,10 +1887,10 @@ static struct option *add_common_switch_branch_options(
>   {
>   	struct option options[] = {
>   		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
> -		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
> +		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
>   			N_("set branch tracking configuration"),
>   			PARSE_OPT_OPTARG,
> -			parse_opt_tracking_mode),
> +			parse_opt_checkout_track),
>   		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
>   			   PARSE_OPT_NOCOMPLETE),
>   		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
> @@ -1942,8 +2095,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
>   			opts->dwim_new_local_branch &&
>   			opts->track == BRANCH_TRACK_UNSPECIFIED &&
>   			!opts->new_branch;
> -		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
> -					     &new_branch_info, opts, &rev);
> +		int n;
> +
> +		if (opts->fetch)
> +			fetch_remote_for_start_point(argv[0]);
> +
> +		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
> +					 &new_branch_info, opts, &rev);
>   		argv += n;
>   		argc -= n;
>   	} else if (!opts->accept_ref && opts->from_treeish) {
> diff --git a/t/t7201-co.sh b/t/t7201-co.sh
> index 9bcf7c0b40..19ac6a1a2e 100755
> --- a/t/t7201-co.sh
> +++ b/t/t7201-co.sh
> @@ -801,4 +801,136 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
>   	test_cmp_config "" --default "" branch.main2.merge
>   '
>   
> +test_expect_success 'setup upstream for --track=fetch tests' '
> +	git checkout main &&
> +	git init fetch_upstream &&
> +	test_commit -C fetch_upstream u_main &&
> +	git remote add fetch_upstream fetch_upstream &&
> +	git fetch fetch_upstream &&
> +	git -C fetch_upstream checkout -b fetch_new &&
> +	test_commit -C fetch_upstream u_new
> +'
> +
> +test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
> +	git checkout main &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
> +	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
> +	test_cmp_config fetch_upstream branch.local_new.remote &&
> +	test_cmp_config refs/heads/fetch_new branch.local_new.merge
> +'
> +
> +test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_target &&
> +	test_commit -C fetch_upstream u_target_pre &&
> +	git -C fetch_upstream checkout -b fetch_other &&
> +	test_commit -C fetch_upstream u_other_pre &&
> +	git fetch fetch_upstream &&
> +	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
> +	git -C fetch_upstream checkout fetch_target &&
> +	test_commit -C fetch_upstream u_target_post &&
> +	git -C fetch_upstream checkout fetch_other &&
> +	test_commit -C fetch_upstream u_other_post &&
> +	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
> +	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
> +'
> +
> +test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout main &&
> +	git remote set-head fetch_upstream main &&
> +	git -C fetch_upstream checkout -b fetch_unrelated &&
> +	test_commit -C fetch_upstream u_unrelated_pre &&
> +	git fetch fetch_upstream fetch_unrelated &&
> +	unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
> +	git -C fetch_upstream checkout main &&
> +	test_commit -C fetch_upstream u_main_post &&
> +	git -C fetch_upstream checkout fetch_unrelated &&
> +	test_commit -C fetch_upstream u_unrelated_post &&
> +	git checkout --track=fetch -b local_from_remote fetch_upstream &&
> +	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
> +	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
> +'
> +
> +test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
> +	git checkout main &&
> +	test_might_fail git branch -D bogus &&
> +	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
> +	test_must_fail git rev-parse --verify refs/heads/bogus
> +'
> +
> +test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_offline &&
> +	test_commit -C fetch_upstream u_offline &&
> +	git fetch fetch_upstream fetch_offline &&
> +	saved_url=$(git config remote.fetch_upstream.url) &&
> +	test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
> +	git config remote.fetch_upstream.url ./does-not-exist &&
> +	git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
> +	test_grep "failed to fetch" err &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
> +'
> +
> +test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_refspec &&
> +	test_commit -C fetch_upstream u_refspec &&
> +	git fetch fetch_upstream fetch_refspec &&
> +	git remote add fetch_custom ./fetch_upstream &&
> +	test_when_finished "git remote remove fetch_custom" &&
> +	git config --replace-all remote.fetch_custom.fetch \
> +		"+refs/heads/*:refs/remotes/custom-ns/*" &&
> +	git fetch fetch_custom &&
> +	test_commit -C fetch_upstream u_refspec_post &&
> +	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
> +	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
> +'
> +
> +test_expect_success 'checkout --track=inherit,direct is rejected' '
> +	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
> +	test_grep "cannot combine" err
> +'
> +
> +test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_lastwin &&
> +	test_commit -C fetch_upstream u_lastwin &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
> +	test_must_fail git checkout --track=fetch --track=direct \
> +		-b local_lastwin fetch_upstream/fetch_lastwin &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
> +'
> +
> +test_expect_success 'checkout --track=fetch,inherit fetches and inherits' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_inherit &&
> +	test_commit -C fetch_upstream u_inherit &&
> +	git fetch fetch_upstream fetch_inherit &&
> +	git checkout -b base_inherit fetch_upstream/fetch_inherit &&
> +	test_commit -C fetch_upstream u_inherit2 &&
> +	git checkout main &&
> +	git checkout --track=fetch,inherit -b local_inherit base_inherit &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD &&
> +	test_cmp_config fetch_upstream branch.local_inherit.remote &&
> +	test_cmp_config refs/heads/fetch_inherit branch.local_inherit.merge
> +'
> +
> +test_expect_success 'checkout --track=bogus reports an error' '
> +	git checkout main &&
> +	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
> +	test_grep "expects" err
> +'
> +
> +test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_switch &&
> +	test_commit -C fetch_upstream u_switch &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
> +	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
> +'
> +
>   test_done
> 
> base-commit: 94f057755b7941b321fd11fec1b2e3ca5313a4e0
Harald Nordgren via GitGitGadgetMay 11, 2026, 13:47 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v8] checkout: extend --track with a "fetch" mode to refresh start-point

From: Harald Nordgren <haraldnordgren@gmail.com>

If you want to fork your topic branch from the very latest of the tip of a branch your remote has, you would do:

    git fetch origin some-branch
    git checkout -b new_branch --track origin/some-branch

Extend the "--track" option of "git checkout" and allow users to write

    git checkout -b new_branch --track=fetch origin/some-branch

to (1) fetch 'some-branch' from the remote 'origin', updating the remote-tracking branch 'origin/some-branch', (2) arrange subsequent 'git pull' on 'new_branch' to interact with 'origin/some-branch' and (3) fork 'new_branch' from it.

In the value of the '--track' option, 'fetch' can be combined with the existing 'direct' (default) and 'inherit' modes via a comma-separated list. Examples:

    git checkout -b new_branch --track=fetch,inherit some_local_branch
    git switch -c new_branch --track=fetch origin/some-branch

When "fetch" is requested and <start-point> is in <remote>/<branch> form, run "git fetch <remote> <branch>" before resolving the ref, so that other remote-tracking branches are left untouched. If <start-point> is a bare remote name like "origin" (which resolves to that remote's default branch), "git fetch <remote>" is run instead, since the target branch is not known up front. Abort the checkout if the fetch fails.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
    checkout: --track=fetch
    
    Check the fallback ref using arg directly instead of reconstructing it.
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v8
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v8
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v7:
 1:  de375d55f1 ! 1:  61c2199fd5 checkout: extend --track with a "fetch" mode to refresh start-point
     @@ builtin/checkout.c
       #include "revision.h"
      +#include "run-command.h"
       #include "setup.h"
     -+#include "strvec.h"
     + #include "strvec.h"
       #include "submodule.h"
     - #include "symlinks.h"
     - #include "trace2.h"
      @@ builtin/checkout.c: struct checkout_opts {
       	int count_checkout_paths;
       	int overlay_mode;
     @@ builtin/checkout.c: struct branch_info {
      +	if (resolve_fetch_target(arg, &remote_name, &src_ref))
      +		return;
      +
     -+	if (src_ref) {
     -+		const char *short_src = src_ref;
     ++	{
      +		struct object_id oid;
      +
     -+		skip_prefix(short_src, "refs/heads/", &short_src);
     -+		strbuf_addf(&dst_ref, "refs/remotes/%s/%s", remote_name, short_src);
     ++		if (strchr(arg, '/'))
     ++			strbuf_addf(&dst_ref, "refs/remotes/%s", arg);
     ++		else
     ++			strbuf_addf(&dst_ref, "refs/remotes/%s/HEAD", arg);
      +		if (!refs_read_ref(get_main_ref_store(the_repository),
      +				   dst_ref.buf, &oid))
      +			have_existing_ref = 1;
 Documentation/git-checkout.adoc |  13 ++-
 Documentation/git-switch.adoc   |  13 ++-
 builtin/checkout.c              | 168 +++++++++++++++++++++++++++++++-
 t/t7201-co.sh                   | 132 +++++++++++++++++++++++++
 4 files changed, 319 insertions(+), 7 deletions(-)
Show changes to 4 files +319 −7

Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh

diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index 43ccf47cf6..28f17f427e 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -158,11 +158,22 @@ of it").
 	resets _<branch>_ to the start point instead of failing.
 
 `-t`::
-`--track[=(direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration. See
 	`--track` in linkgit:git-branch[1] for details. As a convenience,
 	--track without -b implies branch creation.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
+only the remote's default branch is updated. If the fetch fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the checkout proceeds from the existing tip; otherwise the checkout
+is aborted.
++
 If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index 87707e9265..3f54cf39e9 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -154,11 +154,22 @@ should result in deletion of the path).
 	attached to a terminal, regardless of `--quiet`.
 
 `-t`::
-`--track[ (direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration.
 	`-c` is implied. See `--track` in linkgit:git-branch[1] for
 	details.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
+only the remote's default branch is updated. If the fetch fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the switch proceeds from the existing tip; otherwise the switch is
+aborted.
++
 If no `-c` option is given, the name of the new branch will be derived
 from the remote-tracking branch, by looking at the local part of the
 refspec configured for the corresponding remote, and then stripping
diff --git a/builtin/checkout.c b/builtin/checkout.c
index ac0186a33e..157242bc9f 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -26,10 +26,12 @@
 #include "preload-index.h"
 #include "read-cache.h"
 #include "refs.h"
+#include "refspec.h"
 #include "remote.h"
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "setup.h"
 #include "strvec.h"
 #include "submodule.h"
@@ -62,6 +64,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -113,6 +116,157 @@ struct branch_info {
 	char *checkout;
 };
 
+static int resolve_fetch_target(const char *arg, char **remote_out,
+				char **src_ref_out)
+{
+	const char *slash;
+	char *remote_name;
+	struct remote *remote;
+	struct refspec_item query = { 0 };
+	struct strbuf dst = STRBUF_INIT;
+	const char *rest;
+
+	*remote_out = NULL;
+	*src_ref_out = NULL;
+
+	if (!arg || !*arg)
+		return -1;
+
+	slash = strchr(arg, '/');
+	if (slash == arg)
+		return -1;
+	remote_name = slash ? xstrndup(arg, slash - arg) : xstrdup(arg);
+
+	remote = remote_get(remote_name);
+	if (!remote || !remote_is_configured(remote, 1)) {
+		free(remote_name);
+		return -1;
+	}
+
+	rest = (slash && slash[1]) ? slash + 1 : NULL;
+	if (!rest) {
+		struct object_id oid;
+		const char *head_target;
+		const char *short_target;
+
+		strbuf_addf(&dst, "refs/remotes/%s/HEAD", remote_name);
+		head_target = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
+						      dst.buf,
+						      RESOLVE_REF_READING |
+						      RESOLVE_REF_NO_RECURSE,
+						      &oid, NULL);
+		strbuf_reset(&dst);
+		if (head_target &&
+		    skip_prefix(head_target, "refs/remotes/", &short_target) &&
+		    skip_prefix(short_target, remote_name, &short_target) &&
+		    *short_target == '/')
+			rest = short_target + 1;
+	}
+
+	if (rest) {
+		strbuf_addf(&dst, "refs/remotes/%s/%s", remote_name, rest);
+		query.dst = dst.buf;
+		if (!remote_find_tracking(remote, &query) && query.src) {
+			*src_ref_out = xstrdup(query.src);
+			free(query.src);
+		} else {
+			*src_ref_out = xstrdup(rest);
+		}
+	}
+
+	strbuf_release(&dst);
+	*remote_out = remote_name;
+	return 0;
+}
+
+static void fetch_remote_for_start_point(const char *arg)
+{
+	char *remote_name = NULL;
+	char *src_ref = NULL;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+	struct strbuf dst_ref = STRBUF_INIT;
+	int have_existing_ref = 0;
+
+	if (resolve_fetch_target(arg, &remote_name, &src_ref))
+		return;
+
+	{
+		struct object_id oid;
+
+		if (strchr(arg, '/'))
+			strbuf_addf(&dst_ref, "refs/remotes/%s", arg);
+		else
+			strbuf_addf(&dst_ref, "refs/remotes/%s/HEAD", arg);
+		if (!refs_read_ref(get_main_ref_store(the_repository),
+				   dst_ref.buf, &oid))
+			have_existing_ref = 1;
+	}
+
+	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
+	if (src_ref)
+		strvec_push(&cmd.args, src_ref);
+	cmd.git_cmd = 1;
+	if (run_command(&cmd)) {
+		if (have_existing_ref)
+			warning(_("failed to fetch start-point '%s'; "
+				  "using existing '%s'"),
+				arg, dst_ref.buf);
+		else
+			die(_("failed to fetch start-point '%s'"), arg);
+	}
+
+	free(remote_name);
+	free(src_ref);
+	strbuf_release(&dst_ref);
+}
+
+static int parse_opt_checkout_track(const struct option *opt,
+				    const char *arg, int unset)
+{
+	struct checkout_opts *opts = opt->value;
+	struct string_list tokens = STRING_LIST_INIT_DUP;
+	struct string_list_item *item;
+	int saw_direct = 0, saw_inherit = 0;
+	int ret = 0;
+
+	opts->fetch = 0;
+
+	if (unset) {
+		opts->track = BRANCH_TRACK_NEVER;
+		return 0;
+	}
+
+	opts->track = BRANCH_TRACK_EXPLICIT;
+	if (!arg)
+		return 0;
+
+	string_list_split(&tokens, arg, ",", -1);
+	for_each_string_list_item(item, &tokens) {
+		if (!strcmp(item->string, "fetch")) {
+			opts->fetch = 1;
+		} else if (!strcmp(item->string, "direct")) {
+			saw_direct = 1;
+			opts->track = BRANCH_TRACK_EXPLICIT;
+		} else if (!strcmp(item->string, "inherit")) {
+			saw_inherit = 1;
+			opts->track = BRANCH_TRACK_INHERIT;
+		} else {
+			ret = error(_("option `%s' expects \"%s\", \"%s\", "
+				      "or \"%s\""),
+				    "--track", "direct", "inherit", "fetch");
+			goto out;
+		}
+	}
+
+	if (saw_direct && saw_inherit)
+		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
+			    "--track", "direct", "inherit");
+
+out:
+	string_list_clear(&tokens, 0);
+	return ret;
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1244,7 +1398,6 @@ static int git_checkout_config(const char *var, const char *value,
 		opts->dwim_new_local_branch = git_config_bool(var, value);
 		return 0;
 	}
-
 	if (starts_with(var, "submodule."))
 		return git_default_submodule_config(var, value, NULL);
 
@@ -1741,10 +1894,10 @@ static struct option *add_common_switch_branch_options(
 {
 	struct option options[] = {
 		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
-		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
+		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
 			N_("set branch tracking configuration"),
 			PARSE_OPT_OPTARG,
-			parse_opt_tracking_mode),
+			parse_opt_checkout_track),
 		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
@@ -1949,8 +2102,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0]);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 9bcf7c0b40..19ac6a1a2e 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -801,4 +801,136 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --track=fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
+	test_cmp_config fetch_upstream branch.local_new.remote &&
+	test_cmp_config refs/heads/fetch_new branch.local_new.merge
+'
+
+test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
+'
+
+test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
+	git checkout main &&
+	git -C fetch_upstream checkout main &&
+	git remote set-head fetch_upstream main &&
+	git -C fetch_upstream checkout -b fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_pre &&
+	git fetch fetch_upstream fetch_unrelated &&
+	unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_main_post &&
+	git -C fetch_upstream checkout fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_post &&
+	git checkout --track=fetch -b local_from_remote fetch_upstream &&
+	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
+'
+
+test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_offline &&
+	test_commit -C fetch_upstream u_offline &&
+	git fetch fetch_upstream fetch_offline &&
+	saved_url=$(git config remote.fetch_upstream.url) &&
+	test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
+	git config remote.fetch_upstream.url ./does-not-exist &&
+	git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
+	test_grep "failed to fetch" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
+'
+
+test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_refspec &&
+	test_commit -C fetch_upstream u_refspec &&
+	git fetch fetch_upstream fetch_refspec &&
+	git remote add fetch_custom ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_custom" &&
+	git config --replace-all remote.fetch_custom.fetch \
+		"+refs/heads/*:refs/remotes/custom-ns/*" &&
+	git fetch fetch_custom &&
+	test_commit -C fetch_upstream u_refspec_post &&
+	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
+	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
+'
+
+test_expect_success 'checkout --track=inherit,direct is rejected' '
+	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
+	test_grep "cannot combine" err
+'
+
+test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_lastwin &&
+	test_commit -C fetch_upstream u_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
+	test_must_fail git checkout --track=fetch --track=direct \
+		-b local_lastwin fetch_upstream/fetch_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
+'
+
+test_expect_success 'checkout --track=fetch,inherit fetches and inherits' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit &&
+	git fetch fetch_upstream fetch_inherit &&
+	git checkout -b base_inherit fetch_upstream/fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit2 &&
+	git checkout main &&
+	git checkout --track=fetch,inherit -b local_inherit base_inherit &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD &&
+	test_cmp_config fetch_upstream branch.local_inherit.remote &&
+	test_cmp_config refs/heads/fetch_inherit branch.local_inherit.merge
+'
+
+test_expect_success 'checkout --track=bogus reports an error' '
+	git checkout main &&
+	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
+	test_grep "expects" err
+'
+
+test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done

base-commit: 7760f83b59750c27df653c5c46d0f80e44cfe02c
-- 
gitgitgadget
Junio C HamanoMay 12, 2026, 00:32 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH v8] checkout: extend --track with a "fetch" mode to refresh start-point

"Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
Show 21 quoted lines
> diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
> index 43ccf47cf6..28f17f427e 100644
> --- a/Documentation/git-checkout.adoc
> +++ b/Documentation/git-checkout.adoc
> @@ -158,11 +158,22 @@ of it").
>  	resets _<branch>_ to the start point instead of failing.
>  
>  `-t`::
> -`--track[=(direct|inherit)]`::
> +`--track[=(direct|inherit|fetch)[,...]]`::
>  	When creating a new branch, set up "upstream" configuration. See
>  	`--track` in linkgit:git-branch[1] for details. As a convenience,
>  	--track without -b implies branch creation.
>  +
> +The argument is a comma-separated list. `direct` (the default) and
> +`inherit` select the tracking mode and are mutually exclusive. Adding
> +`fetch` requests that the remote be fetched before _<start-point>_ is
> +resolved, so the new branch starts from a fresh tip: when
> +_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
> +updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
> +only the remote's default branch is updated.

The latter is because "checkout -t -b new remote/origin" makes "new" track "remote/origin/HEAD", which makes sense. And of course this fetch can fail.

Show 28 quoted lines
> +static int resolve_fetch_target(const char *arg, char **remote_out,
> +				char **src_ref_out)
> +{
> +	const char *slash;
> +	char *remote_name;
> +	struct remote *remote;
> +	struct refspec_item query = { 0 };
> +	struct strbuf dst = STRBUF_INIT;
> +	const char *rest;
> +
> +	*remote_out = NULL;
> +	*src_ref_out = NULL;
> +
> +	if (!arg || !*arg)
> +		return -1;
> +
> +	slash = strchr(arg, '/');
> +	if (slash == arg)
> +		return -1;
> +	remote_name = slash ? xstrndup(arg, slash - arg) : xstrdup(arg);
> +
> +	remote = remote_get(remote_name);
> +	if (!remote || !remote_is_configured(remote, 1)) {
> +		free(remote_name);
> +		return -1;
> +	}
> +
> +	rest = (slash && slash[1]) ? slash + 1 : NULL;

There is no slash when asking for "origin", and the control goes into the "if (!rest)" block.

Show 18 quoted lines
> +	if (!rest) {
> +		struct object_id oid;
> +		const char *head_target;
> +		const char *short_target;
> +
> +		strbuf_addf(&dst, "refs/remotes/%s/HEAD", remote_name);
> +		head_target = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
> +						      dst.buf,
> +						      RESOLVE_REF_READING |
> +						      RESOLVE_REF_NO_RECURSE,
> +						      &oid, NULL);
> +		strbuf_reset(&dst);
> +		if (head_target &&
> +		    skip_prefix(head_target, "refs/remotes/", &short_target) &&
> +		    skip_prefix(short_target, remote_name, &short_target) &&
> +		    *short_target == '/')
> +			rest = short_target + 1;
> +	}

If refs/remotes/origin/HEAD points at refs/remotes/origin/main, rest gets "main". Otherwise (i.e. unexpected contents in HEAD or lacking HEAD), rest remains NULL. And then we have the "if (rest)" block.

Show 15 quoted lines
> +	if (rest) {
> +		strbuf_addf(&dst, "refs/remotes/%s/%s", remote_name, rest);
> +		query.dst = dst.buf;
> +		if (!remote_find_tracking(remote, &query) && query.src) {
> +			*src_ref_out = xstrdup(query.src);
> +			free(query.src);
> +		} else {
> +			*src_ref_out = xstrdup(rest);
> +		}
> +	}
> +
> +	strbuf_release(&dst);
> +	*remote_out = remote_name;
> +	return 0;
> +}

It is not a new problem but I do not remember how we explicitly forbid "hierarchical" remote names. refs/remotes/a/b/c might be their branch "b/c" at remote we call "a", or branch "c" at remote "a/b". Unless we forbid slashes in remote names, the "there is no slash so we got only the name of the remote to mean its HEAD" logic would not work well, so we may want to double check.

Show 22 quoted lines
> +static void fetch_remote_for_start_point(const char *arg)
> +{
> +	char *remote_name = NULL;
> +	char *src_ref = NULL;
> +	struct child_process cmd = CHILD_PROCESS_INIT;
> +	struct strbuf dst_ref = STRBUF_INIT;
> +	int have_existing_ref = 0;
> +
> +	if (resolve_fetch_target(arg, &remote_name, &src_ref))
> +		return;
> +
> +	{
> +		struct object_id oid;
> +
> +		if (strchr(arg, '/'))
> +			strbuf_addf(&dst_ref, "refs/remotes/%s", arg);
> +		else
> +			strbuf_addf(&dst_ref, "refs/remotes/%s/HEAD", arg);
> +		if (!refs_read_ref(get_main_ref_store(the_repository),
> +				   dst_ref.buf, &oid))
> +			have_existing_ref = 1;
> +	}

I do not quite see the point of this extra block. Can we do without it (and move the def of oid up near the beginning of the function, of course)?

Even better, as resolve_fetch_target() already looks at "arg" and poked at the remote-tracking ref hierarchy, wouldn't it make more sense to make that helper function responsible for finding out if there already is a usable, albeit potentially stale, ref?

Show 17 quoted lines
> +	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
> +	if (src_ref)
> +		strvec_push(&cmd.args, src_ref);
> +	cmd.git_cmd = 1;
> +	if (run_command(&cmd)) {
> +		if (have_existing_ref)
> +			warning(_("failed to fetch start-point '%s'; "
> +				  "using existing '%s'"),
> +				arg, dst_ref.buf);
> +		else
> +			die(_("failed to fetch start-point '%s'"), arg);
> +	}
> +
> +	free(remote_name);
> +	free(src_ref);
> +	strbuf_release(&dst_ref);
> +}
Show 7 quoted lines
> @@ -1244,7 +1398,6 @@ static int git_checkout_config(const char *var, const char *value,
>  		opts->dwim_new_local_branch = git_config_bool(var, value);
>  		return 0;
>  	}
> -
>  	if (starts_with(var, "submodule."))
>  		return git_default_submodule_config(var, value, NULL);
Unrelated patch noise?
Harald Nordgren via GitGitGadgetMay 12, 2026, 10:55 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v9] checkout: extend --track with a "fetch" mode to refresh start-point

From: Harald Nordgren <haraldnordgren@gmail.com>

If you want to fork your topic branch from the very latest of the tip of a branch your remote has, you would do:

    git fetch origin some-branch
    git checkout -b new_branch --track origin/some-branch

Extend the "--track" option of "git checkout" and allow users to write

    git checkout -b new_branch --track=fetch origin/some-branch

to (1) fetch 'some-branch' from the remote 'origin', updating the remote-tracking branch 'origin/some-branch', (2) arrange subsequent 'git pull' on 'new_branch' to interact with 'origin/some-branch' and (3) fork 'new_branch' from it.

In the value of the '--track' option, 'fetch' can be combined with the existing 'direct' (default) and 'inherit' modes via a comma-separated list. Examples:

    git checkout -b new_branch --track=fetch,inherit some_local_branch
    git switch -c new_branch --track=fetch origin/some-branch

When "fetch" is requested and <start-point> is in <remote>/<branch> form, run "git fetch <remote> <branch>" before resolving the ref, so that other remote-tracking branches are left untouched. If <start-point> is a bare remote name like "origin" (which resolves to that remote's default branch), "git fetch <remote>" is run instead, since the target branch is not known up front. Abort the checkout if the fetch fails.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
    checkout: --track=fetch
    
     * Support hierarchical remote names (e.g. nested/remote) by trying the
       longest prefix first.
     * Fold the existing-ref lookup into resolve_fetch_target() so it
       returns the ref name directly.
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v9
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v9
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v8:
 1:  61c2199fd5 ! 1:  021375e4cc checkout: extend --track with a "fetch" mode to refresh start-point
     @@ builtin/checkout.c: struct branch_info {
       };
       
      +static int resolve_fetch_target(const char *arg, char **remote_out,
     -+				char **src_ref_out)
     ++				char **src_ref_out, char **existing_ref_out)
      +{
      +	const char *slash;
     -+	char *remote_name;
     -+	struct remote *remote;
     ++	char *remote_name = NULL;
     ++	struct remote *remote = NULL;
      +	struct refspec_item query = { 0 };
      +	struct strbuf dst = STRBUF_INIT;
     -+	const char *rest;
     ++	struct object_id oid;
     ++	const char *rest = NULL;
     ++	const char *head_target = NULL;
     ++	const char *short_target;
      +
      +	*remote_out = NULL;
      +	*src_ref_out = NULL;
     ++	*existing_ref_out = NULL;
      +
     -+	if (!arg || !*arg)
     -+		return -1;
     -+
     -+	slash = strchr(arg, '/');
     -+	if (slash == arg)
     ++	if (!arg || !*arg || *arg == '/')
      +		return -1;
     -+	remote_name = slash ? xstrndup(arg, slash - arg) : xstrdup(arg);
      +
     -+	remote = remote_get(remote_name);
     -+	if (!remote || !remote_is_configured(remote, 1)) {
     ++	slash = arg + strlen(arg);
     ++	while (1) {
      +		free(remote_name);
     -+		return -1;
     ++		remote_name = xstrndup(arg, slash - arg);
     ++		remote = remote_get(remote_name);
     ++		if (remote && remote_is_configured(remote, 1))
     ++			break;
     ++		while (slash > arg && *--slash != '/')
     ++			;
     ++		if (slash == arg) {
     ++			free(remote_name);
     ++			return -1;
     ++		}
      +	}
      +
     -+	rest = (slash && slash[1]) ? slash + 1 : NULL;
     ++	if (*slash == '/' && slash[1])
     ++		rest = slash + 1;
      +	if (!rest) {
     -+		struct object_id oid;
     -+		const char *head_target;
     -+		const char *short_target;
     -+
      +		strbuf_addf(&dst, "refs/remotes/%s/HEAD", remote_name);
      +		head_target = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
      +						      dst.buf,
      +						      RESOLVE_REF_READING |
      +						      RESOLVE_REF_NO_RECURSE,
      +						      &oid, NULL);
     ++		if (head_target) {
     ++			*existing_ref_out = xstrdup(dst.buf);
     ++			if (skip_prefix(head_target, "refs/remotes/", &short_target) &&
     ++			    skip_prefix(short_target, remote_name, &short_target) &&
     ++			    *short_target == '/')
     ++				rest = short_target + 1;
     ++		}
      +		strbuf_reset(&dst);
     -+		if (head_target &&
     -+		    skip_prefix(head_target, "refs/remotes/", &short_target) &&
     -+		    skip_prefix(short_target, remote_name, &short_target) &&
     -+		    *short_target == '/')
     -+			rest = short_target + 1;
      +	}
      +
      +	if (rest) {
     @@ builtin/checkout.c: struct branch_info {
      +		} else {
      +			*src_ref_out = xstrdup(rest);
      +		}
     ++		if (!*existing_ref_out) {
     ++			strbuf_reset(&dst);
     ++			strbuf_addf(&dst, "refs/remotes/%s", arg);
     ++			if (!refs_read_ref(get_main_ref_store(the_repository),
     ++					   dst.buf, &oid))
     ++				*existing_ref_out = xstrdup(dst.buf);
     ++		}
      +	}
      +
      +	strbuf_release(&dst);
     @@ builtin/checkout.c: struct branch_info {
      +{
      +	char *remote_name = NULL;
      +	char *src_ref = NULL;
     ++	char *existing_ref = NULL;
      +	struct child_process cmd = CHILD_PROCESS_INIT;
     -+	struct strbuf dst_ref = STRBUF_INIT;
     -+	int have_existing_ref = 0;
      +
     -+	if (resolve_fetch_target(arg, &remote_name, &src_ref))
     ++	if (resolve_fetch_target(arg, &remote_name, &src_ref, &existing_ref))
      +		return;
      +
     -+	{
     -+		struct object_id oid;
     -+
     -+		if (strchr(arg, '/'))
     -+			strbuf_addf(&dst_ref, "refs/remotes/%s", arg);
     -+		else
     -+			strbuf_addf(&dst_ref, "refs/remotes/%s/HEAD", arg);
     -+		if (!refs_read_ref(get_main_ref_store(the_repository),
     -+				   dst_ref.buf, &oid))
     -+			have_existing_ref = 1;
     -+	}
     -+
      +	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
      +	if (src_ref)
      +		strvec_push(&cmd.args, src_ref);
      +	cmd.git_cmd = 1;
      +	if (run_command(&cmd)) {
     -+		if (have_existing_ref)
     ++		if (existing_ref)
      +			warning(_("failed to fetch start-point '%s'; "
      +				  "using existing '%s'"),
     -+				arg, dst_ref.buf);
     ++				arg, existing_ref);
      +		else
      +			die(_("failed to fetch start-point '%s'"), arg);
      +	}
      +
      +	free(remote_name);
      +	free(src_ref);
     -+	strbuf_release(&dst_ref);
     ++	free(existing_ref);
      +}
      +
      +static int parse_opt_checkout_track(const struct option *opt,
     @@ builtin/checkout.c: struct branch_info {
       static void branch_info_release(struct branch_info *info)
       {
       	free(info->name);
     -@@ builtin/checkout.c: static int git_checkout_config(const char *var, const char *value,
     - 		opts->dwim_new_local_branch = git_config_bool(var, value);
     - 		return 0;
     - 	}
     --
     - 	if (starts_with(var, "submodule."))
     - 		return git_default_submodule_config(var, value, NULL);
     - 
      @@ builtin/checkout.c: static struct option *add_common_switch_branch_options(
       {
       	struct option options[] = {
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
      +'
      +
     ++test_expect_success 'checkout --track=fetch handles hierarchical remote name' '
     ++	git checkout main &&
     ++	git -C fetch_upstream checkout -b fetch_hier &&
     ++	test_commit -C fetch_upstream u_hier &&
     ++	git remote add nested/remote ./fetch_upstream &&
     ++	test_when_finished "git remote remove nested/remote" &&
     ++	git fetch nested/remote fetch_hier &&
     ++	test_commit -C fetch_upstream u_hier_post &&
     ++	git checkout --track=fetch -b local_hier nested/remote/fetch_hier &&
     ++	test_cmp_rev refs/remotes/nested/remote/fetch_hier HEAD
     ++'
     ++
      +test_expect_success 'checkout --track=inherit,direct is rejected' '
      +	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
      +	test_grep "cannot combine" err
 Documentation/git-checkout.adoc |  13 ++-
 Documentation/git-switch.adoc   |  13 ++-
 builtin/checkout.c              | 168 +++++++++++++++++++++++++++++++-
 t/t7201-co.sh                   | 144 +++++++++++++++++++++++++++
 4 files changed, 332 insertions(+), 6 deletions(-)
Show changes to 4 files +332 −6

Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh

diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index 43ccf47cf6..28f17f427e 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -158,11 +158,22 @@ of it").
 	resets _<branch>_ to the start point instead of failing.
 
 `-t`::
-`--track[=(direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration. See
 	`--track` in linkgit:git-branch[1] for details. As a convenience,
 	--track without -b implies branch creation.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
+only the remote's default branch is updated. If the fetch fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the checkout proceeds from the existing tip; otherwise the checkout
+is aborted.
++
 If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index 87707e9265..3f54cf39e9 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -154,11 +154,22 @@ should result in deletion of the path).
 	attached to a terminal, regardless of `--quiet`.
 
 `-t`::
-`--track[ (direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration.
 	`-c` is implied. See `--track` in linkgit:git-branch[1] for
 	details.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
+only the remote's default branch is updated. If the fetch fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the switch proceeds from the existing tip; otherwise the switch is
+aborted.
++
 If no `-c` option is given, the name of the new branch will be derived
 from the remote-tracking branch, by looking at the local part of the
 refspec configured for the corresponding remote, and then stripping
diff --git a/builtin/checkout.c b/builtin/checkout.c
index ac0186a33e..aff442c526 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -26,10 +26,12 @@
 #include "preload-index.h"
 #include "read-cache.h"
 #include "refs.h"
+#include "refspec.h"
 #include "remote.h"
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "setup.h"
 #include "strvec.h"
 #include "submodule.h"
@@ -62,6 +64,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -113,6 +116,158 @@ struct branch_info {
 	char *checkout;
 };
 
+static int resolve_fetch_target(const char *arg, char **remote_out,
+				char **src_ref_out, char **existing_ref_out)
+{
+	const char *slash;
+	char *remote_name = NULL;
+	struct remote *remote = NULL;
+	struct refspec_item query = { 0 };
+	struct strbuf dst = STRBUF_INIT;
+	struct object_id oid;
+	const char *rest = NULL;
+	const char *head_target = NULL;
+	const char *short_target;
+
+	*remote_out = NULL;
+	*src_ref_out = NULL;
+	*existing_ref_out = NULL;
+
+	if (!arg || !*arg || *arg == '/')
+		return -1;
+
+	slash = arg + strlen(arg);
+	while (1) {
+		free(remote_name);
+		remote_name = xstrndup(arg, slash - arg);
+		remote = remote_get(remote_name);
+		if (remote && remote_is_configured(remote, 1))
+			break;
+		while (slash > arg && *--slash != '/')
+			;
+		if (slash == arg) {
+			free(remote_name);
+			return -1;
+		}
+	}
+
+	if (*slash == '/' && slash[1])
+		rest = slash + 1;
+	if (!rest) {
+		strbuf_addf(&dst, "refs/remotes/%s/HEAD", remote_name);
+		head_target = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
+						      dst.buf,
+						      RESOLVE_REF_READING |
+						      RESOLVE_REF_NO_RECURSE,
+						      &oid, NULL);
+		if (head_target) {
+			*existing_ref_out = xstrdup(dst.buf);
+			if (skip_prefix(head_target, "refs/remotes/", &short_target) &&
+			    skip_prefix(short_target, remote_name, &short_target) &&
+			    *short_target == '/')
+				rest = short_target + 1;
+		}
+		strbuf_reset(&dst);
+	}
+
+	if (rest) {
+		strbuf_addf(&dst, "refs/remotes/%s/%s", remote_name, rest);
+		query.dst = dst.buf;
+		if (!remote_find_tracking(remote, &query) && query.src) {
+			*src_ref_out = xstrdup(query.src);
+			free(query.src);
+		} else {
+			*src_ref_out = xstrdup(rest);
+		}
+		if (!*existing_ref_out) {
+			strbuf_reset(&dst);
+			strbuf_addf(&dst, "refs/remotes/%s", arg);
+			if (!refs_read_ref(get_main_ref_store(the_repository),
+					   dst.buf, &oid))
+				*existing_ref_out = xstrdup(dst.buf);
+		}
+	}
+
+	strbuf_release(&dst);
+	*remote_out = remote_name;
+	return 0;
+}
+
+static void fetch_remote_for_start_point(const char *arg)
+{
+	char *remote_name = NULL;
+	char *src_ref = NULL;
+	char *existing_ref = NULL;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+
+	if (resolve_fetch_target(arg, &remote_name, &src_ref, &existing_ref))
+		return;
+
+	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
+	if (src_ref)
+		strvec_push(&cmd.args, src_ref);
+	cmd.git_cmd = 1;
+	if (run_command(&cmd)) {
+		if (existing_ref)
+			warning(_("failed to fetch start-point '%s'; "
+				  "using existing '%s'"),
+				arg, existing_ref);
+		else
+			die(_("failed to fetch start-point '%s'"), arg);
+	}
+
+	free(remote_name);
+	free(src_ref);
+	free(existing_ref);
+}
+
+static int parse_opt_checkout_track(const struct option *opt,
+				    const char *arg, int unset)
+{
+	struct checkout_opts *opts = opt->value;
+	struct string_list tokens = STRING_LIST_INIT_DUP;
+	struct string_list_item *item;
+	int saw_direct = 0, saw_inherit = 0;
+	int ret = 0;
+
+	opts->fetch = 0;
+
+	if (unset) {
+		opts->track = BRANCH_TRACK_NEVER;
+		return 0;
+	}
+
+	opts->track = BRANCH_TRACK_EXPLICIT;
+	if (!arg)
+		return 0;
+
+	string_list_split(&tokens, arg, ",", -1);
+	for_each_string_list_item(item, &tokens) {
+		if (!strcmp(item->string, "fetch")) {
+			opts->fetch = 1;
+		} else if (!strcmp(item->string, "direct")) {
+			saw_direct = 1;
+			opts->track = BRANCH_TRACK_EXPLICIT;
+		} else if (!strcmp(item->string, "inherit")) {
+			saw_inherit = 1;
+			opts->track = BRANCH_TRACK_INHERIT;
+		} else {
+			ret = error(_("option `%s' expects \"%s\", \"%s\", "
+				      "or \"%s\""),
+				    "--track", "direct", "inherit", "fetch");
+			goto out;
+		}
+	}
+
+	if (saw_direct && saw_inherit)
+		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
+			    "--track", "direct", "inherit");
+
+out:
+	string_list_clear(&tokens, 0);
+	return ret;
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1741,10 +1896,10 @@ static struct option *add_common_switch_branch_options(
 {
 	struct option options[] = {
 		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
-		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
+		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
 			N_("set branch tracking configuration"),
 			PARSE_OPT_OPTARG,
-			parse_opt_tracking_mode),
+			parse_opt_checkout_track),
 		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
@@ -1949,8 +2104,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0]);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 9bcf7c0b40..6dfe9ec931 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -801,4 +801,148 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --track=fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
+	test_cmp_config fetch_upstream branch.local_new.remote &&
+	test_cmp_config refs/heads/fetch_new branch.local_new.merge
+'
+
+test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
+'
+
+test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
+	git checkout main &&
+	git -C fetch_upstream checkout main &&
+	git remote set-head fetch_upstream main &&
+	git -C fetch_upstream checkout -b fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_pre &&
+	git fetch fetch_upstream fetch_unrelated &&
+	unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_main_post &&
+	git -C fetch_upstream checkout fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_post &&
+	git checkout --track=fetch -b local_from_remote fetch_upstream &&
+	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
+'
+
+test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_offline &&
+	test_commit -C fetch_upstream u_offline &&
+	git fetch fetch_upstream fetch_offline &&
+	saved_url=$(git config remote.fetch_upstream.url) &&
+	test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
+	git config remote.fetch_upstream.url ./does-not-exist &&
+	git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
+	test_grep "failed to fetch" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
+'
+
+test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_refspec &&
+	test_commit -C fetch_upstream u_refspec &&
+	git fetch fetch_upstream fetch_refspec &&
+	git remote add fetch_custom ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_custom" &&
+	git config --replace-all remote.fetch_custom.fetch \
+		"+refs/heads/*:refs/remotes/custom-ns/*" &&
+	git fetch fetch_custom &&
+	test_commit -C fetch_upstream u_refspec_post &&
+	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
+	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
+'
+
+test_expect_success 'checkout --track=fetch handles hierarchical remote name' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_hier &&
+	test_commit -C fetch_upstream u_hier &&
+	git remote add nested/remote ./fetch_upstream &&
+	test_when_finished "git remote remove nested/remote" &&
+	git fetch nested/remote fetch_hier &&
+	test_commit -C fetch_upstream u_hier_post &&
+	git checkout --track=fetch -b local_hier nested/remote/fetch_hier &&
+	test_cmp_rev refs/remotes/nested/remote/fetch_hier HEAD
+'
+
+test_expect_success 'checkout --track=inherit,direct is rejected' '
+	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
+	test_grep "cannot combine" err
+'
+
+test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_lastwin &&
+	test_commit -C fetch_upstream u_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
+	test_must_fail git checkout --track=fetch --track=direct \
+		-b local_lastwin fetch_upstream/fetch_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
+'
+
+test_expect_success 'checkout --track=fetch,inherit fetches and inherits' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit &&
+	git fetch fetch_upstream fetch_inherit &&
+	git checkout -b base_inherit fetch_upstream/fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit2 &&
+	git checkout main &&
+	git checkout --track=fetch,inherit -b local_inherit base_inherit &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD &&
+	test_cmp_config fetch_upstream branch.local_inherit.remote &&
+	test_cmp_config refs/heads/fetch_inherit branch.local_inherit.merge
+'
+
+test_expect_success 'checkout --track=bogus reports an error' '
+	git checkout main &&
+	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
+	test_grep "expects" err
+'
+
+test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done

base-commit: 29bd7ed5127255713c1ac2f43b7c6f257d7b4594
-- 
gitgitgadget
Harald Nordgren via GitGitGadgetMay 18, 2026, 08:04 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v10] checkout: extend --track with a "fetch" mode to refresh start-point

From: Harald Nordgren <haraldnordgren@gmail.com>

If you want to fork your topic branch from the very latest of the tip of a branch your remote has, you would do:

    git fetch origin some-branch
    git checkout -b new_branch --track origin/some-branch

Extend the "--track" option of "git checkout" and allow users to write

    git checkout -b new_branch --track=fetch origin/some-branch

to (1) fetch 'some-branch' from the remote 'origin', updating the remote-tracking branch 'origin/some-branch', (2) arrange subsequent 'git pull' on 'new_branch' to interact with 'origin/some-branch' and (3) fork 'new_branch' from it.

In the value of the '--track' option, 'fetch' can be combined with the existing 'direct' (default) and 'inherit' modes via a comma-separated list. Examples:

    git checkout -b new_branch --track=fetch,inherit some_local_branch
    git switch -c new_branch --track=fetch origin/some-branch

When "fetch" is requested and <start-point> is in <remote>/<branch> form, run "git fetch <remote> <branch>" before resolving the ref, so that other remote-tracking branches are left untouched. If <start-point> is a bare remote name like "origin" (which resolves to that remote's default branch), "git fetch <remote>" is run instead, since the target branch is not known up front. Abort the checkout if the fetch fails.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
    checkout: --track=fetch
    
    Rebased to fix merge conflict with master.
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v10
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v10
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v9:
 1:  021375e4cc ! 1:  a773fb6bdf checkout: extend --track with a "fetch" mode to refresh start-point
     @@ Documentation/git-checkout.adoc: of it").
       the refspec configured for the corresponding remote, and then stripping
      
       ## Documentation/git-switch.adoc ##
     -@@ Documentation/git-switch.adoc: should result in deletion of the path).
     +@@ Documentation/git-switch.adoc: variable.
       	attached to a terminal, regardless of `--quiet`.
       
       `-t`::
     @@ builtin/checkout.c
       #include "resolve-undo.h"
       #include "revision.h"
      +#include "run-command.h"
     + #include "sequencer.h"
       #include "setup.h"
       #include "strvec.h"
     - #include "submodule.h"
      @@ builtin/checkout.c: struct checkout_opts {
       	int count_checkout_paths;
       	int overlay_mode;
 Documentation/git-checkout.adoc |  13 ++-
 Documentation/git-switch.adoc   |  13 ++-
 builtin/checkout.c              | 168 +++++++++++++++++++++++++++++++-
 t/t7201-co.sh                   | 144 +++++++++++++++++++++++++++
 4 files changed, 332 insertions(+), 6 deletions(-)
Show changes to 4 files +332 −6

Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh

diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index a8b3b8c2e2..ec63434159 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -158,11 +158,22 @@ of it").
 	resets _<branch>_ to the start point instead of failing.
 
 `-t`::
-`--track[=(direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration. See
 	`--track` in linkgit:git-branch[1] for details. As a convenience,
 	--track without -b implies branch creation.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
+only the remote's default branch is updated. If the fetch fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the checkout proceeds from the existing tip; otherwise the checkout
+is aborted.
++
 If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index d6c4f229a5..b5e79435cd 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -155,11 +155,22 @@ variable.
 	attached to a terminal, regardless of `--quiet`.
 
 `-t`::
-`--track[ (direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration.
 	`-c` is implied. See `--track` in linkgit:git-branch[1] for
 	details.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
+only the remote's default branch is updated. If the fetch fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the switch proceeds from the existing tip; otherwise the switch is
+aborted.
++
 If no `-c` option is given, the name of the new branch will be derived
 from the remote-tracking branch, by looking at the local part of the
 refspec configured for the corresponding remote, and then stripping
diff --git a/builtin/checkout.c b/builtin/checkout.c
index 1345e8574a..fc58456546 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -25,10 +25,12 @@
 #include "preload-index.h"
 #include "read-cache.h"
 #include "refs.h"
+#include "refspec.h"
 #include "remote.h"
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "sequencer.h"
 #include "setup.h"
 #include "strvec.h"
@@ -62,6 +64,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -115,6 +118,158 @@ struct branch_info {
 	char *checkout;
 };
 
+static int resolve_fetch_target(const char *arg, char **remote_out,
+				char **src_ref_out, char **existing_ref_out)
+{
+	const char *slash;
+	char *remote_name = NULL;
+	struct remote *remote = NULL;
+	struct refspec_item query = { 0 };
+	struct strbuf dst = STRBUF_INIT;
+	struct object_id oid;
+	const char *rest = NULL;
+	const char *head_target = NULL;
+	const char *short_target;
+
+	*remote_out = NULL;
+	*src_ref_out = NULL;
+	*existing_ref_out = NULL;
+
+	if (!arg || !*arg || *arg == '/')
+		return -1;
+
+	slash = arg + strlen(arg);
+	while (1) {
+		free(remote_name);
+		remote_name = xstrndup(arg, slash - arg);
+		remote = remote_get(remote_name);
+		if (remote && remote_is_configured(remote, 1))
+			break;
+		while (slash > arg && *--slash != '/')
+			;
+		if (slash == arg) {
+			free(remote_name);
+			return -1;
+		}
+	}
+
+	if (*slash == '/' && slash[1])
+		rest = slash + 1;
+	if (!rest) {
+		strbuf_addf(&dst, "refs/remotes/%s/HEAD", remote_name);
+		head_target = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
+						      dst.buf,
+						      RESOLVE_REF_READING |
+						      RESOLVE_REF_NO_RECURSE,
+						      &oid, NULL);
+		if (head_target) {
+			*existing_ref_out = xstrdup(dst.buf);
+			if (skip_prefix(head_target, "refs/remotes/", &short_target) &&
+			    skip_prefix(short_target, remote_name, &short_target) &&
+			    *short_target == '/')
+				rest = short_target + 1;
+		}
+		strbuf_reset(&dst);
+	}
+
+	if (rest) {
+		strbuf_addf(&dst, "refs/remotes/%s/%s", remote_name, rest);
+		query.dst = dst.buf;
+		if (!remote_find_tracking(remote, &query) && query.src) {
+			*src_ref_out = xstrdup(query.src);
+			free(query.src);
+		} else {
+			*src_ref_out = xstrdup(rest);
+		}
+		if (!*existing_ref_out) {
+			strbuf_reset(&dst);
+			strbuf_addf(&dst, "refs/remotes/%s", arg);
+			if (!refs_read_ref(get_main_ref_store(the_repository),
+					   dst.buf, &oid))
+				*existing_ref_out = xstrdup(dst.buf);
+		}
+	}
+
+	strbuf_release(&dst);
+	*remote_out = remote_name;
+	return 0;
+}
+
+static void fetch_remote_for_start_point(const char *arg)
+{
+	char *remote_name = NULL;
+	char *src_ref = NULL;
+	char *existing_ref = NULL;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+
+	if (resolve_fetch_target(arg, &remote_name, &src_ref, &existing_ref))
+		return;
+
+	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
+	if (src_ref)
+		strvec_push(&cmd.args, src_ref);
+	cmd.git_cmd = 1;
+	if (run_command(&cmd)) {
+		if (existing_ref)
+			warning(_("failed to fetch start-point '%s'; "
+				  "using existing '%s'"),
+				arg, existing_ref);
+		else
+			die(_("failed to fetch start-point '%s'"), arg);
+	}
+
+	free(remote_name);
+	free(src_ref);
+	free(existing_ref);
+}
+
+static int parse_opt_checkout_track(const struct option *opt,
+				    const char *arg, int unset)
+{
+	struct checkout_opts *opts = opt->value;
+	struct string_list tokens = STRING_LIST_INIT_DUP;
+	struct string_list_item *item;
+	int saw_direct = 0, saw_inherit = 0;
+	int ret = 0;
+
+	opts->fetch = 0;
+
+	if (unset) {
+		opts->track = BRANCH_TRACK_NEVER;
+		return 0;
+	}
+
+	opts->track = BRANCH_TRACK_EXPLICIT;
+	if (!arg)
+		return 0;
+
+	string_list_split(&tokens, arg, ",", -1);
+	for_each_string_list_item(item, &tokens) {
+		if (!strcmp(item->string, "fetch")) {
+			opts->fetch = 1;
+		} else if (!strcmp(item->string, "direct")) {
+			saw_direct = 1;
+			opts->track = BRANCH_TRACK_EXPLICIT;
+		} else if (!strcmp(item->string, "inherit")) {
+			saw_inherit = 1;
+			opts->track = BRANCH_TRACK_INHERIT;
+		} else {
+			ret = error(_("option `%s' expects \"%s\", \"%s\", "
+				      "or \"%s\""),
+				    "--track", "direct", "inherit", "fetch");
+			goto out;
+		}
+	}
+
+	if (saw_direct && saw_inherit)
+		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
+			    "--track", "direct", "inherit");
+
+out:
+	string_list_clear(&tokens, 0);
+	return ret;
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1733,10 +1888,10 @@ static struct option *add_common_switch_branch_options(
 {
 	struct option options[] = {
 		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
-		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
+		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
 			N_("set branch tracking configuration"),
 			PARSE_OPT_OPTARG,
-			parse_opt_tracking_mode),
+			parse_opt_checkout_track),
 		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
@@ -1941,8 +2096,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0]);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 7613b1d2a4..75b46494c0 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -870,4 +870,148 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --track=fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
+	test_cmp_config fetch_upstream branch.local_new.remote &&
+	test_cmp_config refs/heads/fetch_new branch.local_new.merge
+'
+
+test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
+'
+
+test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
+	git checkout main &&
+	git -C fetch_upstream checkout main &&
+	git remote set-head fetch_upstream main &&
+	git -C fetch_upstream checkout -b fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_pre &&
+	git fetch fetch_upstream fetch_unrelated &&
+	unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_main_post &&
+	git -C fetch_upstream checkout fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_post &&
+	git checkout --track=fetch -b local_from_remote fetch_upstream &&
+	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
+'
+
+test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_offline &&
+	test_commit -C fetch_upstream u_offline &&
+	git fetch fetch_upstream fetch_offline &&
+	saved_url=$(git config remote.fetch_upstream.url) &&
+	test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
+	git config remote.fetch_upstream.url ./does-not-exist &&
+	git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
+	test_grep "failed to fetch" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
+'
+
+test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_refspec &&
+	test_commit -C fetch_upstream u_refspec &&
+	git fetch fetch_upstream fetch_refspec &&
+	git remote add fetch_custom ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_custom" &&
+	git config --replace-all remote.fetch_custom.fetch \
+		"+refs/heads/*:refs/remotes/custom-ns/*" &&
+	git fetch fetch_custom &&
+	test_commit -C fetch_upstream u_refspec_post &&
+	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
+	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
+'
+
+test_expect_success 'checkout --track=fetch handles hierarchical remote name' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_hier &&
+	test_commit -C fetch_upstream u_hier &&
+	git remote add nested/remote ./fetch_upstream &&
+	test_when_finished "git remote remove nested/remote" &&
+	git fetch nested/remote fetch_hier &&
+	test_commit -C fetch_upstream u_hier_post &&
+	git checkout --track=fetch -b local_hier nested/remote/fetch_hier &&
+	test_cmp_rev refs/remotes/nested/remote/fetch_hier HEAD
+'
+
+test_expect_success 'checkout --track=inherit,direct is rejected' '
+	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
+	test_grep "cannot combine" err
+'
+
+test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_lastwin &&
+	test_commit -C fetch_upstream u_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
+	test_must_fail git checkout --track=fetch --track=direct \
+		-b local_lastwin fetch_upstream/fetch_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
+'
+
+test_expect_success 'checkout --track=fetch,inherit fetches and inherits' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit &&
+	git fetch fetch_upstream fetch_inherit &&
+	git checkout -b base_inherit fetch_upstream/fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit2 &&
+	git checkout main &&
+	git checkout --track=fetch,inherit -b local_inherit base_inherit &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD &&
+	test_cmp_config fetch_upstream branch.local_inherit.remote &&
+	test_cmp_config refs/heads/fetch_inherit branch.local_inherit.merge
+'
+
+test_expect_success 'checkout --track=bogus reports an error' '
+	git checkout main &&
+	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
+	test_grep "expects" err
+'
+
+test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done

base-commit: 68aca6b91299738150f71035d0033af6987fe455
-- 
gitgitgadget
Harald NordgrenMay 18, 2026, 08:06 UTC in reply to Junio C Hamano on lore

Re: [PATCH v8] checkout: extend --track with a "fetch" mode to refresh start-point

Show 8 quoted lines
> I do not quite see the point of this extra block.  Can we do without
> it (and move the def of oid up near the beginning of the function,
> of course)?
>
> Even better, as resolve_fetch_target() already looks at "arg" and
> poked at the remote-tracking ref hierarchy, wouldn't it make more
> sense to make that helper function responsible for finding out if
> there already is a usable, albeit potentially stale, ref?
Done. Can I get another review here please?
Show 9 quoted lines
> > @@ -1244,7 +1398,6 @@ static int git_checkout_config(const char *var, const char *value,
> >               opts->dwim_new_local_branch = git_config_bool(var, value);
> >               return 0;
> >       }
> > -
> >       if (starts_with(var, "submodule."))
> >               return git_default_submodule_config(var, value, NULL);
>
> Unrelated patch noise?
Removed.
Harald
Junio C HamanoMay 19, 2026, 06:16 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH v10] checkout: extend --track with a "fetch" mode to refresh start-point

"Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
Show 193 quoted lines
> From: Harald Nordgren <haraldnordgren@gmail.com>
>
> If you want to fork your topic branch from the very latest of the
> tip of a branch your remote has, you would do:
>
>     git fetch origin some-branch
>     git checkout -b new_branch --track origin/some-branch
>
> Extend the "--track" option of "git checkout" and allow users to
> write
>
>     git checkout -b new_branch --track=fetch origin/some-branch
>
> to (1) fetch 'some-branch' from the remote 'origin', updating the
> remote-tracking branch 'origin/some-branch', (2) arrange subsequent
> 'git pull' on 'new_branch' to interact with 'origin/some-branch' and
> (3) fork 'new_branch' from it.
>
> In the value of the '--track' option, 'fetch' can be combined with
> the existing 'direct' (default) and 'inherit' modes via a
> comma-separated list. Examples:
>
>     git checkout -b new_branch --track=fetch,inherit some_local_branch
>     git switch -c new_branch --track=fetch origin/some-branch
>
> When "fetch" is requested and <start-point> is in <remote>/<branch>
> form, run "git fetch <remote> <branch>" before resolving the ref, so
> that other remote-tracking branches are left untouched. If
> <start-point> is a bare remote name like "origin" (which resolves to
> that remote's default branch), "git fetch <remote>" is run instead,
> since the target branch is not known up front. Abort the checkout if
> the fetch fails.
>
> Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
> ---
>     checkout: --track=fetch
>     
>     Rebased to fix merge conflict with master.
>
> Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v10
> Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v10
> Pull-Request: https://github.com/git/git/pull/2281
>
> Range-diff vs v9:
>
>  1:  021375e4cc ! 1:  a773fb6bdf checkout: extend --track with a "fetch" mode to refresh start-point
>      @@ Documentation/git-checkout.adoc: of it").
>        the refspec configured for the corresponding remote, and then stripping
>       
>        ## Documentation/git-switch.adoc ##
>      -@@ Documentation/git-switch.adoc: should result in deletion of the path).
>      +@@ Documentation/git-switch.adoc: variable.
>        	attached to a terminal, regardless of `--quiet`.
>        
>        `-t`::
>      @@ builtin/checkout.c
>        #include "resolve-undo.h"
>        #include "revision.h"
>       +#include "run-command.h"
>      + #include "sequencer.h"
>        #include "setup.h"
>        #include "strvec.h"
>      - #include "submodule.h"
>       @@ builtin/checkout.c: struct checkout_opts {
>        	int count_checkout_paths;
>        	int overlay_mode;
>
>
>  Documentation/git-checkout.adoc |  13 ++-
>  Documentation/git-switch.adoc   |  13 ++-
>  builtin/checkout.c              | 168 +++++++++++++++++++++++++++++++-
>  t/t7201-co.sh                   | 144 +++++++++++++++++++++++++++
>  4 files changed, 332 insertions(+), 6 deletions(-)
>
> diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
> index a8b3b8c2e2..ec63434159 100644
> --- a/Documentation/git-checkout.adoc
> +++ b/Documentation/git-checkout.adoc
> @@ -158,11 +158,22 @@ of it").
>  	resets _<branch>_ to the start point instead of failing.
>  
>  `-t`::
> -`--track[=(direct|inherit)]`::
> +`--track[=(direct|inherit|fetch)[,...]]`::
>  	When creating a new branch, set up "upstream" configuration. See
>  	`--track` in linkgit:git-branch[1] for details. As a convenience,
>  	--track without -b implies branch creation.
>  +
> +The argument is a comma-separated list. `direct` (the default) and
> +`inherit` select the tracking mode and are mutually exclusive. Adding
> +`fetch` requests that the remote be fetched before _<start-point>_ is
> +resolved, so the new branch starts from a fresh tip: when
> +_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
> +updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
> +only the remote's default branch is updated. If the fetch fails and the
> +corresponding remote-tracking ref already exists, a warning is printed
> +and the checkout proceeds from the existing tip; otherwise the checkout
> +is aborted.
> ++
>  If no `-b` option is given, the name of the new branch will be
>  derived from the remote-tracking branch, by looking at the local part of
>  the refspec configured for the corresponding remote, and then stripping
> diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
> index d6c4f229a5..b5e79435cd 100644
> --- a/Documentation/git-switch.adoc
> +++ b/Documentation/git-switch.adoc
> @@ -155,11 +155,22 @@ variable.
>  	attached to a terminal, regardless of `--quiet`.
>  
>  `-t`::
> -`--track[ (direct|inherit)]`::
> +`--track[=(direct|inherit|fetch)[,...]]`::
>  	When creating a new branch, set up "upstream" configuration.
>  	`-c` is implied. See `--track` in linkgit:git-branch[1] for
>  	details.
>  +
> +The argument is a comma-separated list. `direct` (the default) and
> +`inherit` select the tracking mode and are mutually exclusive. Adding
> +`fetch` requests that the remote be fetched before _<start-point>_ is
> +resolved, so the new branch starts from a fresh tip: when
> +_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
> +updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
> +only the remote's default branch is updated. If the fetch fails and the
> +corresponding remote-tracking ref already exists, a warning is printed
> +and the switch proceeds from the existing tip; otherwise the switch is
> +aborted.
> ++
>  If no `-c` option is given, the name of the new branch will be derived
>  from the remote-tracking branch, by looking at the local part of the
>  refspec configured for the corresponding remote, and then stripping
> diff --git a/builtin/checkout.c b/builtin/checkout.c
> index 1345e8574a..fc58456546 100644
> --- a/builtin/checkout.c
> +++ b/builtin/checkout.c
> @@ -25,10 +25,12 @@
>  #include "preload-index.h"
>  #include "read-cache.h"
>  #include "refs.h"
> +#include "refspec.h"
>  #include "remote.h"
>  #include "repo-settings.h"
>  #include "resolve-undo.h"
>  #include "revision.h"
> +#include "run-command.h"
>  #include "sequencer.h"
>  #include "setup.h"
>  #include "strvec.h"
> @@ -62,6 +64,7 @@ struct checkout_opts {
>  	int count_checkout_paths;
>  	int overlay_mode;
>  	int dwim_new_local_branch;
> +	int fetch;
>  	int discard_changes;
>  	int accept_ref;
>  	int accept_pathspec;
> @@ -115,6 +118,158 @@ struct branch_info {
>  	char *checkout;
>  };
>  
> +static int resolve_fetch_target(const char *arg, char **remote_out,
> +				char **src_ref_out, char **existing_ref_out)
> +{
> +	const char *slash;
> +	char *remote_name = NULL;
> +	struct remote *remote = NULL;
> +	struct refspec_item query = { 0 };
> +	struct strbuf dst = STRBUF_INIT;
> +	struct object_id oid;
> +	const char *rest = NULL;
> +	const char *head_target = NULL;
> +	const char *short_target;
> +
> +	*remote_out = NULL;
> +	*src_ref_out = NULL;
> +	*existing_ref_out = NULL;
> +
> +	if (!arg || !*arg || *arg == '/')
> +		return -1;
> +
> +	slash = arg + strlen(arg);
> +	while (1) {
> +		free(remote_name);
> +		remote_name = xstrndup(arg, slash - arg);
> +		remote = remote_get(remote_name);
> +		if (remote && remote_is_configured(remote, 1))
> +			break;
> +		while (slash > arg && *--slash != '/')
> +			;
> +		if (slash == arg) {
> +			free(remote_name);
> +			return -1;
> +		}
> +	}

OK. So the caller gives "foo/bar/baz" when "foo/bar" is the name of the remote that uses "refs/remotes/foo/bar" to store remote-tracking branches from there. You check "foo/bar/baz", which fails to be a remote, then "foo/bar", which is a configured remote and break.

> +
> +	if (*slash == '/' && slash[1])
> +		rest = slash + 1;

And "baz" becomes the "rest"; if the user gave us "foo/bar" and the abobve loop found it as the name of the remote, we would want to use "refs/remotes/foo/bar/HEAD", which is the "if (!rest)" below is about.

Show 16 quoted lines
> +	if (!rest) {
> +		strbuf_addf(&dst, "refs/remotes/%s/HEAD", remote_name);
> +		head_target = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
> +						      dst.buf,
> +						      RESOLVE_REF_READING |
> +						      RESOLVE_REF_NO_RECURSE,
> +						      &oid, NULL);
> +		if (head_target) {
> +			*existing_ref_out = xstrdup(dst.buf);
> +			if (skip_prefix(head_target, "refs/remotes/", &short_target) &&
> +			    skip_prefix(short_target, remote_name, &short_target) &&
> +			    *short_target == '/')
> +				rest = short_target + 1;
> +		}
> +		strbuf_reset(&dst);
> +	}

So we may have been given "foo/bar" and after resolving HEAD there, have "baz" in rest. Or "foo/bar/baz" was given and we may have figured out that that is "baz" in "foo/bar".

Show 17 quoted lines
> +	if (rest) {
> +		strbuf_addf(&dst, "refs/remotes/%s/%s", remote_name, rest);
> +		query.dst = dst.buf;
> +		if (!remote_find_tracking(remote, &query) && query.src) {
> +			*src_ref_out = xstrdup(query.src);
> +			free(query.src);
> +		} else {
> +			*src_ref_out = xstrdup(rest);
> +		}
> +		if (!*existing_ref_out) {
> +			strbuf_reset(&dst);
> +			strbuf_addf(&dst, "refs/remotes/%s", arg);
> +			if (!refs_read_ref(get_main_ref_store(the_repository),
> +					   dst.buf, &oid))
> +				*existing_ref_out = xstrdup(dst.buf);
> +		}
> +	}

What happens if "HEAD" was not there, though. If "refs/remotes/foo/bar/" did not exist, we would have already returned -1 after trying to find which part in arg is the remote name. But if "refs/remotes/foo/bar" is valid, the user gave us "foo/bar", and we cannot find HEAD, then the above "if (rest)" is skipped. We give "foo/bar" to *remote_out, and return 0 without touching *src_ref_out or *existing_ref_out at all.

Show 18 quoted lines
> +	strbuf_release(&dst);
> +	*remote_out = remote_name;
> +	return 0;
> +}
> +
> +static void fetch_remote_for_start_point(const char *arg)
> +{
> +	char *remote_name = NULL;
> +	char *src_ref = NULL;
> +	char *existing_ref = NULL;
> +	struct child_process cmd = CHILD_PROCESS_INIT;
> +
> +	if (resolve_fetch_target(arg, &remote_name, &src_ref, &existing_ref))
> +		return;
> +
> +	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
> +	if (src_ref)
> +		strvec_push(&cmd.args, src_ref);
What should happen with this configuration
    [remote "origin"]
        fetch = refs/heads/*:refs/upstream/*
and the user says either of these two:
    $ git checkout --track=fetch upstream
    $ git checkout --track=fetch upstream/master

We fail to find in "where does the remote name ends and branch name start?" loop that this request is about remote "origin" at all, no? We may see in the former case that there is refs/remotes/upstream/HEAD >that points at "master" in the same hierarchy, but the code thinks "upstream" is the remote name, which would mean you would "git fetch upstream", when the remote you need to fetch from is "origin".

Show 8 quoted lines
> +	cmd.git_cmd = 1;
> +	if (run_command(&cmd)) {
> +		if (existing_ref)
> +			warning(_("failed to fetch start-point '%s'; "
> +				  "using existing '%s'"),
> +				arg, existing_ref);
> +		else
> +			die(_("failed to fetch start-point '%s'"), arg);

If we failed to set *existing_ref_out, shouldn't we fail without even attempting to call run_command() here, as we will have to die() anyway even if "git fetch" succeeds. For that matter, it may be simpler and more correct for resolve_fetch_target() to fail (return -1) when it happens, by making the lat "if (rest) {...}" to have a corresponding "else { return -1 }" after it.

Show 6 quoted lines
> +	}
> +
> +	free(remote_name);
> +	free(src_ref);
> +	free(existing_ref);
> +}
I'll stop here.
Harald NordgrenMay 19, 2026, 07:52 UTC in reply to Junio C Hamano on lore

Re: [PATCH v10] checkout: extend --track with a "fetch" mode to refresh start-point

Show 52 quoted lines
> > +     strbuf_release(&dst);
> > +     *remote_out = remote_name;
> > +     return 0;
> > +}
> > +
> > +static void fetch_remote_for_start_point(const char *arg)
> > +{
> > +     char *remote_name = NULL;
> > +     char *src_ref = NULL;
> > +     char *existing_ref = NULL;
> > +     struct child_process cmd = CHILD_PROCESS_INIT;
> > +
> > +     if (resolve_fetch_target(arg, &remote_name, &src_ref, &existing_ref))
> > +             return;
> > +
> > +     strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
> > +     if (src_ref)
> > +             strvec_push(&cmd.args, src_ref);
>
> What should happen with this configuration
>
>     [remote "origin"]
>         fetch = refs/heads/*:refs/upstream/*
>
> and the user says either of these two:
>
>     $ git checkout --track=fetch upstream
>     $ git checkout --track=fetch upstream/master
>
> We fail to find in "where does the remote name ends and branch name
> start?" loop that this request is about remote "origin" at all, no?
> We may see in the former case that there is
> refs/remotes/upstream/HEAD >that points at "master" in the same
> hierarchy, but the code thinks "upstream" is the remote name, which
> would mean you would "git fetch upstream", when the remote you need
> to fetch from is "origin".
>
> > +     cmd.git_cmd = 1;
> > +     if (run_command(&cmd)) {
> > +             if (existing_ref)
> > +                     warning(_("failed to fetch start-point '%s'; "
> > +                               "using existing '%s'"),
> > +                             arg, existing_ref);
> > +             else
> > +                     die(_("failed to fetch start-point '%s'"), arg);
>
> If we failed to set *existing_ref_out, shouldn't we fail without
> even attempting to call run_command() here, as we will have to die()
> anyway even if "git fetch" succeeds.  For that matter, it may be
> simpler and more correct for resolve_fetch_target() to fail (return
> -1) when it happens, by making the lat "if (rest) {...}" to have a
> corresponding "else { return -1 }" after it.
Yeah, good point. I will try to address this and send a new patch.
Harald
Harald Nordgren via GitGitGadgetMay 19, 2026, 07:58 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v11] checkout: extend --track with a "fetch" mode to refresh start-point

From: Harald Nordgren <haraldnordgren@gmail.com>

If you want to fork your topic branch from the very latest of the tip of a branch your remote has, you would do:

    git fetch origin some-branch
    git checkout -b new_branch --track origin/some-branch

Extend the "--track" option of "git checkout" and allow users to write

    git checkout -b new_branch --track=fetch origin/some-branch

to (1) fetch 'some-branch' from the remote 'origin', updating the remote-tracking branch 'origin/some-branch', (2) arrange subsequent 'git pull' on 'new_branch' to interact with 'origin/some-branch' and (3) fork 'new_branch' from it.

In the value of the '--track' option, 'fetch' can be combined with the existing 'direct' (default) and 'inherit' modes via a comma-separated list. Examples:

    git checkout -b new_branch --track=fetch,inherit some_local_branch
    git switch -c new_branch --track=fetch origin/some-branch

When "fetch" is requested and <start-point> is in <remote>/<branch> form, run "git fetch <remote> <branch>" before resolving the ref, so that other remote-tracking branches are left untouched. If <start-point> is a bare remote name like "origin" (which resolves to that remote's default branch), "git fetch <remote>" is run instead, since the target branch is not known up front. Abort the checkout if the fetch fails.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
    checkout: --track=fetch
    
     * Find the right remote by checking which remote's fetch refspec maps
       to the user's start-point, instead of assuming the start-point begins
       with the remote's name. This fixes cases where the user has a custom
       refspec mapping into a namespace whose name differs from the remote
       (e.g. fetching from origin into refs/remotes/upstream/*).
     * For a bare namespace name, follow <namespace>/HEAD first to figure
       out which branch to fetch.
     * Strengthen the custom-refspec test so it actually exercises the fetch
       (no prior git fetch).
     * New test for the bare-namespace case.
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v11
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v11
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v10:
 1:  a773fb6bdf ! 1:  d0c9e3e879 checkout: extend --track with a "fetch" mode to refresh start-point
     @@ builtin/checkout.c: struct branch_info {
       	char *checkout;
       };
       
     ++struct fetch_target_cb {
     ++	struct refspec_item query;
     ++	const char *remote_name;
     ++	int matches;
     ++};
     ++
     ++static int match_fetch_target(struct remote *remote, void *priv)
     ++{
     ++	struct fetch_target_cb *cb = priv;
     ++	struct refspec_item q = { .dst = cb->query.dst };
     ++
     ++	if (!remote_find_tracking(remote, &q) && q.src) {
     ++		if (++cb->matches == 1) {
     ++			cb->remote_name = remote->name;
     ++			free(cb->query.src);
     ++			cb->query.src = q.src;
     ++		} else {
     ++			free(q.src);
     ++		}
     ++	}
     ++	return 0;
     ++}
     ++
      +static int resolve_fetch_target(const char *arg, char **remote_out,
      +				char **src_ref_out, char **existing_ref_out)
      +{
     -+	const char *slash;
     -+	char *remote_name = NULL;
     -+	struct remote *remote = NULL;
     -+	struct refspec_item query = { 0 };
      +	struct strbuf dst = STRBUF_INIT;
     ++	struct strbuf head_path = STRBUF_INIT;
     ++	struct fetch_target_cb cb = { 0 };
      +	struct object_id oid;
     -+	const char *rest = NULL;
     -+	const char *head_target = NULL;
     -+	const char *short_target;
     ++	const char *head_target;
      +
      +	*remote_out = NULL;
      +	*src_ref_out = NULL;
      +	*existing_ref_out = NULL;
      +
     -+	if (!arg || !*arg || *arg == '/')
     ++	if (!arg || !*arg)
      +		return -1;
      +
     -+	slash = arg + strlen(arg);
     -+	while (1) {
     -+		free(remote_name);
     -+		remote_name = xstrndup(arg, slash - arg);
     -+		remote = remote_get(remote_name);
     -+		if (remote && remote_is_configured(remote, 1))
     -+			break;
     -+		while (slash > arg && *--slash != '/')
     -+			;
     -+		if (slash == arg) {
     -+			free(remote_name);
     -+			return -1;
     -+		}
     -+	}
     -+
     -+	if (*slash == '/' && slash[1])
     -+		rest = slash + 1;
     -+	if (!rest) {
     -+		strbuf_addf(&dst, "refs/remotes/%s/HEAD", remote_name);
     -+		head_target = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
     -+						      dst.buf,
     -+						      RESOLVE_REF_READING |
     -+						      RESOLVE_REF_NO_RECURSE,
     -+						      &oid, NULL);
     -+		if (head_target) {
     -+			*existing_ref_out = xstrdup(dst.buf);
     -+			if (skip_prefix(head_target, "refs/remotes/", &short_target) &&
     -+			    skip_prefix(short_target, remote_name, &short_target) &&
     -+			    *short_target == '/')
     -+				rest = short_target + 1;
     -+		}
     -+		strbuf_reset(&dst);
     ++	strbuf_addf(&head_path, "refs/remotes/%s/HEAD", arg);
     ++	head_target = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
     ++					      head_path.buf,
     ++					      RESOLVE_REF_READING |
     ++					      RESOLVE_REF_NO_RECURSE,
     ++					      &oid, NULL);
     ++	if (head_target)
     ++		strbuf_addstr(&dst, head_target);
     ++	else
     ++		strbuf_addf(&dst, "refs/remotes/%s", arg);
     ++
     ++	cb.query.dst = dst.buf;
     ++	for_each_remote(match_fetch_target, &cb);
     ++
     ++	if (cb.matches != 1) {
     ++		free(cb.query.src);
     ++		strbuf_release(&dst);
     ++		strbuf_release(&head_path);
     ++		return -1;
      +	}
      +
     -+	if (rest) {
     -+		strbuf_addf(&dst, "refs/remotes/%s/%s", remote_name, rest);
     -+		query.dst = dst.buf;
     -+		if (!remote_find_tracking(remote, &query) && query.src) {
     -+			*src_ref_out = xstrdup(query.src);
     -+			free(query.src);
     -+		} else {
     -+			*src_ref_out = xstrdup(rest);
     -+		}
     -+		if (!*existing_ref_out) {
     -+			strbuf_reset(&dst);
     -+			strbuf_addf(&dst, "refs/remotes/%s", arg);
     -+			if (!refs_read_ref(get_main_ref_store(the_repository),
     -+					   dst.buf, &oid))
     -+				*existing_ref_out = xstrdup(dst.buf);
     -+		}
     -+	}
     ++	*remote_out = xstrdup(cb.remote_name);
     ++	*src_ref_out = cb.query.src;
     ++	if (head_target)
     ++		*existing_ref_out = strbuf_detach(&head_path, NULL);
     ++	else if (!refs_read_ref(get_main_ref_store(the_repository),
     ++				dst.buf, &oid))
     ++		*existing_ref_out = strbuf_detach(&dst, NULL);
      +
      +	strbuf_release(&dst);
     -+	*remote_out = remote_name;
     ++	strbuf_release(&head_path);
      +	return 0;
      +}
      +
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +
      +test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
      +	git checkout main &&
     -+	git -C fetch_upstream checkout -b fetch_refspec &&
     -+	test_commit -C fetch_upstream u_refspec &&
     -+	git fetch fetch_upstream fetch_refspec &&
      +	git remote add fetch_custom ./fetch_upstream &&
      +	test_when_finished "git remote remove fetch_custom" &&
      +	git config --replace-all remote.fetch_custom.fetch \
      +		"+refs/heads/*:refs/remotes/custom-ns/*" &&
     -+	git fetch fetch_custom &&
     -+	test_commit -C fetch_upstream u_refspec_post &&
     ++	git -C fetch_upstream checkout -b fetch_refspec &&
     ++	test_commit -C fetch_upstream u_refspec &&
     ++	test_must_fail git rev-parse --verify refs/remotes/custom-ns/fetch_refspec &&
      +	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
      +	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
      +'
      +
     ++test_expect_success 'checkout --track=fetch on namespace bare name follows <ns>/HEAD' '
     ++	git checkout main &&
     ++	git remote add fetch_ns ./fetch_upstream &&
     ++	test_when_finished "git remote remove fetch_ns" &&
     ++	git config --replace-all remote.fetch_ns.fetch \
     ++		"+refs/heads/*:refs/remotes/ns_alias/*" &&
     ++	git fetch fetch_ns &&
     ++	git symbolic-ref refs/remotes/ns_alias/HEAD refs/remotes/ns_alias/main &&
     ++	git -C fetch_upstream checkout main &&
     ++	test_commit -C fetch_upstream u_ns_post &&
     ++	git checkout --track=fetch -b local_ns ns_alias &&
     ++	test_cmp_rev refs/remotes/ns_alias/main HEAD &&
     ++	test_cmp_config fetch_ns branch.local_ns.remote &&
     ++	test_cmp_config refs/heads/main branch.local_ns.merge
     ++'
     ++
      +test_expect_success 'checkout --track=fetch handles hierarchical remote name' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_hier &&
 Documentation/git-checkout.adoc |  13 ++-
 Documentation/git-switch.adoc   |  13 ++-
 builtin/checkout.c              | 164 +++++++++++++++++++++++++++++++-
 t/t7201-co.sh                   | 158 ++++++++++++++++++++++++++++++
 4 files changed, 342 insertions(+), 6 deletions(-)
Show changes to 4 files +342 −6

Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh

diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index a8b3b8c2e2..ec63434159 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -158,11 +158,22 @@ of it").
 	resets _<branch>_ to the start point instead of failing.
 
 `-t`::
-`--track[=(direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration. See
 	`--track` in linkgit:git-branch[1] for details. As a convenience,
 	--track without -b implies branch creation.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
+only the remote's default branch is updated. If the fetch fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the checkout proceeds from the existing tip; otherwise the checkout
+is aborted.
++
 If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index d6c4f229a5..b5e79435cd 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -155,11 +155,22 @@ variable.
 	attached to a terminal, regardless of `--quiet`.
 
 `-t`::
-`--track[ (direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration.
 	`-c` is implied. See `--track` in linkgit:git-branch[1] for
 	details.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
+only the remote's default branch is updated. If the fetch fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the switch proceeds from the existing tip; otherwise the switch is
+aborted.
++
 If no `-c` option is given, the name of the new branch will be derived
 from the remote-tracking branch, by looking at the local part of the
 refspec configured for the corresponding remote, and then stripping
diff --git a/builtin/checkout.c b/builtin/checkout.c
index 1345e8574a..5b3a06c0cd 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -25,10 +25,12 @@
 #include "preload-index.h"
 #include "read-cache.h"
 #include "refs.h"
+#include "refspec.h"
 #include "remote.h"
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "sequencer.h"
 #include "setup.h"
 #include "strvec.h"
@@ -62,6 +64,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -115,6 +118,154 @@ struct branch_info {
 	char *checkout;
 };
 
+struct fetch_target_cb {
+	struct refspec_item query;
+	const char *remote_name;
+	int matches;
+};
+
+static int match_fetch_target(struct remote *remote, void *priv)
+{
+	struct fetch_target_cb *cb = priv;
+	struct refspec_item q = { .dst = cb->query.dst };
+
+	if (!remote_find_tracking(remote, &q) && q.src) {
+		if (++cb->matches == 1) {
+			cb->remote_name = remote->name;
+			free(cb->query.src);
+			cb->query.src = q.src;
+		} else {
+			free(q.src);
+		}
+	}
+	return 0;
+}
+
+static int resolve_fetch_target(const char *arg, char **remote_out,
+				char **src_ref_out, char **existing_ref_out)
+{
+	struct strbuf dst = STRBUF_INIT;
+	struct strbuf head_path = STRBUF_INIT;
+	struct fetch_target_cb cb = { 0 };
+	struct object_id oid;
+	const char *head_target;
+
+	*remote_out = NULL;
+	*src_ref_out = NULL;
+	*existing_ref_out = NULL;
+
+	if (!arg || !*arg)
+		return -1;
+
+	strbuf_addf(&head_path, "refs/remotes/%s/HEAD", arg);
+	head_target = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
+					      head_path.buf,
+					      RESOLVE_REF_READING |
+					      RESOLVE_REF_NO_RECURSE,
+					      &oid, NULL);
+	if (head_target)
+		strbuf_addstr(&dst, head_target);
+	else
+		strbuf_addf(&dst, "refs/remotes/%s", arg);
+
+	cb.query.dst = dst.buf;
+	for_each_remote(match_fetch_target, &cb);
+
+	if (cb.matches != 1) {
+		free(cb.query.src);
+		strbuf_release(&dst);
+		strbuf_release(&head_path);
+		return -1;
+	}
+
+	*remote_out = xstrdup(cb.remote_name);
+	*src_ref_out = cb.query.src;
+	if (head_target)
+		*existing_ref_out = strbuf_detach(&head_path, NULL);
+	else if (!refs_read_ref(get_main_ref_store(the_repository),
+				dst.buf, &oid))
+		*existing_ref_out = strbuf_detach(&dst, NULL);
+
+	strbuf_release(&dst);
+	strbuf_release(&head_path);
+	return 0;
+}
+
+static void fetch_remote_for_start_point(const char *arg)
+{
+	char *remote_name = NULL;
+	char *src_ref = NULL;
+	char *existing_ref = NULL;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+
+	if (resolve_fetch_target(arg, &remote_name, &src_ref, &existing_ref))
+		return;
+
+	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
+	if (src_ref)
+		strvec_push(&cmd.args, src_ref);
+	cmd.git_cmd = 1;
+	if (run_command(&cmd)) {
+		if (existing_ref)
+			warning(_("failed to fetch start-point '%s'; "
+				  "using existing '%s'"),
+				arg, existing_ref);
+		else
+			die(_("failed to fetch start-point '%s'"), arg);
+	}
+
+	free(remote_name);
+	free(src_ref);
+	free(existing_ref);
+}
+
+static int parse_opt_checkout_track(const struct option *opt,
+				    const char *arg, int unset)
+{
+	struct checkout_opts *opts = opt->value;
+	struct string_list tokens = STRING_LIST_INIT_DUP;
+	struct string_list_item *item;
+	int saw_direct = 0, saw_inherit = 0;
+	int ret = 0;
+
+	opts->fetch = 0;
+
+	if (unset) {
+		opts->track = BRANCH_TRACK_NEVER;
+		return 0;
+	}
+
+	opts->track = BRANCH_TRACK_EXPLICIT;
+	if (!arg)
+		return 0;
+
+	string_list_split(&tokens, arg, ",", -1);
+	for_each_string_list_item(item, &tokens) {
+		if (!strcmp(item->string, "fetch")) {
+			opts->fetch = 1;
+		} else if (!strcmp(item->string, "direct")) {
+			saw_direct = 1;
+			opts->track = BRANCH_TRACK_EXPLICIT;
+		} else if (!strcmp(item->string, "inherit")) {
+			saw_inherit = 1;
+			opts->track = BRANCH_TRACK_INHERIT;
+		} else {
+			ret = error(_("option `%s' expects \"%s\", \"%s\", "
+				      "or \"%s\""),
+				    "--track", "direct", "inherit", "fetch");
+			goto out;
+		}
+	}
+
+	if (saw_direct && saw_inherit)
+		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
+			    "--track", "direct", "inherit");
+
+out:
+	string_list_clear(&tokens, 0);
+	return ret;
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1733,10 +1884,10 @@ static struct option *add_common_switch_branch_options(
 {
 	struct option options[] = {
 		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
-		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
+		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
 			N_("set branch tracking configuration"),
 			PARSE_OPT_OPTARG,
-			parse_opt_tracking_mode),
+			parse_opt_checkout_track),
 		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
@@ -1941,8 +2092,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0]);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 7613b1d2a4..d4f5467903 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -870,4 +870,162 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --track=fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
+	test_cmp_config fetch_upstream branch.local_new.remote &&
+	test_cmp_config refs/heads/fetch_new branch.local_new.merge
+'
+
+test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
+'
+
+test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
+	git checkout main &&
+	git -C fetch_upstream checkout main &&
+	git remote set-head fetch_upstream main &&
+	git -C fetch_upstream checkout -b fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_pre &&
+	git fetch fetch_upstream fetch_unrelated &&
+	unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_main_post &&
+	git -C fetch_upstream checkout fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_post &&
+	git checkout --track=fetch -b local_from_remote fetch_upstream &&
+	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
+'
+
+test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_offline &&
+	test_commit -C fetch_upstream u_offline &&
+	git fetch fetch_upstream fetch_offline &&
+	saved_url=$(git config remote.fetch_upstream.url) &&
+	test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
+	git config remote.fetch_upstream.url ./does-not-exist &&
+	git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
+	test_grep "failed to fetch" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
+'
+
+test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
+	git checkout main &&
+	git remote add fetch_custom ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_custom" &&
+	git config --replace-all remote.fetch_custom.fetch \
+		"+refs/heads/*:refs/remotes/custom-ns/*" &&
+	git -C fetch_upstream checkout -b fetch_refspec &&
+	test_commit -C fetch_upstream u_refspec &&
+	test_must_fail git rev-parse --verify refs/remotes/custom-ns/fetch_refspec &&
+	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
+	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
+'
+
+test_expect_success 'checkout --track=fetch on namespace bare name follows <ns>/HEAD' '
+	git checkout main &&
+	git remote add fetch_ns ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_ns" &&
+	git config --replace-all remote.fetch_ns.fetch \
+		"+refs/heads/*:refs/remotes/ns_alias/*" &&
+	git fetch fetch_ns &&
+	git symbolic-ref refs/remotes/ns_alias/HEAD refs/remotes/ns_alias/main &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_ns_post &&
+	git checkout --track=fetch -b local_ns ns_alias &&
+	test_cmp_rev refs/remotes/ns_alias/main HEAD &&
+	test_cmp_config fetch_ns branch.local_ns.remote &&
+	test_cmp_config refs/heads/main branch.local_ns.merge
+'
+
+test_expect_success 'checkout --track=fetch handles hierarchical remote name' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_hier &&
+	test_commit -C fetch_upstream u_hier &&
+	git remote add nested/remote ./fetch_upstream &&
+	test_when_finished "git remote remove nested/remote" &&
+	git fetch nested/remote fetch_hier &&
+	test_commit -C fetch_upstream u_hier_post &&
+	git checkout --track=fetch -b local_hier nested/remote/fetch_hier &&
+	test_cmp_rev refs/remotes/nested/remote/fetch_hier HEAD
+'
+
+test_expect_success 'checkout --track=inherit,direct is rejected' '
+	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
+	test_grep "cannot combine" err
+'
+
+test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_lastwin &&
+	test_commit -C fetch_upstream u_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
+	test_must_fail git checkout --track=fetch --track=direct \
+		-b local_lastwin fetch_upstream/fetch_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
+'
+
+test_expect_success 'checkout --track=fetch,inherit fetches and inherits' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit &&
+	git fetch fetch_upstream fetch_inherit &&
+	git checkout -b base_inherit fetch_upstream/fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit2 &&
+	git checkout main &&
+	git checkout --track=fetch,inherit -b local_inherit base_inherit &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD &&
+	test_cmp_config fetch_upstream branch.local_inherit.remote &&
+	test_cmp_config refs/heads/fetch_inherit branch.local_inherit.merge
+'
+
+test_expect_success 'checkout --track=bogus reports an error' '
+	git checkout main &&
+	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
+	test_grep "expects" err
+'
+
+test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done

base-commit: 7bcaabddcf68bd0702697da5904c3b68c52f94cf
-- 
gitgitgadget
Junio C HamanoMay 19, 2026, 08:16 UTC in reply to Harald Nordgren on lore

Re: [PATCH v10] checkout: extend --track with a "fetch" mode to refresh start-point

Harald Nordgren <haraldnordgren@gmail.com> writes:
> Yeah, good point. I will try to address this and send a new patch.
Please don't.

Next time, think deeply yourself and do not rob my time to think these things for you. I do not have infinite amount of time. A good balance may be if I find one issue in your current code, it is likely that you'd better three more issues and fix them before sending the next round, or something like that.

Thanks.
Harald NordgrenMay 19, 2026, 08:32 UTC in reply to Junio C Hamano on lore

Re: [PATCH v10] checkout: extend --track with a "fetch" mode to refresh start-point

Show 11 quoted lines
> > Yeah, good point. I will try to address this and send a new patch.
>
> Please don't.
>
> Next time, think deeply yourself and do not rob my time to think
> these things for you.  I do not have infinite amount of time.  A
> good balance may be if I find one issue in your current code, it is
> likely that you'd better three more issues and fix them before
> sending the next round, or something like that.
>
> Thanks.
I already sent the patch. Sorry about that!
Harald
Harald NordgrenMay 19, 2026, 08:38 UTC in reply to Harald Nordgren on lore

Re: [PATCH v10] checkout: extend --track with a "fetch" mode to refresh start-point

Show 13 quoted lines
> > > Yeah, good point. I will try to address this and send a new patch.
> >
> > Please don't.
> >
> > Next time, think deeply yourself and do not rob my time to think
> > these things for you.  I do not have infinite amount of time.  A
> > good balance may be if I find one issue in your current code, it is
> > likely that you'd better three more issues and fix them before
> > sending the next round, or something like that.
> >
> > Thanks.
>
> I already sent the patch. Sorry about that!

I didn't realize how much time this took away from you. My motivation was always to put the topic into a better position ASAP, to avoid anyone else reviewing an old version.

But I do know that it lands in your inbox each time there is a new patch. So I will try to cut down on the amount of patches from now one, since they are not free in terms of yours and other time. Sounds ok?

Harald
Junio C HamanoMay 19, 2026, 10:34 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH v11] checkout: extend --track with a "fetch" mode to refresh start-point

"Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
Show 7 quoted lines
>     checkout: --track=fetch
>     
>      * Find the right remote by checking which remote's fetch refspec maps
>        to the user's start-point, instead of assuming the start-point begins
>        with the remote's name. This fixes cases where the user has a custom
>        refspec mapping into a namespace whose name differs from the remote
>        (e.g. fetching from origin into refs/remotes/upstream/*).

This comment is even before looking at the patch text. After getting one issue pointed out, I'd expect you to think about related issues before sending a new round out.

One. Have you considered the case where the remote-tracking refs are overlapping, e.g., where "origin" and "upstream" point at different URLs but they both store in "refs/remotes/upstream/*"? Perhaps their URLs may textually be different but are pointing logically at the same place (e.g., one ssh:// the other https:// for example).

What should happen?  What does happen after you apply this patch?
>      * For a bare namespace name, follow <namespace>/HEAD first to figure
>        out which branch to fetch.

What should happen if HEAD does not exist? What does happen after you apply this patch?

Thanks.
Phillip WoodMay 21, 2026, 09:49 UTC in reply to Junio C Hamano on lore

Re: [PATCH v11] checkout: extend --track with a "fetch" mode to refresh start-point

On 19/05/2026 11:34, Junio C Hamano wrote:
Show 22 quoted lines
> "Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
> 
>>      checkout: --track=fetch
>>      
>>       * Find the right remote by checking which remote's fetch refspec maps
>>         to the user's start-point, instead of assuming the start-point begins
>>         with the remote's name. This fixes cases where the user has a custom
>>         refspec mapping into a namespace whose name differs from the remote
>>         (e.g. fetching from origin into refs/remotes/upstream/*).
> 
> This comment is even before looking at the patch text.  After
> getting one issue pointed out, I'd expect you to think about related
> issues before sending a new round out.
> 
> One.  Have you considered the case where the remote-tracking refs
> are overlapping, e.g., where "origin" and "upstream" point at
> different URLs but they both store in "refs/remotes/upstream/*"?
> Perhaps their URLs may textually be different but are pointing
> logically at the same place (e.g., one ssh:// the other https:// for
> example).
> 
> What should happen?  What does happen after you apply this patch?

It would be worth looking at what "git checkout --track" does in that case and seeing if we can share the code.

Thanks
Phillip
Show 9 quoted lines
> 
>>       * For a bare namespace name, follow <namespace>/HEAD first to figure
>>         out which branch to fetch.
> 
> What should happen if HEAD does not exist?  What does happen after
> you apply this patch?
> 
> Thanks.
> 
Harald Nordgren via GitGitGadgetMay 21, 2026, 10:20 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v12] checkout: extend --track with a "fetch" mode to refresh start-point

From: Harald Nordgren <haraldnordgren@gmail.com>

Add a "fetch" mode to the "--track" option of "git checkout" / "git switch" that refreshes <start-point> before checking it out:

    git checkout -b new_branch --track=fetch origin/some-branch
is shorthand for
    git fetch origin some-branch
    git checkout -b new_branch --track origin/some-branch

Identify the remote whose configured fetch refspec maps to <start-point>, then run "git fetch <remote> <src-ref>" for just that ref so other remote-tracking branches are left untouched. When <start-point> is a bare <remote> (e.g. "origin"), follow refs/remotes/<remote>/HEAD to learn which branch to refresh. If "git fetch" fails but the remote-tracking ref already exists locally, warn and proceed from the existing tip; otherwise abort.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
    checkout: --track=fetch
    
     * Find the right remote by matching fetch refspecs. Instead of assuming
       the start-point begins with a remote's name, ask each configured
       remote whether its fetch refspec maps to refs/remotes/<start-point>.
     * Die clearly when no remote matches. Previously, if we couldn't figure
       out the remote we'd silently skip the fetch and fall through to a
       confusing later error.
     * Die clearly when more than one remote matches. If two remotes both
       map their fetches into the same refs/remotes/<ns>/* namespace, there
       is no unambiguous choice.
     * Bare-namespace form (--track=fetch origin) requires <ns>/HEAD. When
       the user passes just a namespace, we now follow
       refs/remotes/<ns>/HEAD to learn which branch to refresh. If that
       symref is missing, die with a hint to run git remote set-head <ns>
       --auto instead of guessing or fetching everything. If <ns>/HEAD
       points outside the namespace, reject it.
     * Validate the refname before doing anything. Reject obviously invalid
       start-points like foo..bar up front, so we don't run a fetch we know
       cannot succeed.
     * Forward --quiet to the underlying fetch. checkout -q --track=fetch
       ... now suppresses the fetch progress output, matching the user's
       intent.
     * More tests coverage.
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v12
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v12
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v11:
 1:  d0c9e3e879 ! 1:  bcd034dbed checkout: extend --track with a "fetch" mode to refresh start-point
     @@ Metadata
       ## Commit message ##
          checkout: extend --track with a "fetch" mode to refresh start-point
      
     -    If you want to fork your topic branch from the very latest of the
     -    tip of a branch your remote has, you would do:
     -
     -        git fetch origin some-branch
     -        git checkout -b new_branch --track origin/some-branch
     -
     -    Extend the "--track" option of "git checkout" and allow users to
     -    write
     +    Add a "fetch" mode to the "--track" option of "git checkout" / "git
     +    switch" that refreshes <start-point> before checking it out:
      
              git checkout -b new_branch --track=fetch origin/some-branch
      
     -    to (1) fetch 'some-branch' from the remote 'origin', updating the
     -    remote-tracking branch 'origin/some-branch', (2) arrange subsequent
     -    'git pull' on 'new_branch' to interact with 'origin/some-branch' and
     -    (3) fork 'new_branch' from it.
     -
     -    In the value of the '--track' option, 'fetch' can be combined with
     -    the existing 'direct' (default) and 'inherit' modes via a
     -    comma-separated list. Examples:
     +    is shorthand for
      
     -        git checkout -b new_branch --track=fetch,inherit some_local_branch
     -        git switch -c new_branch --track=fetch origin/some-branch
     +        git fetch origin some-branch
     +        git checkout -b new_branch --track origin/some-branch
      
     -    When "fetch" is requested and <start-point> is in <remote>/<branch>
     -    form, run "git fetch <remote> <branch>" before resolving the ref, so
     -    that other remote-tracking branches are left untouched. If
     -    <start-point> is a bare remote name like "origin" (which resolves to
     -    that remote's default branch), "git fetch <remote>" is run instead,
     -    since the target branch is not known up front. Abort the checkout if
     -    the fetch fails.
     +    Identify the remote whose configured fetch refspec maps to
     +    <start-point>, then run "git fetch <remote> <src-ref>" for just that
     +    ref so other remote-tracking branches are left untouched. When
     +    <start-point> is a bare <remote> (e.g. "origin"), follow
     +    refs/remotes/<remote>/HEAD to learn which branch to refresh. If
     +    "git fetch" fails but the remote-tracking ref already exists locally,
     +    warn and proceed from the existing tip; otherwise abort.
      
          Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
      
     @@ Documentation/git-checkout.adoc: of it").
      +`fetch` requests that the remote be fetched before _<start-point>_ is
      +resolved, so the new branch starts from a fresh tip: when
      +_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
     -+updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
     -+only the remote's default branch is updated. If the fetch fails and the
     ++updated; when _<start-point>_ is a bare _<remote>_ (e.g. `origin`), the
     ++branch named by _<remote>/HEAD_ is updated, and the checkout fails
     ++with a hint to configure that symref if it is not set. The checkout
     ++also fails if no configured remote's fetch refspec maps to
     ++_<start-point>_, or if more than one does (in which case the `fetch`
     ++cannot be unambiguously routed). If the fetch itself fails and the
      +corresponding remote-tracking ref already exists, a warning is printed
      +and the checkout proceeds from the existing tip; otherwise the checkout
      +is aborted.
     @@ Documentation/git-switch.adoc: variable.
      +`--track[=(direct|inherit|fetch)[,...]]`::
       	When creating a new branch, set up "upstream" configuration.
       	`-c` is implied. See `--track` in linkgit:git-branch[1] for
     - 	details.
     +-	details.
     ++	details, and `--track` in linkgit:git-checkout[1] for the
     ++	`fetch` mode.
       +
     -+The argument is a comma-separated list. `direct` (the default) and
     -+`inherit` select the tracking mode and are mutually exclusive. Adding
     -+`fetch` requests that the remote be fetched before _<start-point>_ is
     -+resolved, so the new branch starts from a fresh tip: when
     -+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
     -+updated; when _<start-point>_ is a bare remote name (e.g. `origin`),
     -+only the remote's default branch is updated. If the fetch fails and the
     -+corresponding remote-tracking ref already exists, a warning is printed
     -+and the switch proceeds from the existing tip; otherwise the switch is
     -+aborted.
     -++
       If no `-c` option is given, the name of the new branch will be derived
       from the remote-tracking branch, by looking at the local part of the
     - refspec configured for the corresponding remote, and then stripping
      
       ## builtin/checkout.c ##
      @@
     @@ builtin/checkout.c: struct branch_info {
       };
       
      +struct fetch_target_cb {
     -+	struct refspec_item query;
     -+	const char *remote_name;
     -+	int matches;
     ++	char *dst;
     ++	struct string_list matches;
      +};
      +
      +static int match_fetch_target(struct remote *remote, void *priv)
      +{
      +	struct fetch_target_cb *cb = priv;
     -+	struct refspec_item q = { .dst = cb->query.dst };
     -+
     -+	if (!remote_find_tracking(remote, &q) && q.src) {
     -+		if (++cb->matches == 1) {
     -+			cb->remote_name = remote->name;
     -+			free(cb->query.src);
     -+			cb->query.src = q.src;
     -+		} else {
     -+			free(q.src);
     -+		}
     -+	}
     ++	struct refspec_item q = { .dst = cb->dst };
     ++
     ++	if (!remote_find_tracking(remote, &q) && q.src)
     ++		string_list_append(&cb->matches, remote->name)->util = q.src;
      +	return 0;
      +}
      +
     -+static int resolve_fetch_target(const char *arg, char **remote_out,
     -+				char **src_ref_out, char **existing_ref_out)
     ++static void fetch_remote_for_start_point(const char *arg, int quiet)
      +{
      +	struct strbuf dst = STRBUF_INIT;
     -+	struct strbuf head_path = STRBUF_INIT;
     -+	struct fetch_target_cb cb = { 0 };
     ++	struct fetch_target_cb cb = { .matches = STRING_LIST_INIT_NODUP };
     ++	struct child_process cmd = CHILD_PROCESS_INIT;
      +	struct object_id oid;
     -+	const char *head_target;
     -+
     -+	*remote_out = NULL;
     -+	*src_ref_out = NULL;
     -+	*existing_ref_out = NULL;
     -+
     -+	if (!arg || !*arg)
     -+		return -1;
     -+
     -+	strbuf_addf(&head_path, "refs/remotes/%s/HEAD", arg);
     -+	head_target = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
     -+					      head_path.buf,
     -+					      RESOLVE_REF_READING |
     -+					      RESOLVE_REF_NO_RECURSE,
     -+					      &oid, NULL);
     -+	if (head_target)
     -+		strbuf_addstr(&dst, head_target);
     -+	else
     -+		strbuf_addf(&dst, "refs/remotes/%s", arg);
     -+
     -+	cb.query.dst = dst.buf;
     -+	for_each_remote(match_fetch_target, &cb);
     -+
     -+	if (cb.matches != 1) {
     -+		free(cb.query.src);
     -+		strbuf_release(&dst);
     -+		strbuf_release(&head_path);
     -+		return -1;
     ++	struct remote *named_remote;
     ++	int bare_ns;
     ++	size_t i;
     ++
     ++	strbuf_addf(&dst, "refs/remotes/%s", arg);
     ++	if (check_refname_format(dst.buf, 0))
     ++		die(_("cannot fetch start-point '%s': not a valid "
     ++		      "remote-tracking name"), arg);
     ++
     ++	named_remote = remote_get(arg);
     ++	bare_ns = !strchr(arg, '/') ||
     ++		(named_remote && remote_is_configured(named_remote, 1));
     ++	if (bare_ns) {
     ++		char *head_path = xstrfmt("refs/remotes/%s/HEAD", arg);
     ++		const char *head_target =
     ++			refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
     ++						head_path,
     ++						RESOLVE_REF_READING |
     ++						RESOLVE_REF_NO_RECURSE,
     ++						&oid, NULL);
     ++		if (head_target &&
     ++		    starts_with(head_target, dst.buf) &&
     ++		    head_target[dst.len] == '/' &&
     ++		    !check_refname_format(head_target, 0)) {
     ++			strbuf_reset(&dst);
     ++			strbuf_addstr(&dst, head_target);
     ++			bare_ns = 0;
     ++		}
     ++		free(head_path);
      +	}
      +
     -+	*remote_out = xstrdup(cb.remote_name);
     -+	*src_ref_out = cb.query.src;
     -+	if (head_target)
     -+		*existing_ref_out = strbuf_detach(&head_path, NULL);
     -+	else if (!refs_read_ref(get_main_ref_store(the_repository),
     -+				dst.buf, &oid))
     -+		*existing_ref_out = strbuf_detach(&dst, NULL);
     -+
     -+	strbuf_release(&dst);
     -+	strbuf_release(&head_path);
     -+	return 0;
     -+}
     ++	cb.dst = dst.buf;
     ++	for_each_remote(match_fetch_target, &cb);
      +
     -+static void fetch_remote_for_start_point(const char *arg)
     -+{
     -+	char *remote_name = NULL;
     -+	char *src_ref = NULL;
     -+	char *existing_ref = NULL;
     -+	struct child_process cmd = CHILD_PROCESS_INIT;
     ++	if (cb.matches.nr > 1) {
     ++		struct strbuf msg = STRBUF_INIT;
     ++
     ++		strbuf_addf(&msg,
     ++			    _("cannot fetch start-point '%s': fetch refspecs "
     ++			      "of multiple remotes map to the same destination:"),
     ++			    arg);
     ++		for (i = 0; i < cb.matches.nr; i++)
     ++			strbuf_addf(&msg, "\n  %s", cb.matches.items[i].string);
     ++		strbuf_addstr(&msg,
     ++			      _("\nadjust 'remote.<name>.fetch' so only one "
     ++				"remote maps there, or omit '=fetch'"));
     ++		die("%s", msg.buf);
     ++	}
      +
     -+	if (resolve_fetch_target(arg, &remote_name, &src_ref, &existing_ref))
     -+		return;
     ++	if (!cb.matches.nr) {
     ++		if (bare_ns && named_remote &&
     ++		    remote_is_configured(named_remote, 1))
     ++			die(_("cannot fetch start-point '%s': "
     ++			      "'refs/remotes/%s/HEAD' is not set; run "
     ++			      "'git remote set-head %s --auto' to set it"),
     ++			    arg, arg, arg);
     ++		die(_("cannot fetch start-point '%s': no configured remote's "
     ++		      "fetch refspec matches it"), arg);
     ++	}
      +
     -+	strvec_pushl(&cmd.args, "fetch", remote_name, NULL);
     -+	if (src_ref)
     -+		strvec_push(&cmd.args, src_ref);
     ++	strvec_push(&cmd.args, "fetch");
     ++	if (quiet)
     ++		strvec_push(&cmd.args, "--quiet");
     ++	strvec_pushl(&cmd.args, cb.matches.items[0].string,
     ++		     (char *)cb.matches.items[0].util, NULL);
      +	cmd.git_cmd = 1;
      +	if (run_command(&cmd)) {
     -+		if (existing_ref)
     ++		if (!refs_read_ref(get_main_ref_store(the_repository),
     ++				   dst.buf, &oid))
      +			warning(_("failed to fetch start-point '%s'; "
     -+				  "using existing '%s'"),
     -+				arg, existing_ref);
     ++				  "using existing '%s'"), arg, dst.buf);
      +		else
      +			die(_("failed to fetch start-point '%s'"), arg);
      +	}
      +
     -+	free(remote_name);
     -+	free(src_ref);
     -+	free(existing_ref);
     ++	for (i = 0; i < cb.matches.nr; i++)
     ++		free(cb.matches.items[i].util);
     ++	string_list_clear(&cb.matches, 0);
     ++	strbuf_release(&dst);
      +}
      +
      +static int parse_opt_checkout_track(const struct option *opt,
     @@ builtin/checkout.c: struct branch_info {
      +	struct checkout_opts *opts = opt->value;
      +	struct string_list tokens = STRING_LIST_INIT_DUP;
      +	struct string_list_item *item;
     -+	int saw_direct = 0, saw_inherit = 0;
     ++	int saw_direct = 0;
      +	int ret = 0;
      +
      +	opts->fetch = 0;
     -+
      +	if (unset) {
      +		opts->track = BRANCH_TRACK_NEVER;
      +		return 0;
      +	}
     -+
      +	opts->track = BRANCH_TRACK_EXPLICIT;
      +	if (!arg)
      +		return 0;
      +
      +	string_list_split(&tokens, arg, ",", -1);
      +	for_each_string_list_item(item, &tokens) {
     -+		if (!strcmp(item->string, "fetch")) {
     ++		if (!strcmp(item->string, "fetch"))
      +			opts->fetch = 1;
     -+		} else if (!strcmp(item->string, "direct")) {
     ++		else if (!strcmp(item->string, "direct"))
      +			saw_direct = 1;
     -+			opts->track = BRANCH_TRACK_EXPLICIT;
     -+		} else if (!strcmp(item->string, "inherit")) {
     -+			saw_inherit = 1;
     ++		else if (!strcmp(item->string, "inherit"))
      +			opts->track = BRANCH_TRACK_INHERIT;
     -+		} else {
     ++		else {
      +			ret = error(_("option `%s' expects \"%s\", \"%s\", "
      +				      "or \"%s\""),
      +				    "--track", "direct", "inherit", "fetch");
      +			goto out;
      +		}
      +	}
     -+
     -+	if (saw_direct && saw_inherit)
     ++	if (saw_direct && opts->track == BRANCH_TRACK_INHERIT)
      +		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
      +			    "--track", "direct", "inherit");
     -+
      +out:
      +	string_list_clear(&tokens, 0);
      +	return ret;
     @@ builtin/checkout.c: static int checkout_main(int argc, const char **argv, const
      +		int n;
      +
      +		if (opts->fetch)
     -+			fetch_remote_for_start_point(argv[0]);
     ++			fetch_remote_for_start_point(argv[0], opts->quiet);
      +
      +		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
      +					 &new_branch_info, opts, &rev);
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	git checkout main &&
      +	git remote add fetch_ns ./fetch_upstream &&
      +	test_when_finished "git remote remove fetch_ns" &&
     ++	test_when_finished "git update-ref -d refs/remotes/ns_alias/HEAD" &&
      +	git config --replace-all remote.fetch_ns.fetch \
      +		"+refs/heads/*:refs/remotes/ns_alias/*" &&
      +	git fetch fetch_ns &&
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_cmp_config refs/heads/main branch.local_ns.merge
      +'
      +
     ++test_expect_success '--track=fetch on bare hierarchical remote name follows <ns>/HEAD' '
     ++	git checkout main &&
     ++	git remote add nested/bare ./fetch_upstream &&
     ++	test_when_finished "git remote remove nested/bare" &&
     ++	test_when_finished "git update-ref -d refs/remotes/nested/bare/HEAD" &&
     ++	git fetch nested/bare &&
     ++	git symbolic-ref refs/remotes/nested/bare/HEAD \
     ++		refs/remotes/nested/bare/main &&
     ++	git -C fetch_upstream checkout main &&
     ++	test_commit -C fetch_upstream u_nested_bare_post &&
     ++	git checkout --track=fetch -b local_nested_bare nested/bare &&
     ++	test_cmp_rev refs/remotes/nested/bare/main HEAD
     ++'
     ++
      +test_expect_success 'checkout --track=fetch handles hierarchical remote name' '
      +	git checkout main &&
     -+	git -C fetch_upstream checkout -b fetch_hier &&
     -+	test_commit -C fetch_upstream u_hier &&
      +	git remote add nested/remote ./fetch_upstream &&
      +	test_when_finished "git remote remove nested/remote" &&
     -+	git fetch nested/remote fetch_hier &&
     -+	test_commit -C fetch_upstream u_hier_post &&
     ++	git -C fetch_upstream checkout -b fetch_hier &&
     ++	test_commit -C fetch_upstream u_hier &&
     ++	test_must_fail git rev-parse --verify refs/remotes/nested/remote/fetch_hier &&
      +	git checkout --track=fetch -b local_hier nested/remote/fetch_hier &&
      +	test_cmp_rev refs/remotes/nested/remote/fetch_hier HEAD
      +'
      +
     ++test_expect_success 'checkout --track=fetch dies on bare remote name with no <ns>/HEAD' '
     ++	git checkout main &&
     ++	git remote add fetch_nohead ./fetch_upstream &&
     ++	test_when_finished "git remote remove fetch_nohead" &&
     ++	test_might_fail git symbolic-ref -d refs/remotes/fetch_nohead/HEAD &&
     ++	test_must_fail git checkout --track=fetch -b local_nohead fetch_nohead 2>err &&
     ++	test_grep "refs/remotes/fetch_nohead/HEAD" err &&
     ++	test_grep "git remote set-head fetch_nohead --auto" err &&
     ++	test_must_fail git rev-parse --verify refs/heads/local_nohead
     ++'
     ++
     ++test_expect_success 'checkout --track=fetch on bare unknown name does not suggest set-head' '
     ++	git checkout main &&
     ++	test_must_fail git rev-parse --verify refs/remotes/no_such_ns/HEAD &&
     ++	test_must_fail git config --get remote.no_such_ns.url &&
     ++	test_must_fail git checkout --track=fetch -b local_unknown no_such_ns 2>err &&
     ++	test_grep "no configured remote" err &&
     ++	test_grep ! "set-head" err &&
     ++	test_must_fail git rev-parse --verify refs/heads/local_unknown
     ++'
     ++
     ++test_expect_success 'checkout --track=fetch rejects <ns>/HEAD pointing outside namespace' '
     ++	git checkout main &&
     ++	git remote add fetch_crossns ./fetch_upstream &&
     ++	test_when_finished "git remote remove fetch_crossns" &&
     ++	test_when_finished "git update-ref -d refs/remotes/fetch_crossns/HEAD" &&
     ++	git fetch fetch_crossns &&
     ++	git symbolic-ref refs/remotes/fetch_crossns/HEAD \
     ++		refs/remotes/fetch_upstream/u_main &&
     ++	test_must_fail git checkout --track=fetch -b local_crossns fetch_crossns 2>err &&
     ++	test_grep "refs/remotes/fetch_crossns/HEAD" err &&
     ++	test_must_fail git rev-parse --verify refs/heads/local_crossns
     ++'
     ++
     ++test_expect_success 'checkout --track=fetch dies on ambiguous fetch refspec match' '
     ++	git checkout main &&
     ++	git remote add fetch_ambig_a ./fetch_upstream &&
     ++	git remote add fetch_ambig_b ./fetch_upstream &&
     ++	test_when_finished "git remote remove fetch_ambig_a" &&
     ++	test_when_finished "git remote remove fetch_ambig_b" &&
     ++	git config --replace-all remote.fetch_ambig_a.fetch \
     ++		"+refs/heads/*:refs/remotes/ambig_ns/*" &&
     ++	git config --replace-all remote.fetch_ambig_b.fetch \
     ++		"+refs/heads/*:refs/remotes/ambig_ns/*" &&
     ++	git -C fetch_upstream checkout -b fetch_ambig &&
     ++	test_commit -C fetch_upstream u_ambig &&
     ++	test_must_fail git checkout --track=fetch -b local_ambig ambig_ns/fetch_ambig 2>err &&
     ++	test_grep "fetch_ambig_a" err &&
     ++	test_grep "fetch_ambig_b" err &&
     ++	test_grep "remote.<name>.fetch" err &&
     ++	test_must_fail git rev-parse --verify refs/heads/local_ambig
     ++'
     ++
     ++test_expect_success 'checkout --track=fetch rejects invalid refname components' '
     ++	git checkout main &&
     ++	test_must_fail git checkout --track=fetch -b local_invalid "foo..bar" 2>err &&
     ++	test_grep "valid" err &&
     ++	test_must_fail git rev-parse --verify refs/heads/local_invalid
     ++'
     ++
     ++test_expect_success 'checkout --track=fetch,inherit rejects invalid refname components' '
     ++	git checkout main &&
     ++	test_must_fail git checkout --track=fetch,inherit -b local_invalid \
     ++		"foo..bar" 2>err &&
     ++	test_grep "valid" err &&
     ++	test_must_fail git rev-parse --verify refs/heads/local_invalid
     ++'
     ++
      +test_expect_success 'checkout --track=inherit,direct is rejected' '
      +	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
      +	test_grep "cannot combine" err
      +'
      +
     ++test_expect_success 'checkout --track=direct,inherit is rejected' '
     ++	test_must_fail git checkout --track=direct,inherit -b bad fetch_upstream/fetch_new 2>err &&
     ++	test_grep "cannot combine" err
     ++'
     ++
      +test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_lastwin &&
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
      +'
      +
     -+test_expect_success 'checkout --track=fetch,inherit fetches and inherits' '
     ++test_expect_success 'checkout --track=fetch then --no-track drops fetch' '
     ++	git checkout main &&
     ++	git -C fetch_upstream checkout -b fetch_notrack &&
     ++	test_commit -C fetch_upstream u_notrack &&
     ++	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack &&
     ++	test_must_fail git checkout --track=fetch --no-track \
     ++		-b local_notrack fetch_upstream/fetch_notrack &&
     ++	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack
     ++'
     ++
     ++test_expect_success 'checkout --track=fetch,inherit fetches remote-tracking start-point' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_inherit &&
      +	test_commit -C fetch_upstream u_inherit &&
     -+	git fetch fetch_upstream fetch_inherit &&
     -+	git checkout -b base_inherit fetch_upstream/fetch_inherit &&
     -+	test_commit -C fetch_upstream u_inherit2 &&
     ++	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_inherit &&
     ++	git checkout --track=fetch,inherit -b local_inherit \
     ++		fetch_upstream/fetch_inherit &&
     ++	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD
     ++'
     ++
     ++test_expect_success 'checkout --track=fetch,inherit errors when start-point does not map to a remote' '
      +	git checkout main &&
     -+	git checkout --track=fetch,inherit -b local_inherit base_inherit &&
     -+	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD &&
     -+	test_cmp_config fetch_upstream branch.local_inherit.remote &&
     -+	test_cmp_config refs/heads/fetch_inherit branch.local_inherit.merge
     ++	test_must_fail git checkout --track=fetch,inherit -b bad main 2>err &&
     ++	test_grep "no configured remote" err &&
     ++	test_must_fail git rev-parse --verify refs/heads/bad
     ++'
     ++
     ++test_expect_success 'checkout --track=fetch on local start-point errors' '
     ++	git checkout main &&
     ++	test_must_fail git checkout --track=fetch -b bad main 2>err &&
     ++	test_grep "no configured remote" err &&
     ++	test_must_fail git rev-parse --verify refs/heads/bad
      +'
      +
      +test_expect_success 'checkout --track=bogus reports an error' '
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_grep "expects" err
      +'
      +
     ++test_expect_success 'checkout -q --track=fetch silences the fetch output' '
     ++	git checkout main &&
     ++	git -C fetch_upstream checkout -b fetch_quiet &&
     ++	test_commit -C fetch_upstream u_quiet &&
     ++	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_quiet &&
     ++	git checkout -q --track=fetch -b local_quiet \
     ++		fetch_upstream/fetch_quiet 2>err &&
     ++	test_grep ! "-> fetch_upstream/fetch_quiet" err &&
     ++	test_cmp_rev refs/remotes/fetch_upstream/fetch_quiet HEAD
     ++'
     ++
      +test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_switch &&
 Documentation/git-checkout.adoc |  17 +-
 Documentation/git-switch.adoc   |   5 +-
 builtin/checkout.c              | 159 +++++++++++++++++-
 t/t7201-co.sh                   | 276 ++++++++++++++++++++++++++++++++
 4 files changed, 450 insertions(+), 7 deletions(-)
Show changes to 4 files +450 −7

Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh

diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index a8b3b8c2e2..20b6cae60e 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -158,11 +158,26 @@ of it").
 	resets _<branch>_ to the start point instead of failing.
 
 `-t`::
-`--track[=(direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration. See
 	`--track` in linkgit:git-branch[1] for details. As a convenience,
 	--track without -b implies branch creation.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare _<remote>_ (e.g. `origin`), the
+branch named by _<remote>/HEAD_ is updated, and the checkout fails
+with a hint to configure that symref if it is not set. The checkout
+also fails if no configured remote's fetch refspec maps to
+_<start-point>_, or if more than one does (in which case the `fetch`
+cannot be unambiguously routed). If the fetch itself fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the checkout proceeds from the existing tip; otherwise the checkout
+is aborted.
++
 If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index d6c4f229a5..a8730b1da8 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -155,10 +155,11 @@ variable.
 	attached to a terminal, regardless of `--quiet`.
 
 `-t`::
-`--track[ (direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration.
 	`-c` is implied. See `--track` in linkgit:git-branch[1] for
-	details.
+	details, and `--track` in linkgit:git-checkout[1] for the
+	`fetch` mode.
 +
 If no `-c` option is given, the name of the new branch will be derived
 from the remote-tracking branch, by looking at the local part of the
diff --git a/builtin/checkout.c b/builtin/checkout.c
index 1345e8574a..9c5c4f1c2e 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -25,10 +25,12 @@
 #include "preload-index.h"
 #include "read-cache.h"
 #include "refs.h"
+#include "refspec.h"
 #include "remote.h"
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "sequencer.h"
 #include "setup.h"
 #include "strvec.h"
@@ -62,6 +64,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -115,6 +118,149 @@ struct branch_info {
 	char *checkout;
 };
 
+struct fetch_target_cb {
+	char *dst;
+	struct string_list matches;
+};
+
+static int match_fetch_target(struct remote *remote, void *priv)
+{
+	struct fetch_target_cb *cb = priv;
+	struct refspec_item q = { .dst = cb->dst };
+
+	if (!remote_find_tracking(remote, &q) && q.src)
+		string_list_append(&cb->matches, remote->name)->util = q.src;
+	return 0;
+}
+
+static void fetch_remote_for_start_point(const char *arg, int quiet)
+{
+	struct strbuf dst = STRBUF_INIT;
+	struct fetch_target_cb cb = { .matches = STRING_LIST_INIT_NODUP };
+	struct child_process cmd = CHILD_PROCESS_INIT;
+	struct object_id oid;
+	struct remote *named_remote;
+	int bare_ns;
+	size_t i;
+
+	strbuf_addf(&dst, "refs/remotes/%s", arg);
+	if (check_refname_format(dst.buf, 0))
+		die(_("cannot fetch start-point '%s': not a valid "
+		      "remote-tracking name"), arg);
+
+	named_remote = remote_get(arg);
+	bare_ns = !strchr(arg, '/') ||
+		(named_remote && remote_is_configured(named_remote, 1));
+	if (bare_ns) {
+		char *head_path = xstrfmt("refs/remotes/%s/HEAD", arg);
+		const char *head_target =
+			refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
+						head_path,
+						RESOLVE_REF_READING |
+						RESOLVE_REF_NO_RECURSE,
+						&oid, NULL);
+		if (head_target &&
+		    starts_with(head_target, dst.buf) &&
+		    head_target[dst.len] == '/' &&
+		    !check_refname_format(head_target, 0)) {
+			strbuf_reset(&dst);
+			strbuf_addstr(&dst, head_target);
+			bare_ns = 0;
+		}
+		free(head_path);
+	}
+
+	cb.dst = dst.buf;
+	for_each_remote(match_fetch_target, &cb);
+
+	if (cb.matches.nr > 1) {
+		struct strbuf msg = STRBUF_INIT;
+
+		strbuf_addf(&msg,
+			    _("cannot fetch start-point '%s': fetch refspecs "
+			      "of multiple remotes map to the same destination:"),
+			    arg);
+		for (i = 0; i < cb.matches.nr; i++)
+			strbuf_addf(&msg, "\n  %s", cb.matches.items[i].string);
+		strbuf_addstr(&msg,
+			      _("\nadjust 'remote.<name>.fetch' so only one "
+				"remote maps there, or omit '=fetch'"));
+		die("%s", msg.buf);
+	}
+
+	if (!cb.matches.nr) {
+		if (bare_ns && named_remote &&
+		    remote_is_configured(named_remote, 1))
+			die(_("cannot fetch start-point '%s': "
+			      "'refs/remotes/%s/HEAD' is not set; run "
+			      "'git remote set-head %s --auto' to set it"),
+			    arg, arg, arg);
+		die(_("cannot fetch start-point '%s': no configured remote's "
+		      "fetch refspec matches it"), arg);
+	}
+
+	strvec_push(&cmd.args, "fetch");
+	if (quiet)
+		strvec_push(&cmd.args, "--quiet");
+	strvec_pushl(&cmd.args, cb.matches.items[0].string,
+		     (char *)cb.matches.items[0].util, NULL);
+	cmd.git_cmd = 1;
+	if (run_command(&cmd)) {
+		if (!refs_read_ref(get_main_ref_store(the_repository),
+				   dst.buf, &oid))
+			warning(_("failed to fetch start-point '%s'; "
+				  "using existing '%s'"), arg, dst.buf);
+		else
+			die(_("failed to fetch start-point '%s'"), arg);
+	}
+
+	for (i = 0; i < cb.matches.nr; i++)
+		free(cb.matches.items[i].util);
+	string_list_clear(&cb.matches, 0);
+	strbuf_release(&dst);
+}
+
+static int parse_opt_checkout_track(const struct option *opt,
+				    const char *arg, int unset)
+{
+	struct checkout_opts *opts = opt->value;
+	struct string_list tokens = STRING_LIST_INIT_DUP;
+	struct string_list_item *item;
+	int saw_direct = 0;
+	int ret = 0;
+
+	opts->fetch = 0;
+	if (unset) {
+		opts->track = BRANCH_TRACK_NEVER;
+		return 0;
+	}
+	opts->track = BRANCH_TRACK_EXPLICIT;
+	if (!arg)
+		return 0;
+
+	string_list_split(&tokens, arg, ",", -1);
+	for_each_string_list_item(item, &tokens) {
+		if (!strcmp(item->string, "fetch"))
+			opts->fetch = 1;
+		else if (!strcmp(item->string, "direct"))
+			saw_direct = 1;
+		else if (!strcmp(item->string, "inherit"))
+			opts->track = BRANCH_TRACK_INHERIT;
+		else {
+			ret = error(_("option `%s' expects \"%s\", \"%s\", "
+				      "or \"%s\""),
+				    "--track", "direct", "inherit", "fetch");
+			goto out;
+		}
+	}
+	if (saw_direct && opts->track == BRANCH_TRACK_INHERIT)
+		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
+			    "--track", "direct", "inherit");
+out:
+	string_list_clear(&tokens, 0);
+	return ret;
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1733,10 +1879,10 @@ static struct option *add_common_switch_branch_options(
 {
 	struct option options[] = {
 		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
-		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
+		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
 			N_("set branch tracking configuration"),
 			PARSE_OPT_OPTARG,
-			parse_opt_tracking_mode),
+			parse_opt_checkout_track),
 		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
@@ -1941,8 +2087,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0], opts->quiet);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 7613b1d2a4..c4a165cb1d 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -870,4 +870,280 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --track=fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
+	test_cmp_config fetch_upstream branch.local_new.remote &&
+	test_cmp_config refs/heads/fetch_new branch.local_new.merge
+'
+
+test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
+'
+
+test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
+	git checkout main &&
+	git -C fetch_upstream checkout main &&
+	git remote set-head fetch_upstream main &&
+	git -C fetch_upstream checkout -b fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_pre &&
+	git fetch fetch_upstream fetch_unrelated &&
+	unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_main_post &&
+	git -C fetch_upstream checkout fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_post &&
+	git checkout --track=fetch -b local_from_remote fetch_upstream &&
+	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
+'
+
+test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_offline &&
+	test_commit -C fetch_upstream u_offline &&
+	git fetch fetch_upstream fetch_offline &&
+	saved_url=$(git config remote.fetch_upstream.url) &&
+	test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
+	git config remote.fetch_upstream.url ./does-not-exist &&
+	git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
+	test_grep "failed to fetch" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
+'
+
+test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
+	git checkout main &&
+	git remote add fetch_custom ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_custom" &&
+	git config --replace-all remote.fetch_custom.fetch \
+		"+refs/heads/*:refs/remotes/custom-ns/*" &&
+	git -C fetch_upstream checkout -b fetch_refspec &&
+	test_commit -C fetch_upstream u_refspec &&
+	test_must_fail git rev-parse --verify refs/remotes/custom-ns/fetch_refspec &&
+	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
+	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
+'
+
+test_expect_success 'checkout --track=fetch on namespace bare name follows <ns>/HEAD' '
+	git checkout main &&
+	git remote add fetch_ns ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_ns" &&
+	test_when_finished "git update-ref -d refs/remotes/ns_alias/HEAD" &&
+	git config --replace-all remote.fetch_ns.fetch \
+		"+refs/heads/*:refs/remotes/ns_alias/*" &&
+	git fetch fetch_ns &&
+	git symbolic-ref refs/remotes/ns_alias/HEAD refs/remotes/ns_alias/main &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_ns_post &&
+	git checkout --track=fetch -b local_ns ns_alias &&
+	test_cmp_rev refs/remotes/ns_alias/main HEAD &&
+	test_cmp_config fetch_ns branch.local_ns.remote &&
+	test_cmp_config refs/heads/main branch.local_ns.merge
+'
+
+test_expect_success '--track=fetch on bare hierarchical remote name follows <ns>/HEAD' '
+	git checkout main &&
+	git remote add nested/bare ./fetch_upstream &&
+	test_when_finished "git remote remove nested/bare" &&
+	test_when_finished "git update-ref -d refs/remotes/nested/bare/HEAD" &&
+	git fetch nested/bare &&
+	git symbolic-ref refs/remotes/nested/bare/HEAD \
+		refs/remotes/nested/bare/main &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_nested_bare_post &&
+	git checkout --track=fetch -b local_nested_bare nested/bare &&
+	test_cmp_rev refs/remotes/nested/bare/main HEAD
+'
+
+test_expect_success 'checkout --track=fetch handles hierarchical remote name' '
+	git checkout main &&
+	git remote add nested/remote ./fetch_upstream &&
+	test_when_finished "git remote remove nested/remote" &&
+	git -C fetch_upstream checkout -b fetch_hier &&
+	test_commit -C fetch_upstream u_hier &&
+	test_must_fail git rev-parse --verify refs/remotes/nested/remote/fetch_hier &&
+	git checkout --track=fetch -b local_hier nested/remote/fetch_hier &&
+	test_cmp_rev refs/remotes/nested/remote/fetch_hier HEAD
+'
+
+test_expect_success 'checkout --track=fetch dies on bare remote name with no <ns>/HEAD' '
+	git checkout main &&
+	git remote add fetch_nohead ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_nohead" &&
+	test_might_fail git symbolic-ref -d refs/remotes/fetch_nohead/HEAD &&
+	test_must_fail git checkout --track=fetch -b local_nohead fetch_nohead 2>err &&
+	test_grep "refs/remotes/fetch_nohead/HEAD" err &&
+	test_grep "git remote set-head fetch_nohead --auto" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_nohead
+'
+
+test_expect_success 'checkout --track=fetch on bare unknown name does not suggest set-head' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/no_such_ns/HEAD &&
+	test_must_fail git config --get remote.no_such_ns.url &&
+	test_must_fail git checkout --track=fetch -b local_unknown no_such_ns 2>err &&
+	test_grep "no configured remote" err &&
+	test_grep ! "set-head" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_unknown
+'
+
+test_expect_success 'checkout --track=fetch rejects <ns>/HEAD pointing outside namespace' '
+	git checkout main &&
+	git remote add fetch_crossns ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_crossns" &&
+	test_when_finished "git update-ref -d refs/remotes/fetch_crossns/HEAD" &&
+	git fetch fetch_crossns &&
+	git symbolic-ref refs/remotes/fetch_crossns/HEAD \
+		refs/remotes/fetch_upstream/u_main &&
+	test_must_fail git checkout --track=fetch -b local_crossns fetch_crossns 2>err &&
+	test_grep "refs/remotes/fetch_crossns/HEAD" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_crossns
+'
+
+test_expect_success 'checkout --track=fetch dies on ambiguous fetch refspec match' '
+	git checkout main &&
+	git remote add fetch_ambig_a ./fetch_upstream &&
+	git remote add fetch_ambig_b ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_ambig_a" &&
+	test_when_finished "git remote remove fetch_ambig_b" &&
+	git config --replace-all remote.fetch_ambig_a.fetch \
+		"+refs/heads/*:refs/remotes/ambig_ns/*" &&
+	git config --replace-all remote.fetch_ambig_b.fetch \
+		"+refs/heads/*:refs/remotes/ambig_ns/*" &&
+	git -C fetch_upstream checkout -b fetch_ambig &&
+	test_commit -C fetch_upstream u_ambig &&
+	test_must_fail git checkout --track=fetch -b local_ambig ambig_ns/fetch_ambig 2>err &&
+	test_grep "fetch_ambig_a" err &&
+	test_grep "fetch_ambig_b" err &&
+	test_grep "remote.<name>.fetch" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_ambig
+'
+
+test_expect_success 'checkout --track=fetch rejects invalid refname components' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch -b local_invalid "foo..bar" 2>err &&
+	test_grep "valid" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_invalid
+'
+
+test_expect_success 'checkout --track=fetch,inherit rejects invalid refname components' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch,inherit -b local_invalid \
+		"foo..bar" 2>err &&
+	test_grep "valid" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_invalid
+'
+
+test_expect_success 'checkout --track=inherit,direct is rejected' '
+	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
+	test_grep "cannot combine" err
+'
+
+test_expect_success 'checkout --track=direct,inherit is rejected' '
+	test_must_fail git checkout --track=direct,inherit -b bad fetch_upstream/fetch_new 2>err &&
+	test_grep "cannot combine" err
+'
+
+test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_lastwin &&
+	test_commit -C fetch_upstream u_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
+	test_must_fail git checkout --track=fetch --track=direct \
+		-b local_lastwin fetch_upstream/fetch_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
+'
+
+test_expect_success 'checkout --track=fetch then --no-track drops fetch' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_notrack &&
+	test_commit -C fetch_upstream u_notrack &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack &&
+	test_must_fail git checkout --track=fetch --no-track \
+		-b local_notrack fetch_upstream/fetch_notrack &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack
+'
+
+test_expect_success 'checkout --track=fetch,inherit fetches remote-tracking start-point' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_inherit &&
+	git checkout --track=fetch,inherit -b local_inherit \
+		fetch_upstream/fetch_inherit &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD
+'
+
+test_expect_success 'checkout --track=fetch,inherit errors when start-point does not map to a remote' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch,inherit -b bad main 2>err &&
+	test_grep "no configured remote" err &&
+	test_must_fail git rev-parse --verify refs/heads/bad
+'
+
+test_expect_success 'checkout --track=fetch on local start-point errors' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch -b bad main 2>err &&
+	test_grep "no configured remote" err &&
+	test_must_fail git rev-parse --verify refs/heads/bad
+'
+
+test_expect_success 'checkout --track=bogus reports an error' '
+	git checkout main &&
+	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
+	test_grep "expects" err
+'
+
+test_expect_success 'checkout -q --track=fetch silences the fetch output' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_quiet &&
+	test_commit -C fetch_upstream u_quiet &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_quiet &&
+	git checkout -q --track=fetch -b local_quiet \
+		fetch_upstream/fetch_quiet 2>err &&
+	test_grep ! "-> fetch_upstream/fetch_quiet" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_quiet HEAD
+'
+
+test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done

base-commit: aec3f587505a472db67e9462d0702e7d463a449d
-- 
gitgitgadget
Harald NordgrenMay 21, 2026, 10:24 UTC in reply to Phillip Wood on lore

Re: [PATCH v11] checkout: extend --track with a "fetch" mode to refresh start-point

Interesting idea! I will think about it.
Harald
On Thu, May 21, 2026 at 11:49 AM Phillip Wood <phillip.wood123@gmail.com> wrote:
Show 42 quoted lines
>
> On 19/05/2026 11:34, Junio C Hamano wrote:
> > "Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
> >
> >>      checkout: --track=fetch
> >>
> >>       * Find the right remote by checking which remote's fetch refspec maps
> >>         to the user's start-point, instead of assuming the start-point begins
> >>         with the remote's name. This fixes cases where the user has a custom
> >>         refspec mapping into a namespace whose name differs from the remote
> >>         (e.g. fetching from origin into refs/remotes/upstream/*).
> >
> > This comment is even before looking at the patch text.  After
> > getting one issue pointed out, I'd expect you to think about related
> > issues before sending a new round out.
> >
> > One.  Have you considered the case where the remote-tracking refs
> > are overlapping, e.g., where "origin" and "upstream" point at
> > different URLs but they both store in "refs/remotes/upstream/*"?
> > Perhaps their URLs may textually be different but are pointing
> > logically at the same place (e.g., one ssh:// the other https:// for
> > example).
> >
> > What should happen?  What does happen after you apply this patch?
>
> It would be worth looking at what "git checkout --track" does in that
> case and seeing if we can share the code.
>
> Thanks
>
> Phillip
>
> >
> >>       * For a bare namespace name, follow <namespace>/HEAD first to figure
> >>         out which branch to fetch.
> >
> > What should happen if HEAD does not exist?  What does happen after
> > you apply this patch?
> >
> > Thanks.
> >
>
Junio C HamanoMay 21, 2026, 12:58 UTC in reply to Phillip Wood on lore

Re: [PATCH v11] checkout: extend --track with a "fetch" mode to refresh start-point

Phillip Wood <phillip.wood123@gmail.com> writes:
Show 11 quoted lines
>> One.  Have you considered the case where the remote-tracking refs
>> are overlapping, e.g., where "origin" and "upstream" point at
>> different URLs but they both store in "refs/remotes/upstream/*"?
>> Perhaps their URLs may textually be different but are pointing
>> logically at the same place (e.g., one ssh:// the other https:// for
>> example).
>> 
>> What should happen?  What does happen after you apply this patch?
>
> It would be worth looking at what "git checkout --track" does in that 
> case and seeing if we can share the code.

It always is a good idea to think how we can share code for different purposes to solve a new problem, but in this particular one, I am not sure if "git checkout -t -b topic upstream/main" codepath has much to offer to solve what the new "before the checkout, update from the remote" feature wants to do. To the former, it does not matter how refs/remotes/upstream/* are updated and by fetching which remote at all. The only thing it cares about is to leave the record that this new "topic" branch works with refs/remotes/upstrea/main. But the latter needs to be able to compute which remote it should fetch from. It is a problem that existing code had no need to solve.

Phillip WoodMay 21, 2026, 14:06 UTC in reply to Junio C Hamano on lore

Re: [PATCH v11] checkout: extend --track with a "fetch" mode to refresh start-point

On 21/05/2026 13:58, Junio C Hamano wrote:
Show 21 quoted lines
> Phillip Wood <phillip.wood123@gmail.com> writes:
> 
>>> One.  Have you considered the case where the remote-tracking refs
>>> are overlapping, e.g., where "origin" and "upstream" point at
>>> different URLs but they both store in "refs/remotes/upstream/*"?
>>> Perhaps their URLs may textually be different but are pointing
>>> logically at the same place (e.g., one ssh:// the other https:// for
>>> example).
>>>
>>> What should happen?  What does happen after you apply this patch?
>>
>> It would be worth looking at what "git checkout --track" does in that
>> case and seeing if we can share the code.
> 
> It always is a good idea to think how we can share code for
> different purposes to solve a new problem, but in this particular
> one, I am not sure if "git checkout -t -b topic upstream/main"
> codepath has much to offer to solve what the new "before the
> checkout, update from the remote" feature wants to do.  To the
> former, it does not matter how refs/remotes/upstream/* are updated
> and by fetching which remote at all.

Don't we want to avoid creating a branch with an ambiguous upstream so that a subsequent "git pull" works though? Looking at branch.c:setup_tracking() it seems to reject upstream branches that match more than one remote.

Thanks
Phillip
Show 6 quoted lines
>  The only thing it cares about
> is to leave the record that this new "topic" branch works with
> refs/remotes/upstrea/main.  But the latter needs to be able to
> compute which remote it should fetch from.  It is a problem that
> existing code had no need to solve.
> 
Junio C HamanoMay 21, 2026, 23:53 UTC in reply to Phillip Wood on lore

Re: [PATCH v11] checkout: extend --track with a "fetch" mode to refresh start-point

Phillip Wood <phillip.wood123@gmail.com> writes:
> Don't we want to avoid creating a branch with an ambiguous upstream so 
> that a subsequent "git pull" works though? Looking at 
> branch.c:setup_tracking() it seems to reject upstream branches that 
> match more than one remote.

Yes. We may try to avoid creating misconfigured branches in the first place, but we'd want to make sure other parts of the system that consumes existing branches to behave as sensible as possible, no?

Thanks.
Harald Nordgren via GitGitGadgetMay 23, 2026, 19:48 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v13 0/2] checkout: --track=fetch

 * Create a preparatory commit that exposes find_tracking_remote_for_ref()
   and advise_ambiguous_fetch_refspec() from branch.c, so checkout can reuse
   the same lookup git branch --track uses.
 * Use advise_ambiguous_fetch_refspec() for the "multiple remotes match"
   case, so the wording matches git branch --track.
Harald Nordgren (2):
  branch: expose helpers for finding the remote owning a tracking ref
  checkout: extend --track with a "fetch" mode to refresh start-point
 Documentation/git-checkout.adoc |  17 +-
 Documentation/git-switch.adoc   |   5 +-
 branch.c                        |  96 ++++++-----
 branch.h                        |  16 ++
 builtin/checkout.c              | 139 +++++++++++++++-
 t/t7201-co.sh                   | 276 ++++++++++++++++++++++++++++++++
 6 files changed, 498 insertions(+), 51 deletions(-)
base-commit: aec3f587505a472db67e9462d0702e7d463a449d
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v13
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v13
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v12:
 -:  ---------- > 1:  2369afad24 branch: expose helpers for finding the remote owning a tracking ref
 1:  bcd034dbed ! 2:  60adf0e67d checkout: extend --track with a "fetch" mode to refresh start-point
     @@ Commit message
              git checkout -b new_branch --track origin/some-branch
      
          Identify the remote whose configured fetch refspec maps to
     -    <start-point>, then run "git fetch <remote> <src-ref>" for just that
     -    ref so other remote-tracking branches are left untouched. When
     -    <start-point> is a bare <remote> (e.g. "origin"), follow
     +    <start-point> using find_tracking_remote_for_ref() (the same lookup
     +    "--track" uses to pick which remote to record in
     +    branch.<name>.remote), then run "git fetch <remote> <src-ref>" for
     +    just that ref so other remote-tracking branches are left untouched.
     +    When <start-point> is a bare <remote> (e.g. "origin"), follow
          refs/remotes/<remote>/HEAD to learn which branch to refresh. If
          "git fetch" fails but the remote-tracking ref already exists locally,
          warn and proceed from the existing tip; otherwise abort.
     @@ builtin/checkout.c: struct branch_info {
       	char *checkout;
       };
       
     -+struct fetch_target_cb {
     -+	char *dst;
     -+	struct string_list matches;
     -+};
     -+
     -+static int match_fetch_target(struct remote *remote, void *priv)
     -+{
     -+	struct fetch_target_cb *cb = priv;
     -+	struct refspec_item q = { .dst = cb->dst };
     -+
     -+	if (!remote_find_tracking(remote, &q) && q.src)
     -+		string_list_append(&cb->matches, remote->name)->util = q.src;
     -+	return 0;
     -+}
     -+
      +static void fetch_remote_for_start_point(const char *arg, int quiet)
      +{
      +	struct strbuf dst = STRBUF_INIT;
     -+	struct fetch_target_cb cb = { .matches = STRING_LIST_INIT_NODUP };
     ++	struct tracking tracking;
     ++	struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
     ++	struct string_list ambiguous_remotes = STRING_LIST_INIT_DUP;
      +	struct child_process cmd = CHILD_PROCESS_INIT;
      +	struct object_id oid;
      +	struct remote *named_remote;
      +	int bare_ns;
     -+	size_t i;
      +
      +	strbuf_addf(&dst, "refs/remotes/%s", arg);
      +	if (check_refname_format(dst.buf, 0))
     @@ builtin/checkout.c: struct branch_info {
      +		free(head_path);
      +	}
      +
     -+	cb.dst = dst.buf;
     -+	for_each_remote(match_fetch_target, &cb);
     -+
     -+	if (cb.matches.nr > 1) {
     -+		struct strbuf msg = STRBUF_INIT;
     -+
     -+		strbuf_addf(&msg,
     -+			    _("cannot fetch start-point '%s': fetch refspecs "
     -+			      "of multiple remotes map to the same destination:"),
     -+			    arg);
     -+		for (i = 0; i < cb.matches.nr; i++)
     -+			strbuf_addf(&msg, "\n  %s", cb.matches.items[i].string);
     -+		strbuf_addstr(&msg,
     -+			      _("\nadjust 'remote.<name>.fetch' so only one "
     -+				"remote maps there, or omit '=fetch'"));
     -+		die("%s", msg.buf);
     ++	memset(&tracking, 0, sizeof(tracking));
     ++	tracking.spec.dst = dst.buf;
     ++	tracking.srcs = &tracking_srcs;
     ++	find_tracking_remote_for_ref(&tracking, &ambiguous_remotes);
     ++
     ++	if (tracking.matches > 1) {
     ++		int status = die_message(_("cannot fetch start-point '%s': "
     ++					   "fetch refspecs of multiple remotes "
     ++					   "map to '%s'"), arg, dst.buf);
     ++		advise_ambiguous_fetch_refspec(dst.buf, &ambiguous_remotes);
     ++		exit(status);
      +	}
      +
     -+	if (!cb.matches.nr) {
     ++	if (!tracking.matches) {
      +		if (bare_ns && named_remote &&
      +		    remote_is_configured(named_remote, 1))
      +			die(_("cannot fetch start-point '%s': "
     @@ builtin/checkout.c: struct branch_info {
      +	strvec_push(&cmd.args, "fetch");
      +	if (quiet)
      +		strvec_push(&cmd.args, "--quiet");
     -+	strvec_pushl(&cmd.args, cb.matches.items[0].string,
     -+		     (char *)cb.matches.items[0].util, NULL);
     ++	strvec_pushl(&cmd.args, tracking.remote,
     ++		     tracking_srcs.items[0].string, NULL);
      +	cmd.git_cmd = 1;
      +	if (run_command(&cmd)) {
      +		if (!refs_read_ref(get_main_ref_store(the_repository),
     @@ builtin/checkout.c: struct branch_info {
      +			die(_("failed to fetch start-point '%s'"), arg);
      +	}
      +
     -+	for (i = 0; i < cb.matches.nr; i++)
     -+		free(cb.matches.items[i].util);
     -+	string_list_clear(&cb.matches, 0);
     ++	string_list_clear(&tracking_srcs, 0);
     ++	string_list_clear(&ambiguous_remotes, 0);
      +	strbuf_release(&dst);
      +}
      +
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_must_fail git checkout --track=fetch -b local_ambig ambig_ns/fetch_ambig 2>err &&
      +	test_grep "fetch_ambig_a" err &&
      +	test_grep "fetch_ambig_b" err &&
     -+	test_grep "remote.<name>.fetch" err &&
     ++	test_grep "tracking namespaces" err &&
      +	test_must_fail git rev-parse --verify refs/heads/local_ambig
      +'
      +
-- 
gitgitgadget
Harald Nordgren via GitGitGadgetMay 23, 2026, 19:48 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v13 1/2] branch: expose helpers for finding the remote owning a tracking ref

From: Harald Nordgren <haraldnordgren@gmail.com>

The remote-lookup that setup_tracking() does is useful outside branch.c too; for example, deciding which remote to "git fetch" from given a remote-tracking ref.

Move 'struct tracking' to branch.h and add two helpers backed by the existing for_each_remote walk: find_tracking_remote_for_ref() and advise_ambiguous_fetch_refspec(). setup_tracking() uses both. No behavior change.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
 branch.c | 96 ++++++++++++++++++++++++++++++--------------------------
 branch.h | 16 ++++++++++
 2 files changed, 68 insertions(+), 44 deletions(-)
Show changes to 2 files +68 −44

branch.c, branch.h

diff --git a/branch.c b/branch.c
index 243db7d0fc..46ae7f0035 100644
--- a/branch.c
+++ b/branch.c
@@ -20,16 +20,9 @@
 #include "run-command.h"
 #include "strmap.h"
 
-struct tracking {
-	struct refspec_item spec;
-	struct string_list *srcs;
-	const char *remote;
-	int matches;
-};
-
 struct find_tracked_branch_cb {
 	struct tracking *tracking;
-	struct string_list ambiguous_remotes;
+	struct string_list *ambiguous_remotes;
 };
 
 static int find_tracked_branch(struct remote *remote, void *priv)
@@ -45,10 +38,10 @@ static int find_tracked_branch(struct remote *remote, void *priv)
 			break;
 		case 2:
 			/* there are at least two remotes; backfill the first one */
-			string_list_append(&ftb->ambiguous_remotes, tracking->remote);
+			string_list_append(ftb->ambiguous_remotes, tracking->remote);
 			/* fall through */
 		default:
-			string_list_append(&ftb->ambiguous_remotes, remote->name);
+			string_list_append(ftb->ambiguous_remotes, remote->name);
 			free(tracking->spec.src);
 			string_list_clear(tracking->srcs, 0);
 		break;
@@ -59,6 +52,51 @@ static int find_tracked_branch(struct remote *remote, void *priv)
 	return 0;
 }
 
+void find_tracking_remote_for_ref(struct tracking *tracking,
+				  struct string_list *ambiguous_remotes)
+{
+	struct find_tracked_branch_cb ftb_cb = {
+		.tracking = tracking,
+		.ambiguous_remotes = ambiguous_remotes,
+	};
+
+	for_each_remote(find_tracked_branch, &ftb_cb);
+}
+
+void advise_ambiguous_fetch_refspec(const char *dst,
+				    const struct string_list *ambiguous_remotes)
+{
+	struct strbuf remotes_advice = STRBUF_INIT;
+	struct string_list_item *item;
+
+	if (!advice_enabled(ADVICE_AMBIGUOUS_FETCH_REFSPEC))
+		return;
+
+	for_each_string_list_item(item, ambiguous_remotes)
+		/*
+		 * TRANSLATORS: This is a line listing a remote with duplicate
+		 * refspecs in the advice message below. For RTL languages you'll
+		 * probably want to swap the "%s" and leading "  " space around.
+		 */
+		strbuf_addf(&remotes_advice, _("  %s\n"), item->string);
+
+	/*
+	 * TRANSLATORS: The second argument is a \n-delimited list of
+	 * duplicate refspecs, composed above.
+	 */
+	advise(_("There are multiple remotes whose fetch refspecs map to the remote\n"
+		 "tracking ref '%s':\n"
+		 "%s"
+		 "\n"
+		 "This is typically a configuration error.\n"
+		 "\n"
+		 "To support setting up tracking branches, ensure that\n"
+		 "different remotes' fetch refspecs map into different\n"
+		 "tracking namespaces."), dst,
+	       remotes_advice.buf);
+	strbuf_release(&remotes_advice);
+}
+
 static int should_setup_rebase(const char *origin)
 {
 	switch (autorebase) {
@@ -254,11 +292,8 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 {
 	struct tracking tracking;
 	struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
+	struct string_list ambiguous_remotes = STRING_LIST_INIT_DUP;
 	int config_flags = quiet ? 0 : BRANCH_CONFIG_VERBOSE;
-	struct find_tracked_branch_cb ftb_cb = {
-		.tracking = &tracking,
-		.ambiguous_remotes = STRING_LIST_INIT_DUP,
-	};
 
 	if (!track)
 		BUG("asked to set up tracking, but tracking is disallowed");
@@ -267,7 +302,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 	tracking.spec.dst = (char *)orig_ref;
 	tracking.srcs = &tracking_srcs;
 	if (track != BRANCH_TRACK_INHERIT)
-		for_each_remote(find_tracked_branch, &ftb_cb);
+		find_tracking_remote_for_ref(&tracking, &ambiguous_remotes);
 	else if (inherit_tracking(&tracking, orig_ref))
 		goto cleanup;
 
@@ -293,34 +328,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 	if (tracking.matches > 1) {
 		int status = die_message(_("not tracking: ambiguous information for ref '%s'"),
 					    orig_ref);
-		if (advice_enabled(ADVICE_AMBIGUOUS_FETCH_REFSPEC)) {
-			struct strbuf remotes_advice = STRBUF_INIT;
-			struct string_list_item *item;
-
-			for_each_string_list_item(item, &ftb_cb.ambiguous_remotes)
-				/*
-				 * TRANSLATORS: This is a line listing a remote with duplicate
-				 * refspecs in the advice message below. For RTL languages you'll
-				 * probably want to swap the "%s" and leading "  " space around.
-				 */
-				strbuf_addf(&remotes_advice, _("  %s\n"), item->string);
-
-			/*
-			 * TRANSLATORS: The second argument is a \n-delimited list of
-			 * duplicate refspecs, composed above.
-			 */
-			advise(_("There are multiple remotes whose fetch refspecs map to the remote\n"
-				 "tracking ref '%s':\n"
-				 "%s"
-				 "\n"
-				 "This is typically a configuration error.\n"
-				 "\n"
-				 "To support setting up tracking branches, ensure that\n"
-				 "different remotes' fetch refspecs map into different\n"
-				 "tracking namespaces."), orig_ref,
-			       remotes_advice.buf);
-			strbuf_release(&remotes_advice);
-		}
+		advise_ambiguous_fetch_refspec(orig_ref, &ambiguous_remotes);
 		exit(status);
 	}
 
@@ -347,7 +355,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 
 cleanup:
 	string_list_clear(&tracking_srcs, 0);
-	string_list_clear(&ftb_cb.ambiguous_remotes, 0);
+	string_list_clear(&ambiguous_remotes, 0);
 }
 
 int read_branch_desc(struct strbuf *buf, const char *branch_name)
diff --git a/branch.h b/branch.h
index 3dc6e2a0ff..0aafa1673f 100644
--- a/branch.h
+++ b/branch.h
@@ -1,9 +1,25 @@
 #ifndef BRANCH_H
 #define BRANCH_H
 
+#include "refspec.h"
+#include "string-list.h"
+
 struct repository;
 struct strbuf;
 
+struct tracking {
+	struct refspec_item spec;
+	struct string_list *srcs;
+	const char *remote;
+	int matches;
+};
+
+void find_tracking_remote_for_ref(struct tracking *tracking,
+				  struct string_list *ambiguous_remotes);
+
+void advise_ambiguous_fetch_refspec(const char *dst,
+				    const struct string_list *ambiguous_remotes);
+
 enum branch_track {
 	BRANCH_TRACK_UNSPECIFIED = -1,
 	BRANCH_TRACK_NEVER = 0,
-- 
gitgitgadget
Harald Nordgren via GitGitGadgetMay 23, 2026, 19:48 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v13 2/2] checkout: extend --track with a "fetch" mode to refresh start-point

From: Harald Nordgren <haraldnordgren@gmail.com>

Add a "fetch" mode to the "--track" option of "git checkout" / "git switch" that refreshes <start-point> before checking it out:

    git checkout -b new_branch --track=fetch origin/some-branch
is shorthand for
    git fetch origin some-branch
    git checkout -b new_branch --track origin/some-branch

Identify the remote whose configured fetch refspec maps to <start-point> using find_tracking_remote_for_ref() (the same lookup "--track" uses to pick which remote to record in branch.<name>.remote), then run "git fetch <remote> <src-ref>" for just that ref so other remote-tracking branches are left untouched. When <start-point> is a bare <remote> (e.g. "origin"), follow refs/remotes/<remote>/HEAD to learn which branch to refresh. If "git fetch" fails but the remote-tracking ref already exists locally, warn and proceed from the existing tip; otherwise abort.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
 Documentation/git-checkout.adoc |  17 +-
 Documentation/git-switch.adoc   |   5 +-
 builtin/checkout.c              | 139 +++++++++++++++-
 t/t7201-co.sh                   | 276 ++++++++++++++++++++++++++++++++
 4 files changed, 430 insertions(+), 7 deletions(-)
Show changes to 4 files +430 −7

Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh

diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index a8b3b8c2e2..20b6cae60e 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -158,11 +158,26 @@ of it").
 	resets _<branch>_ to the start point instead of failing.
 
 `-t`::
-`--track[=(direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration. See
 	`--track` in linkgit:git-branch[1] for details. As a convenience,
 	--track without -b implies branch creation.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare _<remote>_ (e.g. `origin`), the
+branch named by _<remote>/HEAD_ is updated, and the checkout fails
+with a hint to configure that symref if it is not set. The checkout
+also fails if no configured remote's fetch refspec maps to
+_<start-point>_, or if more than one does (in which case the `fetch`
+cannot be unambiguously routed). If the fetch itself fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the checkout proceeds from the existing tip; otherwise the checkout
+is aborted.
++
 If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index d6c4f229a5..a8730b1da8 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -155,10 +155,11 @@ variable.
 	attached to a terminal, regardless of `--quiet`.
 
 `-t`::
-`--track[ (direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration.
 	`-c` is implied. See `--track` in linkgit:git-branch[1] for
-	details.
+	details, and `--track` in linkgit:git-checkout[1] for the
+	`fetch` mode.
 +
 If no `-c` option is given, the name of the new branch will be derived
 from the remote-tracking branch, by looking at the local part of the
diff --git a/builtin/checkout.c b/builtin/checkout.c
index 1345e8574a..25b511f22a 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -25,10 +25,12 @@
 #include "preload-index.h"
 #include "read-cache.h"
 #include "refs.h"
+#include "refspec.h"
 #include "remote.h"
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "sequencer.h"
 #include "setup.h"
 #include "strvec.h"
@@ -62,6 +64,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -115,6 +118,129 @@ struct branch_info {
 	char *checkout;
 };
 
+static void fetch_remote_for_start_point(const char *arg, int quiet)
+{
+	struct strbuf dst = STRBUF_INIT;
+	struct tracking tracking;
+	struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
+	struct string_list ambiguous_remotes = STRING_LIST_INIT_DUP;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+	struct object_id oid;
+	struct remote *named_remote;
+	int bare_ns;
+
+	strbuf_addf(&dst, "refs/remotes/%s", arg);
+	if (check_refname_format(dst.buf, 0))
+		die(_("cannot fetch start-point '%s': not a valid "
+		      "remote-tracking name"), arg);
+
+	named_remote = remote_get(arg);
+	bare_ns = !strchr(arg, '/') ||
+		(named_remote && remote_is_configured(named_remote, 1));
+	if (bare_ns) {
+		char *head_path = xstrfmt("refs/remotes/%s/HEAD", arg);
+		const char *head_target =
+			refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
+						head_path,
+						RESOLVE_REF_READING |
+						RESOLVE_REF_NO_RECURSE,
+						&oid, NULL);
+		if (head_target &&
+		    starts_with(head_target, dst.buf) &&
+		    head_target[dst.len] == '/' &&
+		    !check_refname_format(head_target, 0)) {
+			strbuf_reset(&dst);
+			strbuf_addstr(&dst, head_target);
+			bare_ns = 0;
+		}
+		free(head_path);
+	}
+
+	memset(&tracking, 0, sizeof(tracking));
+	tracking.spec.dst = dst.buf;
+	tracking.srcs = &tracking_srcs;
+	find_tracking_remote_for_ref(&tracking, &ambiguous_remotes);
+
+	if (tracking.matches > 1) {
+		int status = die_message(_("cannot fetch start-point '%s': "
+					   "fetch refspecs of multiple remotes "
+					   "map to '%s'"), arg, dst.buf);
+		advise_ambiguous_fetch_refspec(dst.buf, &ambiguous_remotes);
+		exit(status);
+	}
+
+	if (!tracking.matches) {
+		if (bare_ns && named_remote &&
+		    remote_is_configured(named_remote, 1))
+			die(_("cannot fetch start-point '%s': "
+			      "'refs/remotes/%s/HEAD' is not set; run "
+			      "'git remote set-head %s --auto' to set it"),
+			    arg, arg, arg);
+		die(_("cannot fetch start-point '%s': no configured remote's "
+		      "fetch refspec matches it"), arg);
+	}
+
+	strvec_push(&cmd.args, "fetch");
+	if (quiet)
+		strvec_push(&cmd.args, "--quiet");
+	strvec_pushl(&cmd.args, tracking.remote,
+		     tracking_srcs.items[0].string, NULL);
+	cmd.git_cmd = 1;
+	if (run_command(&cmd)) {
+		if (!refs_read_ref(get_main_ref_store(the_repository),
+				   dst.buf, &oid))
+			warning(_("failed to fetch start-point '%s'; "
+				  "using existing '%s'"), arg, dst.buf);
+		else
+			die(_("failed to fetch start-point '%s'"), arg);
+	}
+
+	string_list_clear(&tracking_srcs, 0);
+	string_list_clear(&ambiguous_remotes, 0);
+	strbuf_release(&dst);
+}
+
+static int parse_opt_checkout_track(const struct option *opt,
+				    const char *arg, int unset)
+{
+	struct checkout_opts *opts = opt->value;
+	struct string_list tokens = STRING_LIST_INIT_DUP;
+	struct string_list_item *item;
+	int saw_direct = 0;
+	int ret = 0;
+
+	opts->fetch = 0;
+	if (unset) {
+		opts->track = BRANCH_TRACK_NEVER;
+		return 0;
+	}
+	opts->track = BRANCH_TRACK_EXPLICIT;
+	if (!arg)
+		return 0;
+
+	string_list_split(&tokens, arg, ",", -1);
+	for_each_string_list_item(item, &tokens) {
+		if (!strcmp(item->string, "fetch"))
+			opts->fetch = 1;
+		else if (!strcmp(item->string, "direct"))
+			saw_direct = 1;
+		else if (!strcmp(item->string, "inherit"))
+			opts->track = BRANCH_TRACK_INHERIT;
+		else {
+			ret = error(_("option `%s' expects \"%s\", \"%s\", "
+				      "or \"%s\""),
+				    "--track", "direct", "inherit", "fetch");
+			goto out;
+		}
+	}
+	if (saw_direct && opts->track == BRANCH_TRACK_INHERIT)
+		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
+			    "--track", "direct", "inherit");
+out:
+	string_list_clear(&tokens, 0);
+	return ret;
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1733,10 +1859,10 @@ static struct option *add_common_switch_branch_options(
 {
 	struct option options[] = {
 		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
-		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
+		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
 			N_("set branch tracking configuration"),
 			PARSE_OPT_OPTARG,
-			parse_opt_tracking_mode),
+			parse_opt_checkout_track),
 		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
@@ -1941,8 +2067,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0], opts->quiet);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 7613b1d2a4..1e321b1512 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -870,4 +870,280 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --track=fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
+	test_cmp_config fetch_upstream branch.local_new.remote &&
+	test_cmp_config refs/heads/fetch_new branch.local_new.merge
+'
+
+test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
+'
+
+test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
+	git checkout main &&
+	git -C fetch_upstream checkout main &&
+	git remote set-head fetch_upstream main &&
+	git -C fetch_upstream checkout -b fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_pre &&
+	git fetch fetch_upstream fetch_unrelated &&
+	unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_main_post &&
+	git -C fetch_upstream checkout fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_post &&
+	git checkout --track=fetch -b local_from_remote fetch_upstream &&
+	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
+'
+
+test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_offline &&
+	test_commit -C fetch_upstream u_offline &&
+	git fetch fetch_upstream fetch_offline &&
+	saved_url=$(git config remote.fetch_upstream.url) &&
+	test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
+	git config remote.fetch_upstream.url ./does-not-exist &&
+	git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
+	test_grep "failed to fetch" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
+'
+
+test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
+	git checkout main &&
+	git remote add fetch_custom ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_custom" &&
+	git config --replace-all remote.fetch_custom.fetch \
+		"+refs/heads/*:refs/remotes/custom-ns/*" &&
+	git -C fetch_upstream checkout -b fetch_refspec &&
+	test_commit -C fetch_upstream u_refspec &&
+	test_must_fail git rev-parse --verify refs/remotes/custom-ns/fetch_refspec &&
+	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
+	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
+'
+
+test_expect_success 'checkout --track=fetch on namespace bare name follows <ns>/HEAD' '
+	git checkout main &&
+	git remote add fetch_ns ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_ns" &&
+	test_when_finished "git update-ref -d refs/remotes/ns_alias/HEAD" &&
+	git config --replace-all remote.fetch_ns.fetch \
+		"+refs/heads/*:refs/remotes/ns_alias/*" &&
+	git fetch fetch_ns &&
+	git symbolic-ref refs/remotes/ns_alias/HEAD refs/remotes/ns_alias/main &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_ns_post &&
+	git checkout --track=fetch -b local_ns ns_alias &&
+	test_cmp_rev refs/remotes/ns_alias/main HEAD &&
+	test_cmp_config fetch_ns branch.local_ns.remote &&
+	test_cmp_config refs/heads/main branch.local_ns.merge
+'
+
+test_expect_success '--track=fetch on bare hierarchical remote name follows <ns>/HEAD' '
+	git checkout main &&
+	git remote add nested/bare ./fetch_upstream &&
+	test_when_finished "git remote remove nested/bare" &&
+	test_when_finished "git update-ref -d refs/remotes/nested/bare/HEAD" &&
+	git fetch nested/bare &&
+	git symbolic-ref refs/remotes/nested/bare/HEAD \
+		refs/remotes/nested/bare/main &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_nested_bare_post &&
+	git checkout --track=fetch -b local_nested_bare nested/bare &&
+	test_cmp_rev refs/remotes/nested/bare/main HEAD
+'
+
+test_expect_success 'checkout --track=fetch handles hierarchical remote name' '
+	git checkout main &&
+	git remote add nested/remote ./fetch_upstream &&
+	test_when_finished "git remote remove nested/remote" &&
+	git -C fetch_upstream checkout -b fetch_hier &&
+	test_commit -C fetch_upstream u_hier &&
+	test_must_fail git rev-parse --verify refs/remotes/nested/remote/fetch_hier &&
+	git checkout --track=fetch -b local_hier nested/remote/fetch_hier &&
+	test_cmp_rev refs/remotes/nested/remote/fetch_hier HEAD
+'
+
+test_expect_success 'checkout --track=fetch dies on bare remote name with no <ns>/HEAD' '
+	git checkout main &&
+	git remote add fetch_nohead ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_nohead" &&
+	test_might_fail git symbolic-ref -d refs/remotes/fetch_nohead/HEAD &&
+	test_must_fail git checkout --track=fetch -b local_nohead fetch_nohead 2>err &&
+	test_grep "refs/remotes/fetch_nohead/HEAD" err &&
+	test_grep "git remote set-head fetch_nohead --auto" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_nohead
+'
+
+test_expect_success 'checkout --track=fetch on bare unknown name does not suggest set-head' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/no_such_ns/HEAD &&
+	test_must_fail git config --get remote.no_such_ns.url &&
+	test_must_fail git checkout --track=fetch -b local_unknown no_such_ns 2>err &&
+	test_grep "no configured remote" err &&
+	test_grep ! "set-head" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_unknown
+'
+
+test_expect_success 'checkout --track=fetch rejects <ns>/HEAD pointing outside namespace' '
+	git checkout main &&
+	git remote add fetch_crossns ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_crossns" &&
+	test_when_finished "git update-ref -d refs/remotes/fetch_crossns/HEAD" &&
+	git fetch fetch_crossns &&
+	git symbolic-ref refs/remotes/fetch_crossns/HEAD \
+		refs/remotes/fetch_upstream/u_main &&
+	test_must_fail git checkout --track=fetch -b local_crossns fetch_crossns 2>err &&
+	test_grep "refs/remotes/fetch_crossns/HEAD" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_crossns
+'
+
+test_expect_success 'checkout --track=fetch dies on ambiguous fetch refspec match' '
+	git checkout main &&
+	git remote add fetch_ambig_a ./fetch_upstream &&
+	git remote add fetch_ambig_b ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_ambig_a" &&
+	test_when_finished "git remote remove fetch_ambig_b" &&
+	git config --replace-all remote.fetch_ambig_a.fetch \
+		"+refs/heads/*:refs/remotes/ambig_ns/*" &&
+	git config --replace-all remote.fetch_ambig_b.fetch \
+		"+refs/heads/*:refs/remotes/ambig_ns/*" &&
+	git -C fetch_upstream checkout -b fetch_ambig &&
+	test_commit -C fetch_upstream u_ambig &&
+	test_must_fail git checkout --track=fetch -b local_ambig ambig_ns/fetch_ambig 2>err &&
+	test_grep "fetch_ambig_a" err &&
+	test_grep "fetch_ambig_b" err &&
+	test_grep "tracking namespaces" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_ambig
+'
+
+test_expect_success 'checkout --track=fetch rejects invalid refname components' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch -b local_invalid "foo..bar" 2>err &&
+	test_grep "valid" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_invalid
+'
+
+test_expect_success 'checkout --track=fetch,inherit rejects invalid refname components' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch,inherit -b local_invalid \
+		"foo..bar" 2>err &&
+	test_grep "valid" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_invalid
+'
+
+test_expect_success 'checkout --track=inherit,direct is rejected' '
+	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
+	test_grep "cannot combine" err
+'
+
+test_expect_success 'checkout --track=direct,inherit is rejected' '
+	test_must_fail git checkout --track=direct,inherit -b bad fetch_upstream/fetch_new 2>err &&
+	test_grep "cannot combine" err
+'
+
+test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_lastwin &&
+	test_commit -C fetch_upstream u_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
+	test_must_fail git checkout --track=fetch --track=direct \
+		-b local_lastwin fetch_upstream/fetch_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
+'
+
+test_expect_success 'checkout --track=fetch then --no-track drops fetch' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_notrack &&
+	test_commit -C fetch_upstream u_notrack &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack &&
+	test_must_fail git checkout --track=fetch --no-track \
+		-b local_notrack fetch_upstream/fetch_notrack &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack
+'
+
+test_expect_success 'checkout --track=fetch,inherit fetches remote-tracking start-point' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_inherit &&
+	git checkout --track=fetch,inherit -b local_inherit \
+		fetch_upstream/fetch_inherit &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD
+'
+
+test_expect_success 'checkout --track=fetch,inherit errors when start-point does not map to a remote' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch,inherit -b bad main 2>err &&
+	test_grep "no configured remote" err &&
+	test_must_fail git rev-parse --verify refs/heads/bad
+'
+
+test_expect_success 'checkout --track=fetch on local start-point errors' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch -b bad main 2>err &&
+	test_grep "no configured remote" err &&
+	test_must_fail git rev-parse --verify refs/heads/bad
+'
+
+test_expect_success 'checkout --track=bogus reports an error' '
+	git checkout main &&
+	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
+	test_grep "expects" err
+'
+
+test_expect_success 'checkout -q --track=fetch silences the fetch output' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_quiet &&
+	test_commit -C fetch_upstream u_quiet &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_quiet &&
+	git checkout -q --track=fetch -b local_quiet \
+		fetch_upstream/fetch_quiet 2>err &&
+	test_grep ! "-> fetch_upstream/fetch_quiet" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_quiet HEAD
+'
+
+test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done
-- 
gitgitgadget
Harald NordgrenJun 13, 2026, 17:38 UTC in reply to Phillip Wood on lore

Re: [PATCH v11] checkout: extend --track with a "fetch" mode to refresh start-point

Hi Phillip and JCH!

Would it be possible to get another look here to know if it's worth continuing with this topic. I think it's a useful feature, but the feedback from this list has been a bit lukewarm.

Harald
On Thu, May 21, 2026 at 4:06 PM Phillip Wood <phillip.wood123@gmail.com> wrote:
Show 40 quoted lines
>
> On 21/05/2026 13:58, Junio C Hamano wrote:
> > Phillip Wood <phillip.wood123@gmail.com> writes:
> >
> >>> One.  Have you considered the case where the remote-tracking refs
> >>> are overlapping, e.g., where "origin" and "upstream" point at
> >>> different URLs but they both store in "refs/remotes/upstream/*"?
> >>> Perhaps their URLs may textually be different but are pointing
> >>> logically at the same place (e.g., one ssh:// the other https:// for
> >>> example).
> >>>
> >>> What should happen?  What does happen after you apply this patch?
> >>
> >> It would be worth looking at what "git checkout --track" does in that
> >> case and seeing if we can share the code.
> >
> > It always is a good idea to think how we can share code for
> > different purposes to solve a new problem, but in this particular
> > one, I am not sure if "git checkout -t -b topic upstream/main"
> > codepath has much to offer to solve what the new "before the
> > checkout, update from the remote" feature wants to do.  To the
> > former, it does not matter how refs/remotes/upstream/* are updated
> > and by fetching which remote at all.
>
> Don't we want to avoid creating a branch with an ambiguous upstream so
> that a subsequent "git pull" works though? Looking at
> branch.c:setup_tracking() it seems to reject upstream branches that
> match more than one remote.
>
> Thanks
>
> Phillip
>
> >  The only thing it cares about
> > is to leave the record that this new "topic" branch works with
> > refs/remotes/upstrea/main.  But the latter needs to be able to
> > compute which remote it should fetch from.  It is a problem that
> > existing code had no need to solve.
> >
>
Junio C HamanoJun 17, 2026, 19:15 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH v13 0/2] checkout: --track=fetch

"Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
Show 17 quoted lines
>  * Create a preparatory commit that exposes find_tracking_remote_for_ref()
>    and advise_ambiguous_fetch_refspec() from branch.c, so checkout can reuse
>    the same lookup git branch --track uses.
>  * Use advise_ambiguous_fetch_refspec() for the "multiple remotes match"
>    case, so the wording matches git branch --track.
>
> Harald Nordgren (2):
>   branch: expose helpers for finding the remote owning a tracking ref
>   checkout: extend --track with a "fetch" mode to refresh start-point
>
>  Documentation/git-checkout.adoc |  17 +-
>  Documentation/git-switch.adoc   |   5 +-
>  branch.c                        |  96 ++++++-----
>  branch.h                        |  16 ++
>  builtin/checkout.c              | 139 +++++++++++++++-
>  t/t7201-co.sh                   | 276 ++++++++++++++++++++++++++++++++
>  6 files changed, 498 insertions(+), 51 deletions(-)

I was scanning "What's cooking" and this topic was the oldest one among the ones marked as "Needs review". Nobody seems to have commented on this iteration.

I am still not convinced that it is a good idea to allow "checkout" to go to the network and muck with remote-tracking branches. The remote-tracking branches are meant to give us solid reference points, and such an on-demand update to move them (which by itself is not bad) and then use the updated result without first seeing what it contains (which is the part I disagree with) cannot lead us to a good place. I suspect that the feature encourages a bad workflow to our end-users.

Having said all that, the changes since v12, in response to earlier review comments to avoid duplicating the remote lookup and ambiguity advice logic, look well executed in this round. This also ensures consistent error messages and behavior between 'git branch --track' and 'git checkout --track=fetch'.

IOW, I find the mechanical implementation fairly solid. I am not sure if we are implementing a good thing, though.

One small thing about [1/2];
Show changes to branch.h +17 −1
diff --git a/branch.h b/branch.h
index 3dc6e2a0ff..0aafa1673f 100644
--- a/branch.h
+++ b/branch.h
@@ -1,9 +1,25 @@
 #ifndef BRANCH_H
 #define BRANCH_H
 
+#include "refspec.h"
+#include "string-list.h"
+
 struct repository;
 struct strbuf;
 
+struct tracking {
+	struct refspec_item spec;
+	struct string_list *srcs;
+	const char *remote;
+	int matches;
+};
+
+void find_tracking_remote_for_ref(struct tracking *tracking,
+				  struct string_list *ambiguous_remotes);
+
+void advise_ambiguous_fetch_refspec(const char *dst,
+				    const struct string_list *ambiguous_remotes);
+

As we are not embedding any "string_list" instance into any of our
struct (we only have a pointer to a struct), unlike the way we embed
"struct refspec_item" that requires us to include "refspec.h", we do
not need to include "string-list.h".  Instead, we only need to
declare "struct string_list", just like we declare repository and
strbuf.

diff --git i/branch.h w/branch.h
index 0aafa1673f..c2e6725491 100644
--- i/branch.h
+++ w/branch.h
@@ -2,8 +2,8 @@
 #define BRANCH_H
 
 #include "refspec.h"
-#include "string-list.h"
 
+struct string_list;
 struct repository;
 struct strbuf;
 
Harald NordgrenJun 17, 2026, 22:10 UTC in reply to Junio C Hamano on lore

Re: [PATCH v13 0/2] checkout: --track=fetch

Hi!

Thanks for your continued attention here, I appreciate the help on all my topics.

But can I offer some (unsolicited) feedback on this review process in particular? Given that it seems unlikely to hit 'master' at this point, I want to say that it's the wrong order of things to dig into code specific feedback, before deciding if we even want the feature at all. We are wasting each other's time. I have pushed on despite initial negative feedback, that's on me. But I also cannot lay flat, I like the idea so I keep pushing. Now we have v13, maybe soon v14, of a topic that has slim chances of passing.

I would have been much happier if you shut this topic down directly.

Imagine all the review time spent on this that could have been better spent elsewhere.

Harald
Junio C HamanoJun 18, 2026, 02:50 UTC in reply to Harald Nordgren on lore

Re: [PATCH v13 0/2] checkout: --track=fetch

Harald Nordgren <haraldnordgren@gmail.com> writes:
Show 13 quoted lines
> But can I offer some (unsolicited) feedback on this review process in
> particular? Given that it seems unlikely to hit 'master' at this
> point, I want to say that it's the wrong order of things to dig into
> code specific feedback, before deciding if we even want the feature at
> all. We are wasting each other's time. I have pushed on despite
> initial negative feedback, that's on me. But I also cannot lay flat, I
> like the idea so I keep pushing. Now we have v13, maybe soon v14, of a
> topic that has slim chances of passing.
>
> I would have been much happier if you shut this topic down directly.
>
> Imagine all the review time spent on this that could have been better
> spent elsewhere.

You are forgetting that there are two things a topic author can and should do: addressing higher-level design issues (e.g., Counter "is it a good idea to begin with?" with "it is, because in this context you haven't thought about, it would make the user experience better", to help reviewers understand and hopefully agree with your viewpoint) and addressing mechanical implementation issues (e.g., Respond to "it is wasteful and adds maintenance burden to dupplicate the logic here and there" with "Here is an updated implementation based on better refactoring"). The latter is easier in a sense, especially when the reviewers say something like "I am not sure if this is a good idea to begin with, but assuming it is, here are the things I find in your implementation". But the former needs to be addressed eventually before the topic can gain wider support (remember, it does not have to be sold to _me_ 100% and make me say "oh, I cannot believe Git did not have this feature for 20 years!"; you only need to convince me that it is OK to have it as an opt-in feature, that is a lot lower bar to cross. In addition, I do not have to agree with it at all, as long as others whose judgement I trust well enough support the feature).

Harald NordgrenJun 18, 2026, 12:36 UTC in reply to D. Ben Knoble on lore

Re: [PATCH] checkout: add --fetch to fetch remote before resolving start-point

Hi Ben!
Trying to shore up some support for this topic. How do you feel about this now?
Harald
Harald NordgrenJun 18, 2026, 12:38 UTC in reply to Phillip Wood on lore

Re: [PATCH v6] checkout: extend --track with a "fetch" mode to refresh start-point

Hi Phillip!

How do you feel now, is it worth it for us to move forward with this topic or not?

Harald
On Fri, May 8, 2026 at 3:15 PM Phillip Wood <phillip.wood123@gmail.com> wrote:
Show 35 quoted lines
>
> Hi Harald
>
> On 07/05/2026 21:12, Harald Nordgren wrote:
> > Is this ready to move to next?
>
> I'm not particularly enthusiastic one way or the other about adding
> this, but so long as we only try to fetch when the user explicitly asks
> for it I don't particularly object. However having had a quick scan of
> the implementation I have a few comments
>
> * "--track=inherit,direct" is nonsense and should be rejected
>
> * currently "--track" has "last one wins" behavior so
>    "--track=inherit --track=direct" behaves like "--track=direct". We
>    should probably keep that so that "--track=fetch --track=direct"
>    behaves like "--track=direct", not "--track=fetch,direct"
>
> * if "git fetch" fails and the remote tracking ref already exists then
>    we should print a warning and carry on rather than dying which is more
>    convenient if the user or remote server are offline.
>
> * "git checkout --track=fetch origin/branch" should respect
>    remote.origin.fetch so that we fetch the ref that we're going to
>    checkout. I wonder if we can share this logic with the code that
>    sets the upstream branch.
>
> * "git checkout --track=fetch origin" should only fetch the remote
>    ref that we're going to checkout, not all the refs from origin. i.e.
>    it should read origin/HEAD to work out what to fetch.
>
> Thanks
>
> Phillip
>
Harald Nordgren via GitGitGadgetJun 18, 2026, 12:44 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v14 0/2] checkout: --track=fetch

Extend checkout --track with a fetch mode to refresh start-point.
Changes in v14:
 * Handle .h files in a better way.
Changes in v13:
 * Create a preparatory commit that exposes find_tracking_remote_for_ref()
   and advise_ambiguous_fetch_refspec() from branch.c, so checkout can reuse
   the same lookup git branch --track uses.
 * Use advise_ambiguous_fetch_refspec() for the "multiple remotes match"
   case, so the wording matches git branch --track.
Harald Nordgren (2):
  branch: expose helpers for finding the remote owning a tracking ref
  checkout: extend --track with a "fetch" mode to refresh start-point
 Documentation/git-checkout.adoc |  17 +-
 Documentation/git-switch.adoc   |   5 +-
 branch.c                        |  96 ++++++-----
 branch.h                        |  16 ++
 builtin/checkout.c              | 139 +++++++++++++++-
 t/t7201-co.sh                   | 276 ++++++++++++++++++++++++++++++++
 6 files changed, 498 insertions(+), 51 deletions(-)
base-commit: 4621f8ce5e9b97aa2e8d0d9ffe9d25df2471074d
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v14
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v14
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v13:
 1:  2369afad24 ! 1:  f79689c23d branch: expose helpers for finding the remote owning a tracking ref
     @@ branch.h
       #define BRANCH_H
       
      +#include "refspec.h"
     -+#include "string-list.h"
      +
     ++struct string_list;
       struct repository;
       struct strbuf;
       
 2:  60adf0e67d ! 2:  8518f090b1 checkout: extend --track with a "fetch" mode to refresh start-point
     @@ builtin/checkout.c
      +#include "run-command.h"
       #include "sequencer.h"
       #include "setup.h"
     - #include "strvec.h"
     + #include "sparse-index.h"
      @@ builtin/checkout.c: struct checkout_opts {
       	int count_checkout_paths;
       	int overlay_mode;
-- 
gitgitgadget
Harald Nordgren via GitGitGadgetJun 18, 2026, 12:44 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v14 1/2] branch: expose helpers for finding the remote owning a tracking ref

From: Harald Nordgren <haraldnordgren@gmail.com>

The remote-lookup that setup_tracking() does is useful outside branch.c too; for example, deciding which remote to "git fetch" from given a remote-tracking ref.

Move 'struct tracking' to branch.h and add two helpers backed by the existing for_each_remote walk: find_tracking_remote_for_ref() and advise_ambiguous_fetch_refspec(). setup_tracking() uses both. No behavior change.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
 branch.c | 96 ++++++++++++++++++++++++++++++--------------------------
 branch.h | 16 ++++++++++
 2 files changed, 68 insertions(+), 44 deletions(-)
Show changes to 2 files +68 −44

branch.c, branch.h

diff --git a/branch.c b/branch.c
index 243db7d0fc..46ae7f0035 100644
--- a/branch.c
+++ b/branch.c
@@ -20,16 +20,9 @@
 #include "run-command.h"
 #include "strmap.h"
 
-struct tracking {
-	struct refspec_item spec;
-	struct string_list *srcs;
-	const char *remote;
-	int matches;
-};
-
 struct find_tracked_branch_cb {
 	struct tracking *tracking;
-	struct string_list ambiguous_remotes;
+	struct string_list *ambiguous_remotes;
 };
 
 static int find_tracked_branch(struct remote *remote, void *priv)
@@ -45,10 +38,10 @@ static int find_tracked_branch(struct remote *remote, void *priv)
 			break;
 		case 2:
 			/* there are at least two remotes; backfill the first one */
-			string_list_append(&ftb->ambiguous_remotes, tracking->remote);
+			string_list_append(ftb->ambiguous_remotes, tracking->remote);
 			/* fall through */
 		default:
-			string_list_append(&ftb->ambiguous_remotes, remote->name);
+			string_list_append(ftb->ambiguous_remotes, remote->name);
 			free(tracking->spec.src);
 			string_list_clear(tracking->srcs, 0);
 		break;
@@ -59,6 +52,51 @@ static int find_tracked_branch(struct remote *remote, void *priv)
 	return 0;
 }
 
+void find_tracking_remote_for_ref(struct tracking *tracking,
+				  struct string_list *ambiguous_remotes)
+{
+	struct find_tracked_branch_cb ftb_cb = {
+		.tracking = tracking,
+		.ambiguous_remotes = ambiguous_remotes,
+	};
+
+	for_each_remote(find_tracked_branch, &ftb_cb);
+}
+
+void advise_ambiguous_fetch_refspec(const char *dst,
+				    const struct string_list *ambiguous_remotes)
+{
+	struct strbuf remotes_advice = STRBUF_INIT;
+	struct string_list_item *item;
+
+	if (!advice_enabled(ADVICE_AMBIGUOUS_FETCH_REFSPEC))
+		return;
+
+	for_each_string_list_item(item, ambiguous_remotes)
+		/*
+		 * TRANSLATORS: This is a line listing a remote with duplicate
+		 * refspecs in the advice message below. For RTL languages you'll
+		 * probably want to swap the "%s" and leading "  " space around.
+		 */
+		strbuf_addf(&remotes_advice, _("  %s\n"), item->string);
+
+	/*
+	 * TRANSLATORS: The second argument is a \n-delimited list of
+	 * duplicate refspecs, composed above.
+	 */
+	advise(_("There are multiple remotes whose fetch refspecs map to the remote\n"
+		 "tracking ref '%s':\n"
+		 "%s"
+		 "\n"
+		 "This is typically a configuration error.\n"
+		 "\n"
+		 "To support setting up tracking branches, ensure that\n"
+		 "different remotes' fetch refspecs map into different\n"
+		 "tracking namespaces."), dst,
+	       remotes_advice.buf);
+	strbuf_release(&remotes_advice);
+}
+
 static int should_setup_rebase(const char *origin)
 {
 	switch (autorebase) {
@@ -254,11 +292,8 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 {
 	struct tracking tracking;
 	struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
+	struct string_list ambiguous_remotes = STRING_LIST_INIT_DUP;
 	int config_flags = quiet ? 0 : BRANCH_CONFIG_VERBOSE;
-	struct find_tracked_branch_cb ftb_cb = {
-		.tracking = &tracking,
-		.ambiguous_remotes = STRING_LIST_INIT_DUP,
-	};
 
 	if (!track)
 		BUG("asked to set up tracking, but tracking is disallowed");
@@ -267,7 +302,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 	tracking.spec.dst = (char *)orig_ref;
 	tracking.srcs = &tracking_srcs;
 	if (track != BRANCH_TRACK_INHERIT)
-		for_each_remote(find_tracked_branch, &ftb_cb);
+		find_tracking_remote_for_ref(&tracking, &ambiguous_remotes);
 	else if (inherit_tracking(&tracking, orig_ref))
 		goto cleanup;
 
@@ -293,34 +328,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 	if (tracking.matches > 1) {
 		int status = die_message(_("not tracking: ambiguous information for ref '%s'"),
 					    orig_ref);
-		if (advice_enabled(ADVICE_AMBIGUOUS_FETCH_REFSPEC)) {
-			struct strbuf remotes_advice = STRBUF_INIT;
-			struct string_list_item *item;
-
-			for_each_string_list_item(item, &ftb_cb.ambiguous_remotes)
-				/*
-				 * TRANSLATORS: This is a line listing a remote with duplicate
-				 * refspecs in the advice message below. For RTL languages you'll
-				 * probably want to swap the "%s" and leading "  " space around.
-				 */
-				strbuf_addf(&remotes_advice, _("  %s\n"), item->string);
-
-			/*
-			 * TRANSLATORS: The second argument is a \n-delimited list of
-			 * duplicate refspecs, composed above.
-			 */
-			advise(_("There are multiple remotes whose fetch refspecs map to the remote\n"
-				 "tracking ref '%s':\n"
-				 "%s"
-				 "\n"
-				 "This is typically a configuration error.\n"
-				 "\n"
-				 "To support setting up tracking branches, ensure that\n"
-				 "different remotes' fetch refspecs map into different\n"
-				 "tracking namespaces."), orig_ref,
-			       remotes_advice.buf);
-			strbuf_release(&remotes_advice);
-		}
+		advise_ambiguous_fetch_refspec(orig_ref, &ambiguous_remotes);
 		exit(status);
 	}
 
@@ -347,7 +355,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 
 cleanup:
 	string_list_clear(&tracking_srcs, 0);
-	string_list_clear(&ftb_cb.ambiguous_remotes, 0);
+	string_list_clear(&ambiguous_remotes, 0);
 }
 
 int read_branch_desc(struct strbuf *buf, const char *branch_name)
diff --git a/branch.h b/branch.h
index 3dc6e2a0ff..c2e6725491 100644
--- a/branch.h
+++ b/branch.h
@@ -1,9 +1,25 @@
 #ifndef BRANCH_H
 #define BRANCH_H
 
+#include "refspec.h"
+
+struct string_list;
 struct repository;
 struct strbuf;
 
+struct tracking {
+	struct refspec_item spec;
+	struct string_list *srcs;
+	const char *remote;
+	int matches;
+};
+
+void find_tracking_remote_for_ref(struct tracking *tracking,
+				  struct string_list *ambiguous_remotes);
+
+void advise_ambiguous_fetch_refspec(const char *dst,
+				    const struct string_list *ambiguous_remotes);
+
 enum branch_track {
 	BRANCH_TRACK_UNSPECIFIED = -1,
 	BRANCH_TRACK_NEVER = 0,
-- 
gitgitgadget
Harald Nordgren via GitGitGadgetJun 18, 2026, 12:44 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v14 2/2] checkout: extend --track with a "fetch" mode to refresh start-point

From: Harald Nordgren <haraldnordgren@gmail.com>

Add a "fetch" mode to the "--track" option of "git checkout" / "git switch" that refreshes <start-point> before checking it out:

    git checkout -b new_branch --track=fetch origin/some-branch
is shorthand for
    git fetch origin some-branch
    git checkout -b new_branch --track origin/some-branch

Identify the remote whose configured fetch refspec maps to <start-point> using find_tracking_remote_for_ref() (the same lookup "--track" uses to pick which remote to record in branch.<name>.remote), then run "git fetch <remote> <src-ref>" for just that ref so other remote-tracking branches are left untouched. When <start-point> is a bare <remote> (e.g. "origin"), follow refs/remotes/<remote>/HEAD to learn which branch to refresh. If "git fetch" fails but the remote-tracking ref already exists locally, warn and proceed from the existing tip; otherwise abort.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
 Documentation/git-checkout.adoc |  17 +-
 Documentation/git-switch.adoc   |   5 +-
 builtin/checkout.c              | 139 +++++++++++++++-
 t/t7201-co.sh                   | 276 ++++++++++++++++++++++++++++++++
 4 files changed, 430 insertions(+), 7 deletions(-)
Show changes to 4 files +430 −7

Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh

diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index a8b3b8c2e2..20b6cae60e 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -158,11 +158,26 @@ of it").
 	resets _<branch>_ to the start point instead of failing.
 
 `-t`::
-`--track[=(direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration. See
 	`--track` in linkgit:git-branch[1] for details. As a convenience,
 	--track without -b implies branch creation.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare _<remote>_ (e.g. `origin`), the
+branch named by _<remote>/HEAD_ is updated, and the checkout fails
+with a hint to configure that symref if it is not set. The checkout
+also fails if no configured remote's fetch refspec maps to
+_<start-point>_, or if more than one does (in which case the `fetch`
+cannot be unambiguously routed). If the fetch itself fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the checkout proceeds from the existing tip; otherwise the checkout
+is aborted.
++
 If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index d6c4f229a5..a8730b1da8 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -155,10 +155,11 @@ variable.
 	attached to a terminal, regardless of `--quiet`.
 
 `-t`::
-`--track[ (direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration.
 	`-c` is implied. See `--track` in linkgit:git-branch[1] for
-	details.
+	details, and `--track` in linkgit:git-checkout[1] for the
+	`fetch` mode.
 +
 If no `-c` option is given, the name of the new branch will be derived
 from the remote-tracking branch, by looking at the local part of the
diff --git a/builtin/checkout.c b/builtin/checkout.c
index b78b3a1d16..37caceaefd 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -25,10 +25,12 @@
 #include "preload-index.h"
 #include "read-cache.h"
 #include "refs.h"
+#include "refspec.h"
 #include "remote.h"
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "sequencer.h"
 #include "setup.h"
 #include "sparse-index.h"
@@ -63,6 +65,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -116,6 +119,129 @@ struct branch_info {
 	char *checkout;
 };
 
+static void fetch_remote_for_start_point(const char *arg, int quiet)
+{
+	struct strbuf dst = STRBUF_INIT;
+	struct tracking tracking;
+	struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
+	struct string_list ambiguous_remotes = STRING_LIST_INIT_DUP;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+	struct object_id oid;
+	struct remote *named_remote;
+	int bare_ns;
+
+	strbuf_addf(&dst, "refs/remotes/%s", arg);
+	if (check_refname_format(dst.buf, 0))
+		die(_("cannot fetch start-point '%s': not a valid "
+		      "remote-tracking name"), arg);
+
+	named_remote = remote_get(arg);
+	bare_ns = !strchr(arg, '/') ||
+		(named_remote && remote_is_configured(named_remote, 1));
+	if (bare_ns) {
+		char *head_path = xstrfmt("refs/remotes/%s/HEAD", arg);
+		const char *head_target =
+			refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
+						head_path,
+						RESOLVE_REF_READING |
+						RESOLVE_REF_NO_RECURSE,
+						&oid, NULL);
+		if (head_target &&
+		    starts_with(head_target, dst.buf) &&
+		    head_target[dst.len] == '/' &&
+		    !check_refname_format(head_target, 0)) {
+			strbuf_reset(&dst);
+			strbuf_addstr(&dst, head_target);
+			bare_ns = 0;
+		}
+		free(head_path);
+	}
+
+	memset(&tracking, 0, sizeof(tracking));
+	tracking.spec.dst = dst.buf;
+	tracking.srcs = &tracking_srcs;
+	find_tracking_remote_for_ref(&tracking, &ambiguous_remotes);
+
+	if (tracking.matches > 1) {
+		int status = die_message(_("cannot fetch start-point '%s': "
+					   "fetch refspecs of multiple remotes "
+					   "map to '%s'"), arg, dst.buf);
+		advise_ambiguous_fetch_refspec(dst.buf, &ambiguous_remotes);
+		exit(status);
+	}
+
+	if (!tracking.matches) {
+		if (bare_ns && named_remote &&
+		    remote_is_configured(named_remote, 1))
+			die(_("cannot fetch start-point '%s': "
+			      "'refs/remotes/%s/HEAD' is not set; run "
+			      "'git remote set-head %s --auto' to set it"),
+			    arg, arg, arg);
+		die(_("cannot fetch start-point '%s': no configured remote's "
+		      "fetch refspec matches it"), arg);
+	}
+
+	strvec_push(&cmd.args, "fetch");
+	if (quiet)
+		strvec_push(&cmd.args, "--quiet");
+	strvec_pushl(&cmd.args, tracking.remote,
+		     tracking_srcs.items[0].string, NULL);
+	cmd.git_cmd = 1;
+	if (run_command(&cmd)) {
+		if (!refs_read_ref(get_main_ref_store(the_repository),
+				   dst.buf, &oid))
+			warning(_("failed to fetch start-point '%s'; "
+				  "using existing '%s'"), arg, dst.buf);
+		else
+			die(_("failed to fetch start-point '%s'"), arg);
+	}
+
+	string_list_clear(&tracking_srcs, 0);
+	string_list_clear(&ambiguous_remotes, 0);
+	strbuf_release(&dst);
+}
+
+static int parse_opt_checkout_track(const struct option *opt,
+				    const char *arg, int unset)
+{
+	struct checkout_opts *opts = opt->value;
+	struct string_list tokens = STRING_LIST_INIT_DUP;
+	struct string_list_item *item;
+	int saw_direct = 0;
+	int ret = 0;
+
+	opts->fetch = 0;
+	if (unset) {
+		opts->track = BRANCH_TRACK_NEVER;
+		return 0;
+	}
+	opts->track = BRANCH_TRACK_EXPLICIT;
+	if (!arg)
+		return 0;
+
+	string_list_split(&tokens, arg, ",", -1);
+	for_each_string_list_item(item, &tokens) {
+		if (!strcmp(item->string, "fetch"))
+			opts->fetch = 1;
+		else if (!strcmp(item->string, "direct"))
+			saw_direct = 1;
+		else if (!strcmp(item->string, "inherit"))
+			opts->track = BRANCH_TRACK_INHERIT;
+		else {
+			ret = error(_("option `%s' expects \"%s\", \"%s\", "
+				      "or \"%s\""),
+				    "--track", "direct", "inherit", "fetch");
+			goto out;
+		}
+	}
+	if (saw_direct && opts->track == BRANCH_TRACK_INHERIT)
+		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
+			    "--track", "direct", "inherit");
+out:
+	string_list_clear(&tokens, 0);
+	return ret;
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1786,10 +1912,10 @@ static struct option *add_common_switch_branch_options(
 {
 	struct option options[] = {
 		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
-		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
+		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
 			N_("set branch tracking configuration"),
 			PARSE_OPT_OPTARG,
-			parse_opt_tracking_mode),
+			parse_opt_checkout_track),
 		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
@@ -1994,8 +2120,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0], opts->quiet);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 7613b1d2a4..1e321b1512 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -870,4 +870,280 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --track=fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
+	test_cmp_config fetch_upstream branch.local_new.remote &&
+	test_cmp_config refs/heads/fetch_new branch.local_new.merge
+'
+
+test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
+'
+
+test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
+	git checkout main &&
+	git -C fetch_upstream checkout main &&
+	git remote set-head fetch_upstream main &&
+	git -C fetch_upstream checkout -b fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_pre &&
+	git fetch fetch_upstream fetch_unrelated &&
+	unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_main_post &&
+	git -C fetch_upstream checkout fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_post &&
+	git checkout --track=fetch -b local_from_remote fetch_upstream &&
+	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
+'
+
+test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_offline &&
+	test_commit -C fetch_upstream u_offline &&
+	git fetch fetch_upstream fetch_offline &&
+	saved_url=$(git config remote.fetch_upstream.url) &&
+	test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
+	git config remote.fetch_upstream.url ./does-not-exist &&
+	git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
+	test_grep "failed to fetch" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
+'
+
+test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
+	git checkout main &&
+	git remote add fetch_custom ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_custom" &&
+	git config --replace-all remote.fetch_custom.fetch \
+		"+refs/heads/*:refs/remotes/custom-ns/*" &&
+	git -C fetch_upstream checkout -b fetch_refspec &&
+	test_commit -C fetch_upstream u_refspec &&
+	test_must_fail git rev-parse --verify refs/remotes/custom-ns/fetch_refspec &&
+	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
+	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
+'
+
+test_expect_success 'checkout --track=fetch on namespace bare name follows <ns>/HEAD' '
+	git checkout main &&
+	git remote add fetch_ns ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_ns" &&
+	test_when_finished "git update-ref -d refs/remotes/ns_alias/HEAD" &&
+	git config --replace-all remote.fetch_ns.fetch \
+		"+refs/heads/*:refs/remotes/ns_alias/*" &&
+	git fetch fetch_ns &&
+	git symbolic-ref refs/remotes/ns_alias/HEAD refs/remotes/ns_alias/main &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_ns_post &&
+	git checkout --track=fetch -b local_ns ns_alias &&
+	test_cmp_rev refs/remotes/ns_alias/main HEAD &&
+	test_cmp_config fetch_ns branch.local_ns.remote &&
+	test_cmp_config refs/heads/main branch.local_ns.merge
+'
+
+test_expect_success '--track=fetch on bare hierarchical remote name follows <ns>/HEAD' '
+	git checkout main &&
+	git remote add nested/bare ./fetch_upstream &&
+	test_when_finished "git remote remove nested/bare" &&
+	test_when_finished "git update-ref -d refs/remotes/nested/bare/HEAD" &&
+	git fetch nested/bare &&
+	git symbolic-ref refs/remotes/nested/bare/HEAD \
+		refs/remotes/nested/bare/main &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_nested_bare_post &&
+	git checkout --track=fetch -b local_nested_bare nested/bare &&
+	test_cmp_rev refs/remotes/nested/bare/main HEAD
+'
+
+test_expect_success 'checkout --track=fetch handles hierarchical remote name' '
+	git checkout main &&
+	git remote add nested/remote ./fetch_upstream &&
+	test_when_finished "git remote remove nested/remote" &&
+	git -C fetch_upstream checkout -b fetch_hier &&
+	test_commit -C fetch_upstream u_hier &&
+	test_must_fail git rev-parse --verify refs/remotes/nested/remote/fetch_hier &&
+	git checkout --track=fetch -b local_hier nested/remote/fetch_hier &&
+	test_cmp_rev refs/remotes/nested/remote/fetch_hier HEAD
+'
+
+test_expect_success 'checkout --track=fetch dies on bare remote name with no <ns>/HEAD' '
+	git checkout main &&
+	git remote add fetch_nohead ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_nohead" &&
+	test_might_fail git symbolic-ref -d refs/remotes/fetch_nohead/HEAD &&
+	test_must_fail git checkout --track=fetch -b local_nohead fetch_nohead 2>err &&
+	test_grep "refs/remotes/fetch_nohead/HEAD" err &&
+	test_grep "git remote set-head fetch_nohead --auto" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_nohead
+'
+
+test_expect_success 'checkout --track=fetch on bare unknown name does not suggest set-head' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/no_such_ns/HEAD &&
+	test_must_fail git config --get remote.no_such_ns.url &&
+	test_must_fail git checkout --track=fetch -b local_unknown no_such_ns 2>err &&
+	test_grep "no configured remote" err &&
+	test_grep ! "set-head" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_unknown
+'
+
+test_expect_success 'checkout --track=fetch rejects <ns>/HEAD pointing outside namespace' '
+	git checkout main &&
+	git remote add fetch_crossns ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_crossns" &&
+	test_when_finished "git update-ref -d refs/remotes/fetch_crossns/HEAD" &&
+	git fetch fetch_crossns &&
+	git symbolic-ref refs/remotes/fetch_crossns/HEAD \
+		refs/remotes/fetch_upstream/u_main &&
+	test_must_fail git checkout --track=fetch -b local_crossns fetch_crossns 2>err &&
+	test_grep "refs/remotes/fetch_crossns/HEAD" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_crossns
+'
+
+test_expect_success 'checkout --track=fetch dies on ambiguous fetch refspec match' '
+	git checkout main &&
+	git remote add fetch_ambig_a ./fetch_upstream &&
+	git remote add fetch_ambig_b ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_ambig_a" &&
+	test_when_finished "git remote remove fetch_ambig_b" &&
+	git config --replace-all remote.fetch_ambig_a.fetch \
+		"+refs/heads/*:refs/remotes/ambig_ns/*" &&
+	git config --replace-all remote.fetch_ambig_b.fetch \
+		"+refs/heads/*:refs/remotes/ambig_ns/*" &&
+	git -C fetch_upstream checkout -b fetch_ambig &&
+	test_commit -C fetch_upstream u_ambig &&
+	test_must_fail git checkout --track=fetch -b local_ambig ambig_ns/fetch_ambig 2>err &&
+	test_grep "fetch_ambig_a" err &&
+	test_grep "fetch_ambig_b" err &&
+	test_grep "tracking namespaces" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_ambig
+'
+
+test_expect_success 'checkout --track=fetch rejects invalid refname components' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch -b local_invalid "foo..bar" 2>err &&
+	test_grep "valid" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_invalid
+'
+
+test_expect_success 'checkout --track=fetch,inherit rejects invalid refname components' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch,inherit -b local_invalid \
+		"foo..bar" 2>err &&
+	test_grep "valid" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_invalid
+'
+
+test_expect_success 'checkout --track=inherit,direct is rejected' '
+	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
+	test_grep "cannot combine" err
+'
+
+test_expect_success 'checkout --track=direct,inherit is rejected' '
+	test_must_fail git checkout --track=direct,inherit -b bad fetch_upstream/fetch_new 2>err &&
+	test_grep "cannot combine" err
+'
+
+test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_lastwin &&
+	test_commit -C fetch_upstream u_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
+	test_must_fail git checkout --track=fetch --track=direct \
+		-b local_lastwin fetch_upstream/fetch_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
+'
+
+test_expect_success 'checkout --track=fetch then --no-track drops fetch' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_notrack &&
+	test_commit -C fetch_upstream u_notrack &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack &&
+	test_must_fail git checkout --track=fetch --no-track \
+		-b local_notrack fetch_upstream/fetch_notrack &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack
+'
+
+test_expect_success 'checkout --track=fetch,inherit fetches remote-tracking start-point' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_inherit &&
+	git checkout --track=fetch,inherit -b local_inherit \
+		fetch_upstream/fetch_inherit &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD
+'
+
+test_expect_success 'checkout --track=fetch,inherit errors when start-point does not map to a remote' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch,inherit -b bad main 2>err &&
+	test_grep "no configured remote" err &&
+	test_must_fail git rev-parse --verify refs/heads/bad
+'
+
+test_expect_success 'checkout --track=fetch on local start-point errors' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch -b bad main 2>err &&
+	test_grep "no configured remote" err &&
+	test_must_fail git rev-parse --verify refs/heads/bad
+'
+
+test_expect_success 'checkout --track=bogus reports an error' '
+	git checkout main &&
+	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
+	test_grep "expects" err
+'
+
+test_expect_success 'checkout -q --track=fetch silences the fetch output' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_quiet &&
+	test_commit -C fetch_upstream u_quiet &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_quiet &&
+	git checkout -q --track=fetch -b local_quiet \
+		fetch_upstream/fetch_quiet 2>err &&
+	test_grep ! "-> fetch_upstream/fetch_quiet" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_quiet HEAD
+'
+
+test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done
-- 
gitgitgadget
D. Ben KnobleJun 18, 2026, 17:47 UTC in reply to Harald Nordgren on lore

Re: [PATCH] checkout: add --fetch to fetch remote before resolving start-point

Hi Harald,

On Thu, Jun 18, 2026 at 8:36 AM Harald Nordgren <haraldnordgren@gmail.com> wrote:

Show 7 quoted lines
>
> Hi Ben!
>
> Trying to shore up some support for this topic. How do you feel about this now?
>
>
> Harald

I haven't followed the series too closely; it sounds like the code is in decent shape.

I stand by my thought that this could be convenient, but that's not much one way or another in terms of how it fits in overall with Git's vision.

There are some conveniences I recommend universally. This one requires caveats, as pointed out by others, depending on the project, so… from that point of view I wonder if keeping "fetch + switch" as 2 distinct steps is better? I truly don't know.

-- 
D. Ben Knoble
Phillip WoodJun 23, 2026, 13:49 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH v14 2/2] checkout: extend --track with a "fetch" mode to refresh start-point

Hi Harald
On 18/06/2026 13:44, Harald Nordgren via GitGitGadget wrote:
Show 21 quoted lines
> From: Harald Nordgren <haraldnordgren@gmail.com>
> 
> Add a "fetch" mode to the "--track" option of "git checkout" / "git
> switch" that refreshes <start-point> before checking it out:
> 
>      git checkout -b new_branch --track=fetch origin/some-branch
> 
> is shorthand for
> 
>      git fetch origin some-branch
>      git checkout -b new_branch --track origin/some-branch
> 
> Identify the remote whose configured fetch refspec maps to
> <start-point> using find_tracking_remote_for_ref() (the same lookup
> "--track" uses to pick which remote to record in
> branch.<name>.remote), then run "git fetch <remote> <src-ref>" for
> just that ref so other remote-tracking branches are left untouched.
> When <start-point> is a bare <remote> (e.g. "origin"), follow
> refs/remotes/<remote>/HEAD to learn which branch to refresh. If
> "git fetch" fails but the remote-tracking ref already exists locally,
> warn and proceed from the existing tip; otherwise abort.

This describes the feature well, but does not really explain why it is convenient to have a shorthand for "git fetch ... && git checkout -b ...". For example if the reason is that in a fast-moving project you want to start your new work off the latest upstream changes to minimize the chance of merge conflicts or duplicated work it would be useful to say that. As Junio has said the implementation looks pretty solid I've left a few comments below, but the important thing to do first is to convince others that this is a useful feature and why it is worth blurring the separation between fetch and checkout. You can do that without sending a new version.

Show 28 quoted lines
> diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
> index a8b3b8c2e2..20b6cae60e 100644
> --- a/Documentation/git-checkout.adoc
> +++ b/Documentation/git-checkout.adoc
> @@ -158,11 +158,26 @@ of it").
>   	resets _<branch>_ to the start point instead of failing.
>   
>   `-t`::
> -`--track[=(direct|inherit)]`::
> +`--track[=(direct|inherit|fetch)[,...]]`::
>   	When creating a new branch, set up "upstream" configuration. See
>   	`--track` in linkgit:git-branch[1] for details. As a convenience,
>   	--track without -b implies branch creation.
>   +
> +The argument is a comma-separated list. `direct` (the default) and
> +`inherit` select the tracking mode and are mutually exclusive. Adding
> +`fetch` requests that the remote be fetched before _<start-point>_ is
> +resolved, so the new branch starts from a fresh tip: when
> +_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
> +updated; when _<start-point>_ is a bare _<remote>_ (e.g. `origin`), the
> +branch named by _<remote>/HEAD_ is updated, and the checkout fails
> +with a hint to configure that symref if it is not set. The checkout
> +also fails if no configured remote's fetch refspec maps to
> +_<start-point>_, or if more than one does (in which case the `fetch`
> +cannot be unambiguously routed). If the fetch itself fails and the
> +corresponding remote-tracking ref already exists, a warning is printed
> +and the checkout proceeds from the existing tip; otherwise the checkout
> +is aborted.
Nicely explained
Show 26 quoted lines
> +static void fetch_remote_for_start_point(const char *arg, int quiet)
> +{
> +	struct strbuf dst = STRBUF_INIT;
> +	struct tracking tracking;
> +	struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
> +	struct string_list ambiguous_remotes = STRING_LIST_INIT_DUP;
> +	struct child_process cmd = CHILD_PROCESS_INIT;
> +	struct object_id oid;
> +	struct remote *named_remote;
> +	int bare_ns;
> +
> +	strbuf_addf(&dst, "refs/remotes/%s", arg);
> +	if (check_refname_format(dst.buf, 0))
> +		die(_("cannot fetch start-point '%s': not a valid "
> +		      "remote-tracking name"), arg);
> +
> +	named_remote = remote_get(arg);
> +	bare_ns = !strchr(arg, '/') ||
> +		(named_remote && remote_is_configured(named_remote, 1));
> +	if (bare_ns) {
> +		char *head_path = xstrfmt("refs/remotes/%s/HEAD", arg);
> +		const char *head_target =
> +			refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
> +						head_path,
> +						RESOLVE_REF_READING |
> +						RESOLVE_REF_NO_RECURSE,

Why do we use RESOLVE_REF_NO_RECURSE here? This should match whatever "git checkout -b <remote>" does.

Show 5 quoted lines
> +						&oid, NULL);
> +		if (head_target &&
> +		    starts_with(head_target, dst.buf) &&
> +		    head_target[dst.len] == '/' &&
> +		    !check_refname_format(head_target, 0)) {

I don't think there is any need to call check_refname_format() here - you're using the result of reading a ref, not some untrusted input.

Show 8 quoted lines
> +			strbuf_reset(&dst);
> +			strbuf_addstr(&dst, head_target);
> +			bare_ns = 0;
> +		}
> +		free(head_path);
> +	}
> +
> +	memset(&tracking, 0, sizeof(tracking));

When you want to zero initialize a stack variable it is easier, clearer and less error-prone to initialize it by adding "= {0};" where it is declared.

Show 18 quoted lines
> +	tracking.spec.dst = dst.buf;
> +	tracking.srcs = &tracking_srcs;
> +	find_tracking_remote_for_ref(&tracking, &ambiguous_remotes);
> +
> +	if (tracking.matches > 1) {
> +		int status = die_message(_("cannot fetch start-point '%s': "
> +					   "fetch refspecs of multiple remotes "
> +					   "map to '%s'"), arg, dst.buf);
> +		advise_ambiguous_fetch_refspec(dst.buf, &ambiguous_remotes);
> +		exit(status);
> +	}
> +
> +	if (!tracking.matches) {
> +		if (bare_ns && named_remote &&
> +		    remote_is_configured(named_remote, 1))
> +			die(_("cannot fetch start-point '%s': "
> +			      "'refs/remotes/%s/HEAD' is not set; run "
> +			      "'git remote set-head %s --auto' to set it")

This is quite a long message for a single line - breaking the line and putting the suggested command on a separate line would make it clearer. Something like

cannot fetch start-point 'origin' because 'refs/remotes/origin/HEAD' does not exist. To create it run

     git remote set-head origin --auto
Show 14 quoted lines
> +			    arg, arg, arg);
> +		die(_("cannot fetch start-point '%s': no configured remote's "
> +		      "fetch refspec matches it"), arg);
> +	}
> +
> +	strvec_push(&cmd.args, "fetch");
> +	if (quiet)
> +		strvec_push(&cmd.args, "--quiet");
> +	strvec_pushl(&cmd.args, tracking.remote,
> +		     tracking_srcs.items[0].string, NULL);
> +	cmd.git_cmd = 1;
> +	if (run_command(&cmd)) {
> +		if (!refs_read_ref(get_main_ref_store(the_repository),
> +				   dst.buf, &oid))

You can use refs_ref_exists() to check a ref exists which avoids declaring "oid" which we're not interested in here.

Show 47 quoted lines
> +			warning(_("failed to fetch start-point '%s'; "
> +				  "using existing '%s'"), arg, dst.buf);
> +		else
> +			die(_("failed to fetch start-point '%s'"), arg);
> +	}
> +
> +	string_list_clear(&tracking_srcs, 0);
> +	string_list_clear(&ambiguous_remotes, 0);
> +	strbuf_release(&dst);
> +}
> +
> +static int parse_opt_checkout_track(const struct option *opt,
> +				    const char *arg, int unset)
> +{
> +	struct checkout_opts *opts = opt->value;
> +	struct string_list tokens = STRING_LIST_INIT_DUP;
> +	struct string_list_item *item;
> +	int saw_direct = 0;
> +	int ret = 0;
> +
> +	opts->fetch = 0;
> +	if (unset) {
> +		opts->track = BRANCH_TRACK_NEVER;
> +		return 0;
> +	}
> +	opts->track = BRANCH_TRACK_EXPLICIT;
> +	if (!arg)
> +		return 0;
> +
> +	string_list_split(&tokens, arg, ",", -1);
> +	for_each_string_list_item(item, &tokens) {
> +		if (!strcmp(item->string, "fetch"))
> +			opts->fetch = 1;
> +		else if (!strcmp(item->string, "direct"))
> +			saw_direct = 1;
> +		else if (!strcmp(item->string, "inherit"))
> +			opts->track = BRANCH_TRACK_INHERIT;
> +		else {
> +			ret = error(_("option `%s' expects \"%s\", \"%s\", "
> +				      "or \"%s\""),
> +				    "--track", "direct", "inherit", "fetch");
> +			goto out;
> +		}
> +	}
> +	if (saw_direct && opts->track == BRANCH_TRACK_INHERIT)
> +		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
> +			    "--track", "direct", "inherit");
This parsing looks good
Show 7 quoted lines
> diff --git a/t/t7201-co.sh b/t/t7201-co.sh
> index 7613b1d2a4..1e321b1512 100755
> --- a/t/t7201-co.sh
> +++ b/t/t7201-co.sh
> @@ -870,4 +870,280 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
>   	test_cmp_config "" --default "" branch.main2.merge
>   '

I've not read the tests in detail but there seem to be an awful lot of them. We only need to test each thing once so for example if we test

     git checkout --track=fetch -b <remote-ref>

with a fetch refspec, that maps refs/heads/*:refs/remotes/origin/xxx/* then we don't need to test it without that refspec. I notice you use "namespace" below with is confusing because it is not referring to the feature described in the gitnamespaces(7) man page.

Try and avoid
     test $a = $b

as it makes it hard to debug failing tests. Instead I think you can use test_cmp_rev in this case.

Thanks
Phillip
Show 277 quoted lines
> +test_expect_success 'setup upstream for --track=fetch tests' '
> +	git checkout main &&
> +	git init fetch_upstream &&
> +	test_commit -C fetch_upstream u_main &&
> +	git remote add fetch_upstream fetch_upstream &&
> +	git fetch fetch_upstream &&
> +	git -C fetch_upstream checkout -b fetch_new &&
> +	test_commit -C fetch_upstream u_new
> +'
> +
> +test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
> +	git checkout main &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
> +	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
> +	test_cmp_config fetch_upstream branch.local_new.remote &&
> +	test_cmp_config refs/heads/fetch_new branch.local_new.merge
> +'
> +
> +test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_target &&
> +	test_commit -C fetch_upstream u_target_pre &&
> +	git -C fetch_upstream checkout -b fetch_other &&
> +	test_commit -C fetch_upstream u_other_pre &&
> +	git fetch fetch_upstream &&
> +	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
> +	git -C fetch_upstream checkout fetch_target &&
> +	test_commit -C fetch_upstream u_target_post &&
> +	git -C fetch_upstream checkout fetch_other &&
> +	test_commit -C fetch_upstream u_other_post &&
> +	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
> +	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
> +'
> +
> +test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout main &&
> +	git remote set-head fetch_upstream main &&
> +	git -C fetch_upstream checkout -b fetch_unrelated &&
> +	test_commit -C fetch_upstream u_unrelated_pre &&
> +	git fetch fetch_upstream fetch_unrelated &&
> +	unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
> +	git -C fetch_upstream checkout main &&
> +	test_commit -C fetch_upstream u_main_post &&
> +	git -C fetch_upstream checkout fetch_unrelated &&
> +	test_commit -C fetch_upstream u_unrelated_post &&
> +	git checkout --track=fetch -b local_from_remote fetch_upstream &&
> +	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
> +	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
> +'
> +
> +test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
> +	git checkout main &&
> +	test_might_fail git branch -D bogus &&
> +	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
> +	test_must_fail git rev-parse --verify refs/heads/bogus
> +'
> +
> +test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_offline &&
> +	test_commit -C fetch_upstream u_offline &&
> +	git fetch fetch_upstream fetch_offline &&
> +	saved_url=$(git config remote.fetch_upstream.url) &&
> +	test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
> +	git config remote.fetch_upstream.url ./does-not-exist &&
> +	git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
> +	test_grep "failed to fetch" err &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
> +'
> +
> +test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
> +	git checkout main &&
> +	git remote add fetch_custom ./fetch_upstream &&
> +	test_when_finished "git remote remove fetch_custom" &&
> +	git config --replace-all remote.fetch_custom.fetch \
> +		"+refs/heads/*:refs/remotes/custom-ns/*" &&
> +	git -C fetch_upstream checkout -b fetch_refspec &&
> +	test_commit -C fetch_upstream u_refspec &&
> +	test_must_fail git rev-parse --verify refs/remotes/custom-ns/fetch_refspec &&
> +	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
> +	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
> +'
> +
> +test_expect_success 'checkout --track=fetch on namespace bare name follows <ns>/HEAD' '
> +	git checkout main &&
> +	git remote add fetch_ns ./fetch_upstream &&
> +	test_when_finished "git remote remove fetch_ns" &&
> +	test_when_finished "git update-ref -d refs/remotes/ns_alias/HEAD" &&
> +	git config --replace-all remote.fetch_ns.fetch \
> +		"+refs/heads/*:refs/remotes/ns_alias/*" &&
> +	git fetch fetch_ns &&
> +	git symbolic-ref refs/remotes/ns_alias/HEAD refs/remotes/ns_alias/main &&
> +	git -C fetch_upstream checkout main &&
> +	test_commit -C fetch_upstream u_ns_post &&
> +	git checkout --track=fetch -b local_ns ns_alias &&
> +	test_cmp_rev refs/remotes/ns_alias/main HEAD &&
> +	test_cmp_config fetch_ns branch.local_ns.remote &&
> +	test_cmp_config refs/heads/main branch.local_ns.merge
> +'
> +
> +test_expect_success '--track=fetch on bare hierarchical remote name follows <ns>/HEAD' '
> +	git checkout main &&
> +	git remote add nested/bare ./fetch_upstream &&
> +	test_when_finished "git remote remove nested/bare" &&
> +	test_when_finished "git update-ref -d refs/remotes/nested/bare/HEAD" &&
> +	git fetch nested/bare &&
> +	git symbolic-ref refs/remotes/nested/bare/HEAD \
> +		refs/remotes/nested/bare/main &&
> +	git -C fetch_upstream checkout main &&
> +	test_commit -C fetch_upstream u_nested_bare_post &&
> +	git checkout --track=fetch -b local_nested_bare nested/bare &&
> +	test_cmp_rev refs/remotes/nested/bare/main HEAD
> +'
> +
> +test_expect_success 'checkout --track=fetch handles hierarchical remote name' '
> +	git checkout main &&
> +	git remote add nested/remote ./fetch_upstream &&
> +	test_when_finished "git remote remove nested/remote" &&
> +	git -C fetch_upstream checkout -b fetch_hier &&
> +	test_commit -C fetch_upstream u_hier &&
> +	test_must_fail git rev-parse --verify refs/remotes/nested/remote/fetch_hier &&
> +	git checkout --track=fetch -b local_hier nested/remote/fetch_hier &&
> +	test_cmp_rev refs/remotes/nested/remote/fetch_hier HEAD
> +'
> +
> +test_expect_success 'checkout --track=fetch dies on bare remote name with no <ns>/HEAD' '
> +	git checkout main &&
> +	git remote add fetch_nohead ./fetch_upstream &&
> +	test_when_finished "git remote remove fetch_nohead" &&
> +	test_might_fail git symbolic-ref -d refs/remotes/fetch_nohead/HEAD &&
> +	test_must_fail git checkout --track=fetch -b local_nohead fetch_nohead 2>err &&
> +	test_grep "refs/remotes/fetch_nohead/HEAD" err &&
> +	test_grep "git remote set-head fetch_nohead --auto" err &&
> +	test_must_fail git rev-parse --verify refs/heads/local_nohead
> +'
> +
> +test_expect_success 'checkout --track=fetch on bare unknown name does not suggest set-head' '
> +	git checkout main &&
> +	test_must_fail git rev-parse --verify refs/remotes/no_such_ns/HEAD &&
> +	test_must_fail git config --get remote.no_such_ns.url &&
> +	test_must_fail git checkout --track=fetch -b local_unknown no_such_ns 2>err &&
> +	test_grep "no configured remote" err &&
> +	test_grep ! "set-head" err &&
> +	test_must_fail git rev-parse --verify refs/heads/local_unknown
> +'
> +
> +test_expect_success 'checkout --track=fetch rejects <ns>/HEAD pointing outside namespace' '
> +	git checkout main &&
> +	git remote add fetch_crossns ./fetch_upstream &&
> +	test_when_finished "git remote remove fetch_crossns" &&
> +	test_when_finished "git update-ref -d refs/remotes/fetch_crossns/HEAD" &&
> +	git fetch fetch_crossns &&
> +	git symbolic-ref refs/remotes/fetch_crossns/HEAD \
> +		refs/remotes/fetch_upstream/u_main &&
> +	test_must_fail git checkout --track=fetch -b local_crossns fetch_crossns 2>err &&
> +	test_grep "refs/remotes/fetch_crossns/HEAD" err &&
> +	test_must_fail git rev-parse --verify refs/heads/local_crossns
> +'
> +
> +test_expect_success 'checkout --track=fetch dies on ambiguous fetch refspec match' '
> +	git checkout main &&
> +	git remote add fetch_ambig_a ./fetch_upstream &&
> +	git remote add fetch_ambig_b ./fetch_upstream &&
> +	test_when_finished "git remote remove fetch_ambig_a" &&
> +	test_when_finished "git remote remove fetch_ambig_b" &&
> +	git config --replace-all remote.fetch_ambig_a.fetch \
> +		"+refs/heads/*:refs/remotes/ambig_ns/*" &&
> +	git config --replace-all remote.fetch_ambig_b.fetch \
> +		"+refs/heads/*:refs/remotes/ambig_ns/*" &&
> +	git -C fetch_upstream checkout -b fetch_ambig &&
> +	test_commit -C fetch_upstream u_ambig &&
> +	test_must_fail git checkout --track=fetch -b local_ambig ambig_ns/fetch_ambig 2>err &&
> +	test_grep "fetch_ambig_a" err &&
> +	test_grep "fetch_ambig_b" err &&
> +	test_grep "tracking namespaces" err &&
> +	test_must_fail git rev-parse --verify refs/heads/local_ambig
> +'
> +
> +test_expect_success 'checkout --track=fetch rejects invalid refname components' '
> +	git checkout main &&
> +	test_must_fail git checkout --track=fetch -b local_invalid "foo..bar" 2>err &&
> +	test_grep "valid" err &&
> +	test_must_fail git rev-parse --verify refs/heads/local_invalid
> +'
> +
> +test_expect_success 'checkout --track=fetch,inherit rejects invalid refname components' '
> +	git checkout main &&
> +	test_must_fail git checkout --track=fetch,inherit -b local_invalid \
> +		"foo..bar" 2>err &&
> +	test_grep "valid" err &&
> +	test_must_fail git rev-parse --verify refs/heads/local_invalid
> +'
> +
> +test_expect_success 'checkout --track=inherit,direct is rejected' '
> +	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
> +	test_grep "cannot combine" err
> +'
> +
> +test_expect_success 'checkout --track=direct,inherit is rejected' '
> +	test_must_fail git checkout --track=direct,inherit -b bad fetch_upstream/fetch_new 2>err &&
> +	test_grep "cannot combine" err
> +'
> +
> +test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_lastwin &&
> +	test_commit -C fetch_upstream u_lastwin &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
> +	test_must_fail git checkout --track=fetch --track=direct \
> +		-b local_lastwin fetch_upstream/fetch_lastwin &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
> +'
> +
> +test_expect_success 'checkout --track=fetch then --no-track drops fetch' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_notrack &&
> +	test_commit -C fetch_upstream u_notrack &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack &&
> +	test_must_fail git checkout --track=fetch --no-track \
> +		-b local_notrack fetch_upstream/fetch_notrack &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack
> +'
> +
> +test_expect_success 'checkout --track=fetch,inherit fetches remote-tracking start-point' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_inherit &&
> +	test_commit -C fetch_upstream u_inherit &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_inherit &&
> +	git checkout --track=fetch,inherit -b local_inherit \
> +		fetch_upstream/fetch_inherit &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD
> +'
> +
> +test_expect_success 'checkout --track=fetch,inherit errors when start-point does not map to a remote' '
> +	git checkout main &&
> +	test_must_fail git checkout --track=fetch,inherit -b bad main 2>err &&
> +	test_grep "no configured remote" err &&
> +	test_must_fail git rev-parse --verify refs/heads/bad
> +'
> +
> +test_expect_success 'checkout --track=fetch on local start-point errors' '
> +	git checkout main &&
> +	test_must_fail git checkout --track=fetch -b bad main 2>err &&
> +	test_grep "no configured remote" err &&
> +	test_must_fail git rev-parse --verify refs/heads/bad
> +'
> +
> +test_expect_success 'checkout --track=bogus reports an error' '
> +	git checkout main &&
> +	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
> +	test_grep "expects" err
> +'
> +
> +test_expect_success 'checkout -q --track=fetch silences the fetch output' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_quiet &&
> +	test_commit -C fetch_upstream u_quiet &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_quiet &&
> +	git checkout -q --track=fetch -b local_quiet \
> +		fetch_upstream/fetch_quiet 2>err &&
> +	test_grep ! "-> fetch_upstream/fetch_quiet" err &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_quiet HEAD
> +'
> +
> +test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
> +	git checkout main &&
> +	git -C fetch_upstream checkout -b fetch_switch &&
> +	test_commit -C fetch_upstream u_switch &&
> +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
> +	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
> +	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
> +'
> +
>   test_done
Harald NordgrenJun 23, 2026, 17:47 UTC in reply to Phillip Wood on lore

Re: [PATCH v14 2/2] checkout: extend --track with a "fetch" mode to refresh start-point

Ok, let's focus on the need for the feature before talking code:

In an active project, forking from "origin/master" without refreshing first often has consequences: you start work that has already been done, or you build on an old version of the code which causes big conflicts only later when you pull. The fix is simple ("git fetch origin master && git checkout -b topic origin/master"), but it is still a mouthful. Other tools exist because this is annoying enough that people automate it.

Consider instead that the cost of a fetch is nothing.

When a new user types "git checkout -b topic origin/master", I assume their mental model is already "start from the LATEST origin/master". The fetch is implicit, automating it matches what they probably already meant.

Harald
On Tue, Jun 23, 2026 at 3:49 PM Phillip Wood <phillip.wood123@gmail.com> wrote:
Show 522 quoted lines
>
> Hi Harald
>
> On 18/06/2026 13:44, Harald Nordgren via GitGitGadget wrote:
> > From: Harald Nordgren <haraldnordgren@gmail.com>
> >
> > Add a "fetch" mode to the "--track" option of "git checkout" / "git
> > switch" that refreshes <start-point> before checking it out:
> >
> >      git checkout -b new_branch --track=fetch origin/some-branch
> >
> > is shorthand for
> >
> >      git fetch origin some-branch
> >      git checkout -b new_branch --track origin/some-branch
> >
> > Identify the remote whose configured fetch refspec maps to
> > <start-point> using find_tracking_remote_for_ref() (the same lookup
> > "--track" uses to pick which remote to record in
> > branch.<name>.remote), then run "git fetch <remote> <src-ref>" for
> > just that ref so other remote-tracking branches are left untouched.
> > When <start-point> is a bare <remote> (e.g. "origin"), follow
> > refs/remotes/<remote>/HEAD to learn which branch to refresh. If
> > "git fetch" fails but the remote-tracking ref already exists locally,
> > warn and proceed from the existing tip; otherwise abort.
>
> This describes the feature well, but does not really explain why it is
> convenient to have a shorthand for "git fetch ... && git checkout -b
> ...". For example if the reason is that in a fast-moving project you
> want to start your new work off the latest upstream changes to minimize
> the chance of merge conflicts or duplicated work it would be useful to
> say that. As Junio has said the implementation looks pretty solid I've
> left a few comments below, but the important thing to do first is to
> convince others that this is a useful feature and why it is worth
> blurring the separation between fetch and checkout. You can do that
> without sending a new version.
>
> > diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
> > index a8b3b8c2e2..20b6cae60e 100644
> > --- a/Documentation/git-checkout.adoc
> > +++ b/Documentation/git-checkout.adoc
> > @@ -158,11 +158,26 @@ of it").
> >       resets _<branch>_ to the start point instead of failing.
> >
> >   `-t`::
> > -`--track[=(direct|inherit)]`::
> > +`--track[=(direct|inherit|fetch)[,...]]`::
> >       When creating a new branch, set up "upstream" configuration. See
> >       `--track` in linkgit:git-branch[1] for details. As a convenience,
> >       --track without -b implies branch creation.
> >   +
> > +The argument is a comma-separated list. `direct` (the default) and
> > +`inherit` select the tracking mode and are mutually exclusive. Adding
> > +`fetch` requests that the remote be fetched before _<start-point>_ is
> > +resolved, so the new branch starts from a fresh tip: when
> > +_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
> > +updated; when _<start-point>_ is a bare _<remote>_ (e.g. `origin`), the
> > +branch named by _<remote>/HEAD_ is updated, and the checkout fails
> > +with a hint to configure that symref if it is not set. The checkout
> > +also fails if no configured remote's fetch refspec maps to
> > +_<start-point>_, or if more than one does (in which case the `fetch`
> > +cannot be unambiguously routed). If the fetch itself fails and the
> > +corresponding remote-tracking ref already exists, a warning is printed
> > +and the checkout proceeds from the existing tip; otherwise the checkout
> > +is aborted.
>
> Nicely explained
>
> > +static void fetch_remote_for_start_point(const char *arg, int quiet)
> > +{
> > +     struct strbuf dst = STRBUF_INIT;
> > +     struct tracking tracking;
> > +     struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
> > +     struct string_list ambiguous_remotes = STRING_LIST_INIT_DUP;
> > +     struct child_process cmd = CHILD_PROCESS_INIT;
> > +     struct object_id oid;
> > +     struct remote *named_remote;
> > +     int bare_ns;
> > +
> > +     strbuf_addf(&dst, "refs/remotes/%s", arg);
> > +     if (check_refname_format(dst.buf, 0))
> > +             die(_("cannot fetch start-point '%s': not a valid "
> > +                   "remote-tracking name"), arg);
> > +
> > +     named_remote = remote_get(arg);
> > +     bare_ns = !strchr(arg, '/') ||
> > +             (named_remote && remote_is_configured(named_remote, 1));
> > +     if (bare_ns) {
> > +             char *head_path = xstrfmt("refs/remotes/%s/HEAD", arg);
> > +             const char *head_target =
> > +                     refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
> > +                                             head_path,
> > +                                             RESOLVE_REF_READING |
> > +                                             RESOLVE_REF_NO_RECURSE,
>
> Why do we use RESOLVE_REF_NO_RECURSE here? This should match whatever
> "git checkout -b <remote>" does.
>
> > +                                             &oid, NULL);
> > +             if (head_target &&
> > +                 starts_with(head_target, dst.buf) &&
> > +                 head_target[dst.len] == '/' &&
> > +                 !check_refname_format(head_target, 0)) {
>
> I don't think there is any need to call check_refname_format() here -
> you're using the result of reading a ref, not some untrusted input.
>
> > +                     strbuf_reset(&dst);
> > +                     strbuf_addstr(&dst, head_target);
> > +                     bare_ns = 0;
> > +             }
> > +             free(head_path);
> > +     }
> > +
> > +     memset(&tracking, 0, sizeof(tracking));
>
> When you want to zero initialize a stack variable it is easier, clearer
> and less error-prone to initialize it by adding "= {0};" where it is
> declared.
>
> > +     tracking.spec.dst = dst.buf;
> > +     tracking.srcs = &tracking_srcs;
> > +     find_tracking_remote_for_ref(&tracking, &ambiguous_remotes);
> > +
> > +     if (tracking.matches > 1) {
> > +             int status = die_message(_("cannot fetch start-point '%s': "
> > +                                        "fetch refspecs of multiple remotes "
> > +                                        "map to '%s'"), arg, dst.buf);
> > +             advise_ambiguous_fetch_refspec(dst.buf, &ambiguous_remotes);
> > +             exit(status);
> > +     }
> > +
> > +     if (!tracking.matches) {
> > +             if (bare_ns && named_remote &&
> > +                 remote_is_configured(named_remote, 1))
> > +                     die(_("cannot fetch start-point '%s': "
> > +                           "'refs/remotes/%s/HEAD' is not set; run "
> > +                           "'git remote set-head %s --auto' to set it")
>
> This is quite a long message for a single line - breaking the line and
> putting the suggested command on a separate line would make it clearer.
> Something like
>
> cannot fetch start-point 'origin' because 'refs/remotes/origin/HEAD'
> does not exist. To create it run
>
>      git remote set-head origin --auto
>
> > +                         arg, arg, arg);
> > +             die(_("cannot fetch start-point '%s': no configured remote's "
> > +                   "fetch refspec matches it"), arg);
> > +     }
> > +
> > +     strvec_push(&cmd.args, "fetch");
> > +     if (quiet)
> > +             strvec_push(&cmd.args, "--quiet");
> > +     strvec_pushl(&cmd.args, tracking.remote,
> > +                  tracking_srcs.items[0].string, NULL);
> > +     cmd.git_cmd = 1;
> > +     if (run_command(&cmd)) {
> > +             if (!refs_read_ref(get_main_ref_store(the_repository),
> > +                                dst.buf, &oid))
>
> You can use refs_ref_exists() to check a ref exists which avoids
> declaring "oid" which we're not interested in here.
>
> > +                     warning(_("failed to fetch start-point '%s'; "
> > +                               "using existing '%s'"), arg, dst.buf);
> > +             else
> > +                     die(_("failed to fetch start-point '%s'"), arg);
> > +     }
> > +
> > +     string_list_clear(&tracking_srcs, 0);
> > +     string_list_clear(&ambiguous_remotes, 0);
> > +     strbuf_release(&dst);
> > +}
> > +
> > +static int parse_opt_checkout_track(const struct option *opt,
> > +                                 const char *arg, int unset)
> > +{
> > +     struct checkout_opts *opts = opt->value;
> > +     struct string_list tokens = STRING_LIST_INIT_DUP;
> > +     struct string_list_item *item;
> > +     int saw_direct = 0;
> > +     int ret = 0;
> > +
> > +     opts->fetch = 0;
> > +     if (unset) {
> > +             opts->track = BRANCH_TRACK_NEVER;
> > +             return 0;
> > +     }
> > +     opts->track = BRANCH_TRACK_EXPLICIT;
> > +     if (!arg)
> > +             return 0;
> > +
> > +     string_list_split(&tokens, arg, ",", -1);
> > +     for_each_string_list_item(item, &tokens) {
> > +             if (!strcmp(item->string, "fetch"))
> > +                     opts->fetch = 1;
> > +             else if (!strcmp(item->string, "direct"))
> > +                     saw_direct = 1;
> > +             else if (!strcmp(item->string, "inherit"))
> > +                     opts->track = BRANCH_TRACK_INHERIT;
> > +             else {
> > +                     ret = error(_("option `%s' expects \"%s\", \"%s\", "
> > +                                   "or \"%s\""),
> > +                                 "--track", "direct", "inherit", "fetch");
> > +                     goto out;
> > +             }
> > +     }
> > +     if (saw_direct && opts->track == BRANCH_TRACK_INHERIT)
> > +             ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
> > +                         "--track", "direct", "inherit");
>
> This parsing looks good
> > diff --git a/t/t7201-co.sh b/t/t7201-co.sh
> > index 7613b1d2a4..1e321b1512 100755
> > --- a/t/t7201-co.sh
> > +++ b/t/t7201-co.sh
> > @@ -870,4 +870,280 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
> >       test_cmp_config "" --default "" branch.main2.merge
> >   '
>
> I've not read the tests in detail but there seem to be an awful lot of
> them. We only need to test each thing once so for example if we test
>
>      git checkout --track=fetch -b <remote-ref>
>
> with a fetch refspec, that maps refs/heads/*:refs/remotes/origin/xxx/*
> then we don't need to test it without that refspec. I notice you use
> "namespace" below with is confusing because it is not referring to the
> feature described in the gitnamespaces(7) man page.
>
> Try and avoid
>
>      test $a = $b
>
> as it makes it hard to debug failing tests. Instead I think you can use
> test_cmp_rev in this case.
>
> Thanks
>
> Phillip
>
> > +test_expect_success 'setup upstream for --track=fetch tests' '
> > +     git checkout main &&
> > +     git init fetch_upstream &&
> > +     test_commit -C fetch_upstream u_main &&
> > +     git remote add fetch_upstream fetch_upstream &&
> > +     git fetch fetch_upstream &&
> > +     git -C fetch_upstream checkout -b fetch_new &&
> > +     test_commit -C fetch_upstream u_new
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
> > +     git checkout main &&
> > +     test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
> > +     git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
> > +     test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
> > +     test_cmp_config fetch_upstream branch.local_new.remote &&
> > +     test_cmp_config refs/heads/fetch_new branch.local_new.merge
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
> > +     git checkout main &&
> > +     git -C fetch_upstream checkout -b fetch_target &&
> > +     test_commit -C fetch_upstream u_target_pre &&
> > +     git -C fetch_upstream checkout -b fetch_other &&
> > +     test_commit -C fetch_upstream u_other_pre &&
> > +     git fetch fetch_upstream &&
> > +     other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
> > +     git -C fetch_upstream checkout fetch_target &&
> > +     test_commit -C fetch_upstream u_target_post &&
> > +     git -C fetch_upstream checkout fetch_other &&
> > +     test_commit -C fetch_upstream u_other_post &&
> > +     git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
> > +     test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
> > +     test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
> > +     git checkout main &&
> > +     git -C fetch_upstream checkout main &&
> > +     git remote set-head fetch_upstream main &&
> > +     git -C fetch_upstream checkout -b fetch_unrelated &&
> > +     test_commit -C fetch_upstream u_unrelated_pre &&
> > +     git fetch fetch_upstream fetch_unrelated &&
> > +     unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
> > +     git -C fetch_upstream checkout main &&
> > +     test_commit -C fetch_upstream u_main_post &&
> > +     git -C fetch_upstream checkout fetch_unrelated &&
> > +     test_commit -C fetch_upstream u_unrelated_post &&
> > +     git checkout --track=fetch -b local_from_remote fetch_upstream &&
> > +     test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
> > +     test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
> > +     git checkout main &&
> > +     test_might_fail git branch -D bogus &&
> > +     test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
> > +     test_must_fail git rev-parse --verify refs/heads/bogus
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
> > +     git checkout main &&
> > +     git -C fetch_upstream checkout -b fetch_offline &&
> > +     test_commit -C fetch_upstream u_offline &&
> > +     git fetch fetch_upstream fetch_offline &&
> > +     saved_url=$(git config remote.fetch_upstream.url) &&
> > +     test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
> > +     git config remote.fetch_upstream.url ./does-not-exist &&
> > +     git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
> > +     test_grep "failed to fetch" err &&
> > +     test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
> > +     git checkout main &&
> > +     git remote add fetch_custom ./fetch_upstream &&
> > +     test_when_finished "git remote remove fetch_custom" &&
> > +     git config --replace-all remote.fetch_custom.fetch \
> > +             "+refs/heads/*:refs/remotes/custom-ns/*" &&
> > +     git -C fetch_upstream checkout -b fetch_refspec &&
> > +     test_commit -C fetch_upstream u_refspec &&
> > +     test_must_fail git rev-parse --verify refs/remotes/custom-ns/fetch_refspec &&
> > +     git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
> > +     test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch on namespace bare name follows <ns>/HEAD' '
> > +     git checkout main &&
> > +     git remote add fetch_ns ./fetch_upstream &&
> > +     test_when_finished "git remote remove fetch_ns" &&
> > +     test_when_finished "git update-ref -d refs/remotes/ns_alias/HEAD" &&
> > +     git config --replace-all remote.fetch_ns.fetch \
> > +             "+refs/heads/*:refs/remotes/ns_alias/*" &&
> > +     git fetch fetch_ns &&
> > +     git symbolic-ref refs/remotes/ns_alias/HEAD refs/remotes/ns_alias/main &&
> > +     git -C fetch_upstream checkout main &&
> > +     test_commit -C fetch_upstream u_ns_post &&
> > +     git checkout --track=fetch -b local_ns ns_alias &&
> > +     test_cmp_rev refs/remotes/ns_alias/main HEAD &&
> > +     test_cmp_config fetch_ns branch.local_ns.remote &&
> > +     test_cmp_config refs/heads/main branch.local_ns.merge
> > +'
> > +
> > +test_expect_success '--track=fetch on bare hierarchical remote name follows <ns>/HEAD' '
> > +     git checkout main &&
> > +     git remote add nested/bare ./fetch_upstream &&
> > +     test_when_finished "git remote remove nested/bare" &&
> > +     test_when_finished "git update-ref -d refs/remotes/nested/bare/HEAD" &&
> > +     git fetch nested/bare &&
> > +     git symbolic-ref refs/remotes/nested/bare/HEAD \
> > +             refs/remotes/nested/bare/main &&
> > +     git -C fetch_upstream checkout main &&
> > +     test_commit -C fetch_upstream u_nested_bare_post &&
> > +     git checkout --track=fetch -b local_nested_bare nested/bare &&
> > +     test_cmp_rev refs/remotes/nested/bare/main HEAD
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch handles hierarchical remote name' '
> > +     git checkout main &&
> > +     git remote add nested/remote ./fetch_upstream &&
> > +     test_when_finished "git remote remove nested/remote" &&
> > +     git -C fetch_upstream checkout -b fetch_hier &&
> > +     test_commit -C fetch_upstream u_hier &&
> > +     test_must_fail git rev-parse --verify refs/remotes/nested/remote/fetch_hier &&
> > +     git checkout --track=fetch -b local_hier nested/remote/fetch_hier &&
> > +     test_cmp_rev refs/remotes/nested/remote/fetch_hier HEAD
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch dies on bare remote name with no <ns>/HEAD' '
> > +     git checkout main &&
> > +     git remote add fetch_nohead ./fetch_upstream &&
> > +     test_when_finished "git remote remove fetch_nohead" &&
> > +     test_might_fail git symbolic-ref -d refs/remotes/fetch_nohead/HEAD &&
> > +     test_must_fail git checkout --track=fetch -b local_nohead fetch_nohead 2>err &&
> > +     test_grep "refs/remotes/fetch_nohead/HEAD" err &&
> > +     test_grep "git remote set-head fetch_nohead --auto" err &&
> > +     test_must_fail git rev-parse --verify refs/heads/local_nohead
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch on bare unknown name does not suggest set-head' '
> > +     git checkout main &&
> > +     test_must_fail git rev-parse --verify refs/remotes/no_such_ns/HEAD &&
> > +     test_must_fail git config --get remote.no_such_ns.url &&
> > +     test_must_fail git checkout --track=fetch -b local_unknown no_such_ns 2>err &&
> > +     test_grep "no configured remote" err &&
> > +     test_grep ! "set-head" err &&
> > +     test_must_fail git rev-parse --verify refs/heads/local_unknown
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch rejects <ns>/HEAD pointing outside namespace' '
> > +     git checkout main &&
> > +     git remote add fetch_crossns ./fetch_upstream &&
> > +     test_when_finished "git remote remove fetch_crossns" &&
> > +     test_when_finished "git update-ref -d refs/remotes/fetch_crossns/HEAD" &&
> > +     git fetch fetch_crossns &&
> > +     git symbolic-ref refs/remotes/fetch_crossns/HEAD \
> > +             refs/remotes/fetch_upstream/u_main &&
> > +     test_must_fail git checkout --track=fetch -b local_crossns fetch_crossns 2>err &&
> > +     test_grep "refs/remotes/fetch_crossns/HEAD" err &&
> > +     test_must_fail git rev-parse --verify refs/heads/local_crossns
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch dies on ambiguous fetch refspec match' '
> > +     git checkout main &&
> > +     git remote add fetch_ambig_a ./fetch_upstream &&
> > +     git remote add fetch_ambig_b ./fetch_upstream &&
> > +     test_when_finished "git remote remove fetch_ambig_a" &&
> > +     test_when_finished "git remote remove fetch_ambig_b" &&
> > +     git config --replace-all remote.fetch_ambig_a.fetch \
> > +             "+refs/heads/*:refs/remotes/ambig_ns/*" &&
> > +     git config --replace-all remote.fetch_ambig_b.fetch \
> > +             "+refs/heads/*:refs/remotes/ambig_ns/*" &&
> > +     git -C fetch_upstream checkout -b fetch_ambig &&
> > +     test_commit -C fetch_upstream u_ambig &&
> > +     test_must_fail git checkout --track=fetch -b local_ambig ambig_ns/fetch_ambig 2>err &&
> > +     test_grep "fetch_ambig_a" err &&
> > +     test_grep "fetch_ambig_b" err &&
> > +     test_grep "tracking namespaces" err &&
> > +     test_must_fail git rev-parse --verify refs/heads/local_ambig
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch rejects invalid refname components' '
> > +     git checkout main &&
> > +     test_must_fail git checkout --track=fetch -b local_invalid "foo..bar" 2>err &&
> > +     test_grep "valid" err &&
> > +     test_must_fail git rev-parse --verify refs/heads/local_invalid
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch,inherit rejects invalid refname components' '
> > +     git checkout main &&
> > +     test_must_fail git checkout --track=fetch,inherit -b local_invalid \
> > +             "foo..bar" 2>err &&
> > +     test_grep "valid" err &&
> > +     test_must_fail git rev-parse --verify refs/heads/local_invalid
> > +'
> > +
> > +test_expect_success 'checkout --track=inherit,direct is rejected' '
> > +     test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
> > +     test_grep "cannot combine" err
> > +'
> > +
> > +test_expect_success 'checkout --track=direct,inherit is rejected' '
> > +     test_must_fail git checkout --track=direct,inherit -b bad fetch_upstream/fetch_new 2>err &&
> > +     test_grep "cannot combine" err
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
> > +     git checkout main &&
> > +     git -C fetch_upstream checkout -b fetch_lastwin &&
> > +     test_commit -C fetch_upstream u_lastwin &&
> > +     test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
> > +     test_must_fail git checkout --track=fetch --track=direct \
> > +             -b local_lastwin fetch_upstream/fetch_lastwin &&
> > +     test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch then --no-track drops fetch' '
> > +     git checkout main &&
> > +     git -C fetch_upstream checkout -b fetch_notrack &&
> > +     test_commit -C fetch_upstream u_notrack &&
> > +     test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack &&
> > +     test_must_fail git checkout --track=fetch --no-track \
> > +             -b local_notrack fetch_upstream/fetch_notrack &&
> > +     test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch,inherit fetches remote-tracking start-point' '
> > +     git checkout main &&
> > +     git -C fetch_upstream checkout -b fetch_inherit &&
> > +     test_commit -C fetch_upstream u_inherit &&
> > +     test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_inherit &&
> > +     git checkout --track=fetch,inherit -b local_inherit \
> > +             fetch_upstream/fetch_inherit &&
> > +     test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch,inherit errors when start-point does not map to a remote' '
> > +     git checkout main &&
> > +     test_must_fail git checkout --track=fetch,inherit -b bad main 2>err &&
> > +     test_grep "no configured remote" err &&
> > +     test_must_fail git rev-parse --verify refs/heads/bad
> > +'
> > +
> > +test_expect_success 'checkout --track=fetch on local start-point errors' '
> > +     git checkout main &&
> > +     test_must_fail git checkout --track=fetch -b bad main 2>err &&
> > +     test_grep "no configured remote" err &&
> > +     test_must_fail git rev-parse --verify refs/heads/bad
> > +'
> > +
> > +test_expect_success 'checkout --track=bogus reports an error' '
> > +     git checkout main &&
> > +     test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
> > +     test_grep "expects" err
> > +'
> > +
> > +test_expect_success 'checkout -q --track=fetch silences the fetch output' '
> > +     git checkout main &&
> > +     git -C fetch_upstream checkout -b fetch_quiet &&
> > +     test_commit -C fetch_upstream u_quiet &&
> > +     test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_quiet &&
> > +     git checkout -q --track=fetch -b local_quiet \
> > +             fetch_upstream/fetch_quiet 2>err &&
> > +     test_grep ! "-> fetch_upstream/fetch_quiet" err &&
> > +     test_cmp_rev refs/remotes/fetch_upstream/fetch_quiet HEAD
> > +'
> > +
> > +test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
> > +     git checkout main &&
> > +     git -C fetch_upstream checkout -b fetch_switch &&
> > +     test_commit -C fetch_upstream u_switch &&
> > +     test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
> > +     git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
> > +     test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
> > +'
> > +
> >   test_done
>
Harald Nordgren via GitGitGadgetJun 24, 2026, 21:54 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v15 0/2] checkout: --track=fetch

Extend checkout --track with a fetch mode to refresh start-point.
Changes in v15:
 * Reword commit message to lead with motivation.
 * Drop RESOLVE_REF_NO_RECURSE so <ns>/HEAD lookup matches what git checkout
   does for the same ref. Drop redundant check_refname_format on a ref we
   just read. Replace memset with brace initializer. Use refs_ref_exists and
   pass NULL for the OID out-params.
 * Split the "set HEAD" error onto its own line via die_message and advise,
   matching the suggested format.
 * Remove 6 redundant tests, replace test $a = $b with test_cmp_rev, and
   rename test titles to avoid "namespace".
Changes in v14:
 * Handle .h files in a better way.
Changes in v13:
 * Create a preparatory commit that exposes find_tracking_remote_for_ref()
   and advise_ambiguous_fetch_refspec() from branch.c, so checkout can reuse
   the same lookup git branch --track uses.
 * Use advise_ambiguous_fetch_refspec() for the "multiple remotes match"
   case, so the wording matches git branch --track.
Harald Nordgren (2):
  branch: expose helpers for finding the remote owning a tracking ref
  checkout: extend --track with a "fetch" mode to refresh start-point
 Documentation/git-checkout.adoc |  17 ++-
 Documentation/git-switch.adoc   |   5 +-
 branch.c                        |  96 +++++++-------
 branch.h                        |  16 +++
 builtin/checkout.c              | 138 +++++++++++++++++++-
 t/t7201-co.sh                   | 222 ++++++++++++++++++++++++++++++++
 6 files changed, 443 insertions(+), 51 deletions(-)
base-commit: ab776a62a78576513ee121424adb19597fbb7613
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2281%2FHaraldNordgren%2Fcheckout-fetch-start-point-v15
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2281/HaraldNordgren/checkout-fetch-start-point-v15
Pull-Request: https://github.com/git/git/pull/2281
Range-diff vs v14:
 1:  f79689c23d = 1:  8139490c36 branch: expose helpers for finding the remote owning a tracking ref
 2:  8518f090b1 ! 2:  b7e387f123 checkout: extend --track with a "fetch" mode to refresh start-point
     @@ Metadata
       ## Commit message ##
          checkout: extend --track with a "fetch" mode to refresh start-point
      
     -    Add a "fetch" mode to the "--track" option of "git checkout" / "git
     -    switch" that refreshes <start-point> before checking it out:
     +    Forking from an existing remote branch without refreshing first often
     +    has consequences: you start work that has already been done, or you
     +    build on an old version of the code which causes big conflicts later
     +    when you pull. The workaround is two commands ("git fetch <remote>
     +    <branch> && git checkout -b <topic> <remote>/<branch>"), and when
     +    the fetch is skipped the checkout silently starts from a stale tip.
      
     -        git checkout -b new_branch --track=fetch origin/some-branch
     +    Users may already expect "<remote>/<branch>" to refer to the latest
     +    tip on the remote. While this blurs the line between fetch and
     +    checkout, git already does this in places where it pays off: "git
     +    clone" fetches and checks out, and "git pull" fetches and merges.
      
     -    is shorthand for
     +    Add a "fetch" mode to "--track" that refreshes <start-point> before
     +    checking it out:
      
     -        git fetch origin some-branch
     -        git checkout -b new_branch --track origin/some-branch
     +        git checkout -b new_branch --track=fetch origin/some-branch
      
     -    Identify the remote whose configured fetch refspec maps to
     -    <start-point> using find_tracking_remote_for_ref() (the same lookup
     -    "--track" uses to pick which remote to record in
     -    branch.<name>.remote), then run "git fetch <remote> <src-ref>" for
     -    just that ref so other remote-tracking branches are left untouched.
     -    When <start-point> is a bare <remote> (e.g. "origin"), follow
     -    refs/remotes/<remote>/HEAD to learn which branch to refresh. If
     -    "git fetch" fails but the remote-tracking ref already exists locally,
     -    warn and proceed from the existing tip; otherwise abort.
     +    Only the requested branch is fetched so other remote-tracking
     +    branches are left untouched. When <start-point> is a bare <remote>
     +    (e.g. "origin"), follow refs/remotes/<remote>/HEAD to learn which
     +    branch to refresh. If "git fetch" fails but the remote-tracking ref
     +    already exists locally, warn and proceed from the existing tip,
     +    otherwise abort.
      
          Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
      
     @@ builtin/checkout.c: struct branch_info {
      +static void fetch_remote_for_start_point(const char *arg, int quiet)
      +{
      +	struct strbuf dst = STRBUF_INIT;
     -+	struct tracking tracking;
     ++	struct tracking tracking = { 0 };
      +	struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
      +	struct string_list ambiguous_remotes = STRING_LIST_INIT_DUP;
      +	struct child_process cmd = CHILD_PROCESS_INIT;
     -+	struct object_id oid;
      +	struct remote *named_remote;
      +	int bare_ns;
      +
     @@ builtin/checkout.c: struct branch_info {
      +		const char *head_target =
      +			refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
      +						head_path,
     -+						RESOLVE_REF_READING |
     -+						RESOLVE_REF_NO_RECURSE,
     -+						&oid, NULL);
     ++						RESOLVE_REF_READING,
     ++						NULL, NULL);
      +		if (head_target &&
      +		    starts_with(head_target, dst.buf) &&
     -+		    head_target[dst.len] == '/' &&
     -+		    !check_refname_format(head_target, 0)) {
     ++		    head_target[dst.len] == '/') {
      +			strbuf_reset(&dst);
      +			strbuf_addstr(&dst, head_target);
      +			bare_ns = 0;
     @@ builtin/checkout.c: struct branch_info {
      +		free(head_path);
      +	}
      +
     -+	memset(&tracking, 0, sizeof(tracking));
      +	tracking.spec.dst = dst.buf;
      +	tracking.srcs = &tracking_srcs;
      +	find_tracking_remote_for_ref(&tracking, &ambiguous_remotes);
     @@ builtin/checkout.c: struct branch_info {
      +
      +	if (!tracking.matches) {
      +		if (bare_ns && named_remote &&
     -+		    remote_is_configured(named_remote, 1))
     -+			die(_("cannot fetch start-point '%s': "
     -+			      "'refs/remotes/%s/HEAD' is not set; run "
     -+			      "'git remote set-head %s --auto' to set it"),
     -+			    arg, arg, arg);
     ++		    remote_is_configured(named_remote, 1)) {
     ++			int status = die_message(_("cannot fetch start-point '%s' "
     ++						   "because 'refs/remotes/%s/HEAD' "
     ++						   "does not exist."), arg, arg);
     ++			advise(_("To create it run\n"
     ++				 "\n"
     ++				 "    git remote set-head %s --auto\n"), arg);
     ++			exit(status);
     ++		}
      +		die(_("cannot fetch start-point '%s': no configured remote's "
      +		      "fetch refspec matches it"), arg);
      +	}
     @@ builtin/checkout.c: struct branch_info {
      +		     tracking_srcs.items[0].string, NULL);
      +	cmd.git_cmd = 1;
      +	if (run_command(&cmd)) {
     -+		if (!refs_read_ref(get_main_ref_store(the_repository),
     -+				   dst.buf, &oid))
     ++		if (refs_ref_exists(get_main_ref_store(the_repository), dst.buf))
      +			warning(_("failed to fetch start-point '%s'; "
      +				  "using existing '%s'"), arg, dst.buf);
      +		else
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	git -C fetch_upstream checkout -b fetch_other &&
      +	test_commit -C fetch_upstream u_other_pre &&
      +	git fetch fetch_upstream &&
     -+	other_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_other) &&
     ++	git update-ref refs/heads/snapshot_other refs/remotes/fetch_upstream/fetch_other &&
      +	git -C fetch_upstream checkout fetch_target &&
      +	test_commit -C fetch_upstream u_target_post &&
      +	git -C fetch_upstream checkout fetch_other &&
      +	test_commit -C fetch_upstream u_other_post &&
      +	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
      +	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
     -+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_other)" = "$other_before"
     ++	test_cmp_rev refs/remotes/fetch_upstream/fetch_other snapshot_other
      +'
      +
      +test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	git -C fetch_upstream checkout -b fetch_unrelated &&
      +	test_commit -C fetch_upstream u_unrelated_pre &&
      +	git fetch fetch_upstream fetch_unrelated &&
     -+	unrelated_before=$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated) &&
     ++	git update-ref refs/heads/snapshot_unrelated \
     ++		refs/remotes/fetch_upstream/fetch_unrelated &&
      +	git -C fetch_upstream checkout main &&
      +	test_commit -C fetch_upstream u_main_post &&
      +	git -C fetch_upstream checkout fetch_unrelated &&
      +	test_commit -C fetch_upstream u_unrelated_post &&
      +	git checkout --track=fetch -b local_from_remote fetch_upstream &&
      +	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
     -+	test "$(git rev-parse refs/remotes/fetch_upstream/fetch_unrelated)" = "$unrelated_before"
     ++	test_cmp_rev refs/remotes/fetch_upstream/fetch_unrelated snapshot_unrelated
      +'
      +
      +test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
      +'
      +
     -+test_expect_success 'checkout --track=fetch on namespace bare name follows <ns>/HEAD' '
     ++test_expect_success 'checkout --track=fetch on bare remote-tracking prefix follows <prefix>/HEAD' '
      +	git checkout main &&
      +	git remote add fetch_ns ./fetch_upstream &&
      +	test_when_finished "git remote remove fetch_ns" &&
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_cmp_config refs/heads/main branch.local_ns.merge
      +'
      +
     -+test_expect_success '--track=fetch on bare hierarchical remote name follows <ns>/HEAD' '
     -+	git checkout main &&
     -+	git remote add nested/bare ./fetch_upstream &&
     -+	test_when_finished "git remote remove nested/bare" &&
     -+	test_when_finished "git update-ref -d refs/remotes/nested/bare/HEAD" &&
     -+	git fetch nested/bare &&
     -+	git symbolic-ref refs/remotes/nested/bare/HEAD \
     -+		refs/remotes/nested/bare/main &&
     -+	git -C fetch_upstream checkout main &&
     -+	test_commit -C fetch_upstream u_nested_bare_post &&
     -+	git checkout --track=fetch -b local_nested_bare nested/bare &&
     -+	test_cmp_rev refs/remotes/nested/bare/main HEAD
     -+'
     -+
     -+test_expect_success 'checkout --track=fetch handles hierarchical remote name' '
     -+	git checkout main &&
     -+	git remote add nested/remote ./fetch_upstream &&
     -+	test_when_finished "git remote remove nested/remote" &&
     -+	git -C fetch_upstream checkout -b fetch_hier &&
     -+	test_commit -C fetch_upstream u_hier &&
     -+	test_must_fail git rev-parse --verify refs/remotes/nested/remote/fetch_hier &&
     -+	git checkout --track=fetch -b local_hier nested/remote/fetch_hier &&
     -+	test_cmp_rev refs/remotes/nested/remote/fetch_hier HEAD
     -+'
     -+
      +test_expect_success 'checkout --track=fetch dies on bare remote name with no <ns>/HEAD' '
      +	git checkout main &&
      +	git remote add fetch_nohead ./fetch_upstream &&
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_must_fail git rev-parse --verify refs/heads/local_unknown
      +'
      +
     -+test_expect_success 'checkout --track=fetch rejects <ns>/HEAD pointing outside namespace' '
     ++test_expect_success 'checkout --track=fetch rejects <ns>/HEAD pointing outside the tracking prefix' '
      +	git checkout main &&
      +	git remote add fetch_crossns ./fetch_upstream &&
      +	test_when_finished "git remote remove fetch_crossns" &&
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_must_fail git rev-parse --verify refs/heads/local_invalid
      +'
      +
     -+test_expect_success 'checkout --track=fetch,inherit rejects invalid refname components' '
     -+	git checkout main &&
     -+	test_must_fail git checkout --track=fetch,inherit -b local_invalid \
     -+		"foo..bar" 2>err &&
     -+	test_grep "valid" err &&
     -+	test_must_fail git rev-parse --verify refs/heads/local_invalid
     -+'
     -+
      +test_expect_success 'checkout --track=inherit,direct is rejected' '
      +	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
      +	test_grep "cannot combine" err
      +'
      +
     -+test_expect_success 'checkout --track=direct,inherit is rejected' '
     -+	test_must_fail git checkout --track=direct,inherit -b bad fetch_upstream/fetch_new 2>err &&
     -+	test_grep "cannot combine" err
     -+'
     -+
      +test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_lastwin &&
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
      +'
      +
     -+test_expect_success 'checkout --track=fetch then --no-track drops fetch' '
     -+	git checkout main &&
     -+	git -C fetch_upstream checkout -b fetch_notrack &&
     -+	test_commit -C fetch_upstream u_notrack &&
     -+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack &&
     -+	test_must_fail git checkout --track=fetch --no-track \
     -+		-b local_notrack fetch_upstream/fetch_notrack &&
     -+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_notrack
     -+'
     -+
      +test_expect_success 'checkout --track=fetch,inherit fetches remote-tracking start-point' '
      +	git checkout main &&
      +	git -C fetch_upstream checkout -b fetch_inherit &&
     @@ t/t7201-co.sh: test_expect_success 'tracking info copied with autoSetupMerge=inh
      +	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD
      +'
      +
     -+test_expect_success 'checkout --track=fetch,inherit errors when start-point does not map to a remote' '
     -+	git checkout main &&
     -+	test_must_fail git checkout --track=fetch,inherit -b bad main 2>err &&
     -+	test_grep "no configured remote" err &&
     -+	test_must_fail git rev-parse --verify refs/heads/bad
     -+'
     -+
      +test_expect_success 'checkout --track=fetch on local start-point errors' '
      +	git checkout main &&
      +	test_must_fail git checkout --track=fetch -b bad main 2>err &&
-- 
gitgitgadget
Harald Nordgren via GitGitGadgetJun 24, 2026, 21:54 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v15 1/2] branch: expose helpers for finding the remote owning a tracking ref

From: Harald Nordgren <haraldnordgren@gmail.com>

The remote-lookup that setup_tracking() does is useful outside branch.c too; for example, deciding which remote to "git fetch" from given a remote-tracking ref.

Move 'struct tracking' to branch.h and add two helpers backed by the existing for_each_remote walk: find_tracking_remote_for_ref() and advise_ambiguous_fetch_refspec(). setup_tracking() uses both. No behavior change.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
 branch.c | 96 ++++++++++++++++++++++++++++++--------------------------
 branch.h | 16 ++++++++++
 2 files changed, 68 insertions(+), 44 deletions(-)
Show changes to 2 files +68 −44

branch.c, branch.h

diff --git a/branch.c b/branch.c
index 243db7d0fc..46ae7f0035 100644
--- a/branch.c
+++ b/branch.c
@@ -20,16 +20,9 @@
 #include "run-command.h"
 #include "strmap.h"
 
-struct tracking {
-	struct refspec_item spec;
-	struct string_list *srcs;
-	const char *remote;
-	int matches;
-};
-
 struct find_tracked_branch_cb {
 	struct tracking *tracking;
-	struct string_list ambiguous_remotes;
+	struct string_list *ambiguous_remotes;
 };
 
 static int find_tracked_branch(struct remote *remote, void *priv)
@@ -45,10 +38,10 @@ static int find_tracked_branch(struct remote *remote, void *priv)
 			break;
 		case 2:
 			/* there are at least two remotes; backfill the first one */
-			string_list_append(&ftb->ambiguous_remotes, tracking->remote);
+			string_list_append(ftb->ambiguous_remotes, tracking->remote);
 			/* fall through */
 		default:
-			string_list_append(&ftb->ambiguous_remotes, remote->name);
+			string_list_append(ftb->ambiguous_remotes, remote->name);
 			free(tracking->spec.src);
 			string_list_clear(tracking->srcs, 0);
 		break;
@@ -59,6 +52,51 @@ static int find_tracked_branch(struct remote *remote, void *priv)
 	return 0;
 }
 
+void find_tracking_remote_for_ref(struct tracking *tracking,
+				  struct string_list *ambiguous_remotes)
+{
+	struct find_tracked_branch_cb ftb_cb = {
+		.tracking = tracking,
+		.ambiguous_remotes = ambiguous_remotes,
+	};
+
+	for_each_remote(find_tracked_branch, &ftb_cb);
+}
+
+void advise_ambiguous_fetch_refspec(const char *dst,
+				    const struct string_list *ambiguous_remotes)
+{
+	struct strbuf remotes_advice = STRBUF_INIT;
+	struct string_list_item *item;
+
+	if (!advice_enabled(ADVICE_AMBIGUOUS_FETCH_REFSPEC))
+		return;
+
+	for_each_string_list_item(item, ambiguous_remotes)
+		/*
+		 * TRANSLATORS: This is a line listing a remote with duplicate
+		 * refspecs in the advice message below. For RTL languages you'll
+		 * probably want to swap the "%s" and leading "  " space around.
+		 */
+		strbuf_addf(&remotes_advice, _("  %s\n"), item->string);
+
+	/*
+	 * TRANSLATORS: The second argument is a \n-delimited list of
+	 * duplicate refspecs, composed above.
+	 */
+	advise(_("There are multiple remotes whose fetch refspecs map to the remote\n"
+		 "tracking ref '%s':\n"
+		 "%s"
+		 "\n"
+		 "This is typically a configuration error.\n"
+		 "\n"
+		 "To support setting up tracking branches, ensure that\n"
+		 "different remotes' fetch refspecs map into different\n"
+		 "tracking namespaces."), dst,
+	       remotes_advice.buf);
+	strbuf_release(&remotes_advice);
+}
+
 static int should_setup_rebase(const char *origin)
 {
 	switch (autorebase) {
@@ -254,11 +292,8 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 {
 	struct tracking tracking;
 	struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
+	struct string_list ambiguous_remotes = STRING_LIST_INIT_DUP;
 	int config_flags = quiet ? 0 : BRANCH_CONFIG_VERBOSE;
-	struct find_tracked_branch_cb ftb_cb = {
-		.tracking = &tracking,
-		.ambiguous_remotes = STRING_LIST_INIT_DUP,
-	};
 
 	if (!track)
 		BUG("asked to set up tracking, but tracking is disallowed");
@@ -267,7 +302,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 	tracking.spec.dst = (char *)orig_ref;
 	tracking.srcs = &tracking_srcs;
 	if (track != BRANCH_TRACK_INHERIT)
-		for_each_remote(find_tracked_branch, &ftb_cb);
+		find_tracking_remote_for_ref(&tracking, &ambiguous_remotes);
 	else if (inherit_tracking(&tracking, orig_ref))
 		goto cleanup;
 
@@ -293,34 +328,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 	if (tracking.matches > 1) {
 		int status = die_message(_("not tracking: ambiguous information for ref '%s'"),
 					    orig_ref);
-		if (advice_enabled(ADVICE_AMBIGUOUS_FETCH_REFSPEC)) {
-			struct strbuf remotes_advice = STRBUF_INIT;
-			struct string_list_item *item;
-
-			for_each_string_list_item(item, &ftb_cb.ambiguous_remotes)
-				/*
-				 * TRANSLATORS: This is a line listing a remote with duplicate
-				 * refspecs in the advice message below. For RTL languages you'll
-				 * probably want to swap the "%s" and leading "  " space around.
-				 */
-				strbuf_addf(&remotes_advice, _("  %s\n"), item->string);
-
-			/*
-			 * TRANSLATORS: The second argument is a \n-delimited list of
-			 * duplicate refspecs, composed above.
-			 */
-			advise(_("There are multiple remotes whose fetch refspecs map to the remote\n"
-				 "tracking ref '%s':\n"
-				 "%s"
-				 "\n"
-				 "This is typically a configuration error.\n"
-				 "\n"
-				 "To support setting up tracking branches, ensure that\n"
-				 "different remotes' fetch refspecs map into different\n"
-				 "tracking namespaces."), orig_ref,
-			       remotes_advice.buf);
-			strbuf_release(&remotes_advice);
-		}
+		advise_ambiguous_fetch_refspec(orig_ref, &ambiguous_remotes);
 		exit(status);
 	}
 
@@ -347,7 +355,7 @@ static void setup_tracking(const char *new_ref, const char *orig_ref,
 
 cleanup:
 	string_list_clear(&tracking_srcs, 0);
-	string_list_clear(&ftb_cb.ambiguous_remotes, 0);
+	string_list_clear(&ambiguous_remotes, 0);
 }
 
 int read_branch_desc(struct strbuf *buf, const char *branch_name)
diff --git a/branch.h b/branch.h
index 3dc6e2a0ff..c2e6725491 100644
--- a/branch.h
+++ b/branch.h
@@ -1,9 +1,25 @@
 #ifndef BRANCH_H
 #define BRANCH_H
 
+#include "refspec.h"
+
+struct string_list;
 struct repository;
 struct strbuf;
 
+struct tracking {
+	struct refspec_item spec;
+	struct string_list *srcs;
+	const char *remote;
+	int matches;
+};
+
+void find_tracking_remote_for_ref(struct tracking *tracking,
+				  struct string_list *ambiguous_remotes);
+
+void advise_ambiguous_fetch_refspec(const char *dst,
+				    const struct string_list *ambiguous_remotes);
+
 enum branch_track {
 	BRANCH_TRACK_UNSPECIFIED = -1,
 	BRANCH_TRACK_NEVER = 0,
-- 
gitgitgadget
Harald Nordgren via GitGitGadgetJun 24, 2026, 21:54 UTC in reply to Harald Nordgren via GitGitGadget on lore

[PATCH v15 2/2] checkout: extend --track with a "fetch" mode to refresh start-point

From: Harald Nordgren <haraldnordgren@gmail.com>

Forking from an existing remote branch without refreshing first often has consequences: you start work that has already been done, or you build on an old version of the code which causes big conflicts later when you pull. The workaround is two commands ("git fetch <remote> <branch> && git checkout -b <topic> <remote>/<branch>"), and when the fetch is skipped the checkout silently starts from a stale tip.

Users may already expect "<remote>/<branch>" to refer to the latest tip on the remote. While this blurs the line between fetch and checkout, git already does this in places where it pays off: "git clone" fetches and checks out, and "git pull" fetches and merges.

Add a "fetch" mode to "--track" that refreshes <start-point> before checking it out:

    git checkout -b new_branch --track=fetch origin/some-branch

Only the requested branch is fetched so other remote-tracking branches are left untouched. When <start-point> is a bare <remote> (e.g. "origin"), follow refs/remotes/<remote>/HEAD to learn which branch to refresh. If "git fetch" fails but the remote-tracking ref already exists locally, warn and proceed from the existing tip, otherwise abort.

Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
 Documentation/git-checkout.adoc |  17 ++-
 Documentation/git-switch.adoc   |   5 +-
 builtin/checkout.c              | 138 +++++++++++++++++++-
 t/t7201-co.sh                   | 222 ++++++++++++++++++++++++++++++++
 4 files changed, 375 insertions(+), 7 deletions(-)
Show changes to 4 files +375 −7

Documentation/git-checkout.adoc, Documentation/git-switch.adoc, builtin/checkout.c, t/t7201-co.sh

diff --git a/Documentation/git-checkout.adoc b/Documentation/git-checkout.adoc
index a8b3b8c2e2..20b6cae60e 100644
--- a/Documentation/git-checkout.adoc
+++ b/Documentation/git-checkout.adoc
@@ -158,11 +158,26 @@ of it").
 	resets _<branch>_ to the start point instead of failing.
 
 `-t`::
-`--track[=(direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration. See
 	`--track` in linkgit:git-branch[1] for details. As a convenience,
 	--track without -b implies branch creation.
 +
+The argument is a comma-separated list. `direct` (the default) and
+`inherit` select the tracking mode and are mutually exclusive. Adding
+`fetch` requests that the remote be fetched before _<start-point>_ is
+resolved, so the new branch starts from a fresh tip: when
+_<start-point>_ is in _<remote>/<branch>_ form, only that branch is
+updated; when _<start-point>_ is a bare _<remote>_ (e.g. `origin`), the
+branch named by _<remote>/HEAD_ is updated, and the checkout fails
+with a hint to configure that symref if it is not set. The checkout
+also fails if no configured remote's fetch refspec maps to
+_<start-point>_, or if more than one does (in which case the `fetch`
+cannot be unambiguously routed). If the fetch itself fails and the
+corresponding remote-tracking ref already exists, a warning is printed
+and the checkout proceeds from the existing tip; otherwise the checkout
+is aborted.
++
 If no `-b` option is given, the name of the new branch will be
 derived from the remote-tracking branch, by looking at the local part of
 the refspec configured for the corresponding remote, and then stripping
diff --git a/Documentation/git-switch.adoc b/Documentation/git-switch.adoc
index d6c4f229a5..a8730b1da8 100644
--- a/Documentation/git-switch.adoc
+++ b/Documentation/git-switch.adoc
@@ -155,10 +155,11 @@ variable.
 	attached to a terminal, regardless of `--quiet`.
 
 `-t`::
-`--track[ (direct|inherit)]`::
+`--track[=(direct|inherit|fetch)[,...]]`::
 	When creating a new branch, set up "upstream" configuration.
 	`-c` is implied. See `--track` in linkgit:git-branch[1] for
-	details.
+	details, and `--track` in linkgit:git-checkout[1] for the
+	`fetch` mode.
 +
 If no `-c` option is given, the name of the new branch will be derived
 from the remote-tracking branch, by looking at the local part of the
diff --git a/builtin/checkout.c b/builtin/checkout.c
index b78b3a1d16..c6154fbbb0 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -25,10 +25,12 @@
 #include "preload-index.h"
 #include "read-cache.h"
 #include "refs.h"
+#include "refspec.h"
 #include "remote.h"
 #include "repo-settings.h"
 #include "resolve-undo.h"
 #include "revision.h"
+#include "run-command.h"
 #include "sequencer.h"
 #include "setup.h"
 #include "sparse-index.h"
@@ -63,6 +65,7 @@ struct checkout_opts {
 	int count_checkout_paths;
 	int overlay_mode;
 	int dwim_new_local_branch;
+	int fetch;
 	int discard_changes;
 	int accept_ref;
 	int accept_pathspec;
@@ -116,6 +119,128 @@ struct branch_info {
 	char *checkout;
 };
 
+static void fetch_remote_for_start_point(const char *arg, int quiet)
+{
+	struct strbuf dst = STRBUF_INIT;
+	struct tracking tracking = { 0 };
+	struct string_list tracking_srcs = STRING_LIST_INIT_DUP;
+	struct string_list ambiguous_remotes = STRING_LIST_INIT_DUP;
+	struct child_process cmd = CHILD_PROCESS_INIT;
+	struct remote *named_remote;
+	int bare_ns;
+
+	strbuf_addf(&dst, "refs/remotes/%s", arg);
+	if (check_refname_format(dst.buf, 0))
+		die(_("cannot fetch start-point '%s': not a valid "
+		      "remote-tracking name"), arg);
+
+	named_remote = remote_get(arg);
+	bare_ns = !strchr(arg, '/') ||
+		(named_remote && remote_is_configured(named_remote, 1));
+	if (bare_ns) {
+		char *head_path = xstrfmt("refs/remotes/%s/HEAD", arg);
+		const char *head_target =
+			refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
+						head_path,
+						RESOLVE_REF_READING,
+						NULL, NULL);
+		if (head_target &&
+		    starts_with(head_target, dst.buf) &&
+		    head_target[dst.len] == '/') {
+			strbuf_reset(&dst);
+			strbuf_addstr(&dst, head_target);
+			bare_ns = 0;
+		}
+		free(head_path);
+	}
+
+	tracking.spec.dst = dst.buf;
+	tracking.srcs = &tracking_srcs;
+	find_tracking_remote_for_ref(&tracking, &ambiguous_remotes);
+
+	if (tracking.matches > 1) {
+		int status = die_message(_("cannot fetch start-point '%s': "
+					   "fetch refspecs of multiple remotes "
+					   "map to '%s'"), arg, dst.buf);
+		advise_ambiguous_fetch_refspec(dst.buf, &ambiguous_remotes);
+		exit(status);
+	}
+
+	if (!tracking.matches) {
+		if (bare_ns && named_remote &&
+		    remote_is_configured(named_remote, 1)) {
+			int status = die_message(_("cannot fetch start-point '%s' "
+						   "because 'refs/remotes/%s/HEAD' "
+						   "does not exist."), arg, arg);
+			advise(_("To create it run\n"
+				 "\n"
+				 "    git remote set-head %s --auto\n"), arg);
+			exit(status);
+		}
+		die(_("cannot fetch start-point '%s': no configured remote's "
+		      "fetch refspec matches it"), arg);
+	}
+
+	strvec_push(&cmd.args, "fetch");
+	if (quiet)
+		strvec_push(&cmd.args, "--quiet");
+	strvec_pushl(&cmd.args, tracking.remote,
+		     tracking_srcs.items[0].string, NULL);
+	cmd.git_cmd = 1;
+	if (run_command(&cmd)) {
+		if (refs_ref_exists(get_main_ref_store(the_repository), dst.buf))
+			warning(_("failed to fetch start-point '%s'; "
+				  "using existing '%s'"), arg, dst.buf);
+		else
+			die(_("failed to fetch start-point '%s'"), arg);
+	}
+
+	string_list_clear(&tracking_srcs, 0);
+	string_list_clear(&ambiguous_remotes, 0);
+	strbuf_release(&dst);
+}
+
+static int parse_opt_checkout_track(const struct option *opt,
+				    const char *arg, int unset)
+{
+	struct checkout_opts *opts = opt->value;
+	struct string_list tokens = STRING_LIST_INIT_DUP;
+	struct string_list_item *item;
+	int saw_direct = 0;
+	int ret = 0;
+
+	opts->fetch = 0;
+	if (unset) {
+		opts->track = BRANCH_TRACK_NEVER;
+		return 0;
+	}
+	opts->track = BRANCH_TRACK_EXPLICIT;
+	if (!arg)
+		return 0;
+
+	string_list_split(&tokens, arg, ",", -1);
+	for_each_string_list_item(item, &tokens) {
+		if (!strcmp(item->string, "fetch"))
+			opts->fetch = 1;
+		else if (!strcmp(item->string, "direct"))
+			saw_direct = 1;
+		else if (!strcmp(item->string, "inherit"))
+			opts->track = BRANCH_TRACK_INHERIT;
+		else {
+			ret = error(_("option `%s' expects \"%s\", \"%s\", "
+				      "or \"%s\""),
+				    "--track", "direct", "inherit", "fetch");
+			goto out;
+		}
+	}
+	if (saw_direct && opts->track == BRANCH_TRACK_INHERIT)
+		ret = error(_("option `%s' cannot combine \"%s\" and \"%s\""),
+			    "--track", "direct", "inherit");
+out:
+	string_list_clear(&tokens, 0);
+	return ret;
+}
+
 static void branch_info_release(struct branch_info *info)
 {
 	free(info->name);
@@ -1786,10 +1911,10 @@ static struct option *add_common_switch_branch_options(
 {
 	struct option options[] = {
 		OPT_BOOL('d', "detach", &opts->force_detach, N_("detach HEAD at named commit")),
-		OPT_CALLBACK_F('t', "track",  &opts->track, "(direct|inherit)",
+		OPT_CALLBACK_F('t', "track",  opts, "(direct|inherit|fetch)[,...]",
 			N_("set branch tracking configuration"),
 			PARSE_OPT_OPTARG,
-			parse_opt_tracking_mode),
+			parse_opt_checkout_track),
 		OPT__FORCE(&opts->force, N_("force checkout (throw away local modifications)"),
 			   PARSE_OPT_NOCOMPLETE),
 		OPT_STRING(0, "orphan", &opts->new_orphan_branch, N_("new-branch"), N_("new unborn branch")),
@@ -1994,8 +2119,13 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 			opts->dwim_new_local_branch &&
 			opts->track == BRANCH_TRACK_UNSPECIFIED &&
 			!opts->new_branch;
-		int n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
-					     &new_branch_info, opts, &rev);
+		int n;
+
+		if (opts->fetch)
+			fetch_remote_for_start_point(argv[0], opts->quiet);
+
+		n = parse_branchname_arg(argc, argv, dwim_ok, which_command,
+					 &new_branch_info, opts, &rev);
 		argv += n;
 		argc -= n;
 	} else if (!opts->accept_ref && opts->from_treeish) {
diff --git a/t/t7201-co.sh b/t/t7201-co.sh
index 7613b1d2a4..bc0c72c49d 100755
--- a/t/t7201-co.sh
+++ b/t/t7201-co.sh
@@ -870,4 +870,226 @@ test_expect_success 'tracking info copied with autoSetupMerge=inherit' '
 	test_cmp_config "" --default "" branch.main2.merge
 '
 
+test_expect_success 'setup upstream for --track=fetch tests' '
+	git checkout main &&
+	git init fetch_upstream &&
+	test_commit -C fetch_upstream u_main &&
+	git remote add fetch_upstream fetch_upstream &&
+	git fetch fetch_upstream &&
+	git -C fetch_upstream checkout -b fetch_new &&
+	test_commit -C fetch_upstream u_new
+'
+
+test_expect_success 'checkout --track=fetch -b picks up branch created upstream after clone' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_new &&
+	git checkout --track=fetch -b local_new fetch_upstream/fetch_new &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_new HEAD &&
+	test_cmp_config fetch_upstream branch.local_new.remote &&
+	test_cmp_config refs/heads/fetch_new branch.local_new.merge
+'
+
+test_expect_success 'checkout --track=fetch <remote>/<branch> leaves other tracking branches untouched' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_target &&
+	test_commit -C fetch_upstream u_target_pre &&
+	git -C fetch_upstream checkout -b fetch_other &&
+	test_commit -C fetch_upstream u_other_pre &&
+	git fetch fetch_upstream &&
+	git update-ref refs/heads/snapshot_other refs/remotes/fetch_upstream/fetch_other &&
+	git -C fetch_upstream checkout fetch_target &&
+	test_commit -C fetch_upstream u_target_post &&
+	git -C fetch_upstream checkout fetch_other &&
+	test_commit -C fetch_upstream u_other_post &&
+	git checkout --track=fetch -b local_target fetch_upstream/fetch_target &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_target HEAD &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_other snapshot_other
+'
+
+test_expect_success 'checkout --track=fetch with bare remote name fetches only <remote>/HEAD target' '
+	git checkout main &&
+	git -C fetch_upstream checkout main &&
+	git remote set-head fetch_upstream main &&
+	git -C fetch_upstream checkout -b fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_pre &&
+	git fetch fetch_upstream fetch_unrelated &&
+	git update-ref refs/heads/snapshot_unrelated \
+		refs/remotes/fetch_upstream/fetch_unrelated &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_main_post &&
+	git -C fetch_upstream checkout fetch_unrelated &&
+	test_commit -C fetch_upstream u_unrelated_post &&
+	git checkout --track=fetch -b local_from_remote fetch_upstream &&
+	test_cmp_rev refs/remotes/fetch_upstream/main HEAD &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_unrelated snapshot_unrelated
+'
+
+test_expect_success 'checkout --track=fetch aborts and does not create branch when no existing ref' '
+	git checkout main &&
+	test_might_fail git branch -D bogus &&
+	test_must_fail git checkout --track=fetch -b bogus fetch_upstream/does_not_exist &&
+	test_must_fail git rev-parse --verify refs/heads/bogus
+'
+
+test_expect_success 'checkout --track=fetch warns and proceeds when fetch fails but ref exists' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_offline &&
+	test_commit -C fetch_upstream u_offline &&
+	git fetch fetch_upstream fetch_offline &&
+	saved_url=$(git config remote.fetch_upstream.url) &&
+	test_when_finished "git config remote.fetch_upstream.url \"$saved_url\"" &&
+	git config remote.fetch_upstream.url ./does-not-exist &&
+	git checkout --track=fetch -b local_offline fetch_upstream/fetch_offline 2>err &&
+	test_grep "failed to fetch" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_offline HEAD
+'
+
+test_expect_success 'checkout --track=fetch resolves through configured fetch refspec' '
+	git checkout main &&
+	git remote add fetch_custom ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_custom" &&
+	git config --replace-all remote.fetch_custom.fetch \
+		"+refs/heads/*:refs/remotes/custom-ns/*" &&
+	git -C fetch_upstream checkout -b fetch_refspec &&
+	test_commit -C fetch_upstream u_refspec &&
+	test_must_fail git rev-parse --verify refs/remotes/custom-ns/fetch_refspec &&
+	git checkout --track=fetch -b local_refspec custom-ns/fetch_refspec &&
+	test_cmp_rev refs/remotes/custom-ns/fetch_refspec HEAD
+'
+
+test_expect_success 'checkout --track=fetch on bare remote-tracking prefix follows <prefix>/HEAD' '
+	git checkout main &&
+	git remote add fetch_ns ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_ns" &&
+	test_when_finished "git update-ref -d refs/remotes/ns_alias/HEAD" &&
+	git config --replace-all remote.fetch_ns.fetch \
+		"+refs/heads/*:refs/remotes/ns_alias/*" &&
+	git fetch fetch_ns &&
+	git symbolic-ref refs/remotes/ns_alias/HEAD refs/remotes/ns_alias/main &&
+	git -C fetch_upstream checkout main &&
+	test_commit -C fetch_upstream u_ns_post &&
+	git checkout --track=fetch -b local_ns ns_alias &&
+	test_cmp_rev refs/remotes/ns_alias/main HEAD &&
+	test_cmp_config fetch_ns branch.local_ns.remote &&
+	test_cmp_config refs/heads/main branch.local_ns.merge
+'
+
+test_expect_success 'checkout --track=fetch dies on bare remote name with no <ns>/HEAD' '
+	git checkout main &&
+	git remote add fetch_nohead ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_nohead" &&
+	test_might_fail git symbolic-ref -d refs/remotes/fetch_nohead/HEAD &&
+	test_must_fail git checkout --track=fetch -b local_nohead fetch_nohead 2>err &&
+	test_grep "refs/remotes/fetch_nohead/HEAD" err &&
+	test_grep "git remote set-head fetch_nohead --auto" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_nohead
+'
+
+test_expect_success 'checkout --track=fetch on bare unknown name does not suggest set-head' '
+	git checkout main &&
+	test_must_fail git rev-parse --verify refs/remotes/no_such_ns/HEAD &&
+	test_must_fail git config --get remote.no_such_ns.url &&
+	test_must_fail git checkout --track=fetch -b local_unknown no_such_ns 2>err &&
+	test_grep "no configured remote" err &&
+	test_grep ! "set-head" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_unknown
+'
+
+test_expect_success 'checkout --track=fetch rejects <ns>/HEAD pointing outside the tracking prefix' '
+	git checkout main &&
+	git remote add fetch_crossns ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_crossns" &&
+	test_when_finished "git update-ref -d refs/remotes/fetch_crossns/HEAD" &&
+	git fetch fetch_crossns &&
+	git symbolic-ref refs/remotes/fetch_crossns/HEAD \
+		refs/remotes/fetch_upstream/u_main &&
+	test_must_fail git checkout --track=fetch -b local_crossns fetch_crossns 2>err &&
+	test_grep "refs/remotes/fetch_crossns/HEAD" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_crossns
+'
+
+test_expect_success 'checkout --track=fetch dies on ambiguous fetch refspec match' '
+	git checkout main &&
+	git remote add fetch_ambig_a ./fetch_upstream &&
+	git remote add fetch_ambig_b ./fetch_upstream &&
+	test_when_finished "git remote remove fetch_ambig_a" &&
+	test_when_finished "git remote remove fetch_ambig_b" &&
+	git config --replace-all remote.fetch_ambig_a.fetch \
+		"+refs/heads/*:refs/remotes/ambig_ns/*" &&
+	git config --replace-all remote.fetch_ambig_b.fetch \
+		"+refs/heads/*:refs/remotes/ambig_ns/*" &&
+	git -C fetch_upstream checkout -b fetch_ambig &&
+	test_commit -C fetch_upstream u_ambig &&
+	test_must_fail git checkout --track=fetch -b local_ambig ambig_ns/fetch_ambig 2>err &&
+	test_grep "fetch_ambig_a" err &&
+	test_grep "fetch_ambig_b" err &&
+	test_grep "tracking namespaces" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_ambig
+'
+
+test_expect_success 'checkout --track=fetch rejects invalid refname components' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch -b local_invalid "foo..bar" 2>err &&
+	test_grep "valid" err &&
+	test_must_fail git rev-parse --verify refs/heads/local_invalid
+'
+
+test_expect_success 'checkout --track=inherit,direct is rejected' '
+	test_must_fail git checkout --track=inherit,direct -b bad fetch_upstream/fetch_new 2>err &&
+	test_grep "cannot combine" err
+'
+
+test_expect_success 'checkout --track=fetch then --track=direct drops fetch (last-one-wins)' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_lastwin &&
+	test_commit -C fetch_upstream u_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin &&
+	test_must_fail git checkout --track=fetch --track=direct \
+		-b local_lastwin fetch_upstream/fetch_lastwin &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_lastwin
+'
+
+test_expect_success 'checkout --track=fetch,inherit fetches remote-tracking start-point' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_inherit &&
+	test_commit -C fetch_upstream u_inherit &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_inherit &&
+	git checkout --track=fetch,inherit -b local_inherit \
+		fetch_upstream/fetch_inherit &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_inherit HEAD
+'
+
+test_expect_success 'checkout --track=fetch on local start-point errors' '
+	git checkout main &&
+	test_must_fail git checkout --track=fetch -b bad main 2>err &&
+	test_grep "no configured remote" err &&
+	test_must_fail git rev-parse --verify refs/heads/bad
+'
+
+test_expect_success 'checkout --track=bogus reports an error' '
+	git checkout main &&
+	test_must_fail git checkout --track=bogus -b bogus_branch fetch_upstream/fetch_new 2>err &&
+	test_grep "expects" err
+'
+
+test_expect_success 'checkout -q --track=fetch silences the fetch output' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_quiet &&
+	test_commit -C fetch_upstream u_quiet &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_quiet &&
+	git checkout -q --track=fetch -b local_quiet \
+		fetch_upstream/fetch_quiet 2>err &&
+	test_grep ! "-> fetch_upstream/fetch_quiet" err &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_quiet HEAD
+'
+
+test_expect_success 'switch --track=fetch -c picks up branch created upstream after clone' '
+	git checkout main &&
+	git -C fetch_upstream checkout -b fetch_switch &&
+	test_commit -C fetch_upstream u_switch &&
+	test_must_fail git rev-parse --verify refs/remotes/fetch_upstream/fetch_switch &&
+	git switch --track=fetch -c local_switch fetch_upstream/fetch_switch &&
+	test_cmp_rev refs/remotes/fetch_upstream/fetch_switch HEAD
+'
+
 test_done
-- 
gitgitgadget
Junio C HamanoJun 24, 2026, 23:20 UTC in reply to Harald Nordgren on lore

Re: [PATCH v14 2/2] checkout: extend --track with a "fetch" mode to refresh start-point

Harald Nordgren <haraldnordgren@gmail.com> writes:
Show 6 quoted lines
> Ok, let's focus on the need for the feature before talking code:
>
> In an active project, forking from "origin/master" without refreshing
> first often has consequences: you start work that has already been
> done, or you build on an old version of the code which causes big
> conflicts only later when you pull. The fix is simple ...

The above only argues that contributors should not start work on top of a stale codebase without looking at reasonably recent codebase.

I am not sure if automated fetch immediately before forking to start work will be a good fix for that, especially if the fork of a new branch is done blindly _without_ looking at what the updated upstream contains.

> ... ("git fetch
> origin master && git checkout -b topic origin/master"), but it is
> still a mouthful. Other tools exist because this is annoying enough
> that people automate it.
And to actually look at the recent codebase, one would probably need
	git fetch
	git log [-p] ..origin -- your-area-of-interest/
	... other inspection of the recent changes to refresh your
	... understanding of the base code comes here
	git checkout -b topic origin

or something like that. Wouldn't folding the first and the third step into one operation encourage omitting the second step? In a sense, having a tool to let people blindly fetch and fork without looking at what changed recently (i.e., they had a reason to think that what they had was stale, so has a fetch actually resolved that staleness? what new things did the fetch bring in?) may encourage a bad workflow.

An obvious complaint against "update and always inspect and understand" would be "it would slow us down!", but that is why projects encourage forking your topic at a well known release tags, not from a random "tip of the tree of the day".

I think most of the above has already been communicated earlier in discussions before we got to v14, but I may be wrong. Are there any new arguments in support of the feature?

Ben KnobleJun 25, 2026, 01:17 UTC in reply to Junio C Hamano on lore

Re: [PATCH v14 2/2] checkout: extend --track with a "fetch" mode to refresh start-point

Show 39 quoted lines
> Le 24 juin 2026 à 19:20, Junio C Hamano <gitster@pobox.com> a écrit :
> 
> Harald Nordgren <haraldnordgren@gmail.com> writes:
> 
>> Ok, let's focus on the need for the feature before talking code:
>> 
>> In an active project, forking from "origin/master" without refreshing
>> first often has consequences: you start work that has already been
>> done, or you build on an old version of the code which causes big
>> conflicts only later when you pull. The fix is simple ...
> 
> The above only argues that contributors should not start work on top
> of a stale codebase without looking at reasonably recent codebase.
> 
> I am not sure if automated fetch immediately before forking to start
> work will be a good fix for that, especially if the fork of a new
> branch is done blindly _without_ looking at what the updated
> upstream contains.
> 
>> ... ("git fetch
>> origin master && git checkout -b topic origin/master"), but it is
>> still a mouthful. Other tools exist because this is annoying enough
>> that people automate it.
> 
> And to actually look at the recent codebase, one would probably need
> 
>    git fetch
>    git log [-p] ..origin -- your-area-of-interest/
>    ... other inspection of the recent changes to refresh your
>    ... understanding of the base code comes here
>    git checkout -b topic origin
> 
> or something like that.  Wouldn't folding the first and the third
> step into one operation encourage omitting the second step?  In a
> sense, having a tool to let people blindly fetch and fork without
> looking at what changed recently (i.e., they had a reason to think
> that what they had was stale, so has a fetch actually resolved that
> staleness?  what new things did the fetch bring in?) may encourage
> a bad workflow.
I think I remain overall ambivalent, but as anecdata: when I’m working on my employer’scode, it is the default (90%+?) for folks to omit step 2 and have the kind of blind fetch + branch that this would facilitate.
I myself do this when I’m reasonably sure the other changes can’t be of interest (common), or when I suspect the change I’m going to start on will conflict with recent changes I haven’t fetched. At other times I’m more interested in step 2, but generally I omit it at work.
Now, as to why: I spend a lot more time reviewing PRs at work (and making sure they merge quickly when they are in the right direction), and so I’m usually fairly confident of what a fetch is going to bring! [I also fetch several times a day to keep up to date locally, to facilitate various maintenance, admin, and archaeology tasks.] Contrast with distributed open source projects, where I might not have fetched for weeks and can’t predict what might fall out (let alone how it might it interact with local WIP).
So « bad workflow » I agree with, but am plenty guilty of :)
To wrap up, I wonder if the convenience of this proposal is especially aimed at folks like my corporate environment (where « build near the tip and integrate quickly » is the norm), but less than useful for those same folks in a different situation?
(OTOH, I suppose I might use something similar when starting a new topic branch from Git’s master branch, since there’s probably no harm in working on a recent copy of master unless I already have older code that needs updated?)
Show 8 quoted lines
> An obvious complaint against "update and always inspect and
> understand" would be "it would slow us down!", but that is why
> projects encourage forking your topic at a well known release tags,
> not from a random "tip of the tree of the day".
> 
> I think most of the above has already been communicated earlier in
> discussions before we got to v14, but I may be wrong.  Are there any
> new arguments in support of the feature?
Harald NordgrenJun 25, 2026, 08:53 UTC in reply to Ben Knoble on lore

Re: [PATCH v14 2/2] checkout: extend --track with a "fetch" mode to refresh start-point

Hi!

I think you are touching on the critical point here; Git is likely one of the most ordered software projects that exist (I haven't worked on Linux kernel but that's the only one I can imagine is more stringent), and every "real job" I had has been fast-paced and chaotic.

I believe that we must leave the ivory tower and make Git great for the real world.

> I also fetch several times a day to keep up to date locally

I think this is also something that makes you not feel the pain as much. As a technical leader who spends time on reviewing, it gives a more of a aloof/holistic view. And more likely to have already fetched the latest master at any given point. When I worked as an IC, I forked from a stale branch 1000's of times and often felt that pain, I would have wished for this feature.

> So « bad workflow » I agree with, but am plenty guilty of :)

Is it "bad", or is it just a completely normal workflow for 99% of developers? Maybe we should cater to the normal workflow rather than chastising them.

> To wrap up, I wonder if the convenience of this proposal is especially aimed at folks like my corporate environment (where « build near the tip and integrate quickly » is the norm), but less than useful for those same folks in a different situation?
Sure, we can say that, but that's likely 99% of all Git users?
Harald
Harald
Kristofer KarlssonJun 25, 2026, 09:15 UTC in reply to Harald Nordgren on lore

Re: [PATCH v14 2/2] checkout: extend --track with a "fetch" mode to refresh start-point

On Thu, 25 Jun 2026 at 10:54, Harald Nordgren <haraldnordgren@gmail.com> wrote:
Show 11 quoted lines
>
> Hi!
>
> I think you are touching on the critical point here; Git is likely one
> of the most ordered software projects that exist (I haven't worked on
> Linux kernel but that's the only one I can imagine is more stringent),
> and every "real job" I had has been fast-paced and chaotic.
>
> I believe that we must leave the ivory tower and make Git great for
> the real world.
>

I wouldn't call it an ivory tower, but rather a very solid foundation of useful primitives that can be composed and extended by higher level workflows. I think this is a good thing. The git core is kept clean and simple and it provides hooks and tooling to allow for customization.

For the combination of fetch and checkout, it seems easy enough to add as a git alias:

  [alias]
      newtopic = "!f() { git fetch origin master && git checkout -b
\"$1\" FETCH_HEAD; }; f"

I think the usecase is valid, but I think it can be cleanly added on top of git instead of changing git.

- Kristofer
Junio C HamanoJul 23, 2026, 23:48 UTC in reply to Harald Nordgren via GitGitGadget on lore

Re: [PATCH v15 0/2] checkout: --track=fetch

"Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
> Extend checkout --track with a fetch mode to refresh start-point.
> Changes in v15:
>
>  * Reword commit message to lead with motivation.

I was reviewing the draft of the What's Cooking report and noticed that this topic is among a handful of stalled efforts going nowhere.

Show 6 quoted lines
>      +    Forking from an existing remote branch without refreshing first often
>      +    has consequences: you start work that has already been done, or you
>      +    build on an old version of the code which causes big conflicts later
>      +    when you pull. The workaround is two commands ("git fetch <remote>
>      +    <branch> && git checkout -b <topic> <remote>/<branch>"), and when
>      +    the fetch is skipped the checkout silently starts from a stale tip.

Automatically updating the tip of the remote tracking branch also has consequences. It might be fine for the current branch, but it would also make the other branches that forked from the same place go "stale" and without the user realizing (e.g., "git diff @{u}" while they are checked out would show what the user does not expect).

As long as you keep calling this "workaround", I remain skeptical that the merit of this proposal would outweigh its downside. As this topic is about to become more than a month old, let me mark mark the topic to be discarded in my draft of the whats-cooking report.

Back to recent threads