[PATCH 1/3] remote: reject invalid branch names in add -t
- From
Harald Nordgren via GitGitGadget <gitgitgadget@gmail.com>
- Date
- Nov 25, 2026, 18:55 UTC
- Message-ID
- <b829c46707c53095345ae0480e7e82bd83afef02.1795632934.git.gitgitgadget@gmail.com>
- In-Reply-To
- <pull.2429.git.git.1795632934.gitgitgadget@gmail.com>
From: Harald Nordgren <haraldnordgren@gmail.com>
A typo in "git remote add -t", or a shell that expands something unexpected like @{u}, silently produced a fetch refspec that could never match anything, or in some cases outright invalid syntax. Every later fetch from that remote then failed with a confusing error and nothing pointed back at the original mistake.
Check each branch name given to -t before anything is written, so the command fails without creating the remote at all.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com> --- builtin/remote.c | 15 +++++++++++++++ t/t5505-remote.sh | 7 +++++++ 2 files changed, 22 insertions(+)
diff --git a/builtin/remote.c b/builtin/remote.c index de989ea3ba..63d2db39fe 100644 --- a/builtin/remote.c +++ b/builtin/remote.c @@ -123,6 +123,19 @@ enum { #define MIRROR_PUSH 2 #define MIRROR_BOTH (MIRROR_FETCH|MIRROR_PUSH) +static void validate_tracked_branchname(const char *branchname, int mirror) +{ + struct strbuf ref = STRBUF_INIT; + + if (mirror) + strbuf_addf(&ref, "refs/%s", branchname); + else + strbuf_addf(&ref, "refs/heads/%s", branchname); + if (check_refname_format(ref.buf, REFNAME_REFSPEC_PATTERN)) + die(_("'%s' is not a valid branch name"), branchname); + strbuf_release(&ref); +} + static void add_branch(const char *key, const char *branchname, const char *remotename, int mirror, struct strbuf *tmp) { @@ -211,6 +224,8 @@ static int add(int argc, const char **argv, const char *prefix, die(_("specifying a master branch makes no sense with --mirror")); if (mirror && !(mirror & MIRROR_FETCH) && track.nr) die(_("specifying branches to track makes sense only with fetch mirrors")); + for (size_t i = 0; i < track.nr; i++) + validate_tracked_branchname(track.items[i].string, mirror); name = argv[0]; url = argv[1]; diff --git a/t/t5505-remote.sh b/t/t5505-remote.sh index 5fbfcb0848..055fa42e27 100755 --- a/t/t5505-remote.sh +++ b/t/t5505-remote.sh @@ -266,6 +266,13 @@ test_expect_success 'add invalid foreign_vcs remote' ' test_cmp expect actual ' +test_expect_success 'add -t with an invalid branch name' ' + echo "fatal: '\''@{u}'\'' is not a valid branch name" >expect && + test_must_fail git remote add -t "@{u}" badtrack bar 2>actual && + test_cmp expect actual && + test_must_fail git config get remote.badtrack.url +' + test_expect_success 'without subcommand' ' echo origin >expect && git -C test remote >actual &&
-- gitgitgadget