Subject: Re: [PATCH] checkout: fix BUG() case in 9081a421a6

From: Junio C Hamano <[email-masked]>
Date: Fri, 21 Jan 2022 16:33:47 -0800

Ævar Arnfjörð Bjarmason  <[email-masked]> writes:

> diff --git a/builtin/checkout.c b/builtin/checkout.c
> index 6a5dd2a2a22..52a47ef40e1 100644
> --- a/builtin/checkout.c
> +++ b/builtin/checkout.c
> @@ -1090,13 +1090,10 @@ static int switch_branches(const struct checkout_opts *opts,
>  		FREE_AND_NULL(old_branch_info.path);
>  
>  	if (old_branch_info.path) {
> -		const char *const prefix = "refs/heads/";
> -		const char *p;
> -		if (skip_prefix(old_branch_info.path, prefix, &p))
> -			old_branch_info.name = xstrdup(p);
> -		else
> -			BUG("should be able to skip past '%s' in '%s'!",
> -			    prefix, old_branch_info.path);
> +		const char *p = old_branch_info.path;
> +
> +		skip_prefix(old_branch_info.path, "refs/heads/", &p);
> +		old_branch_info.name = xstrdup(p);
>  	}

What we want is a faithful reversion wrt the behaviour, while
keeping the leakfix.

The old code did

	skip_prefix(old_branch_info.path, "refs/heads", &old_branch_info.name);

meaning that old_branch_info.name is left unchanged if .path did not
begin with "refs/heads".

The function that uses old_branch_info.name prepared at this point
in the flow is merge_working_tree(), where it uses .name for the
textual label for the "ancestor" tree.  It is preferrable to have a
branch name, but the code is prepared to see NULL in there, where it
comes up with an abbreviated commit object name.

                o.ancestor = old_branch_info->name;
                if (old_branch_info->name == NULL) {
                        strbuf_add_unique_abbrev(&old_commit_shortname,
                                                 &old_branch_info->commit->object.oid,
                                                 DEFAULT_ABBREV);
                        o.ancestor = old_commit_shortname.buf;
                }

As 9081a421a6 properly 0-initializes old_branch_info, I think it is
sufficient to just drop the "else BUG" clause; we shouldn't have to
copy the .path that does not begin with "refs/heads/" there; .name
member would be NULL in such a case.

I do not care too much about reverting the constant that is only
used once into a literal.  So, how about doing it this way instead?

 builtin/checkout.c | 3 ---
 1 file changed, 3 deletions(-)

diff --git i/builtin/checkout.c w/builtin/checkout.c
index 43d0275187..1fb34d537d 100644
--- i/builtin/checkout.c
+++ w/builtin/checkout.c
@@ -1094,9 +1094,6 @@ static int switch_branches(const struct checkout_opts *opts,
 		const char *p;
 		if (skip_prefix(old_branch_info.path, prefix, &p))
 			old_branch_info.name = xstrdup(p);
-		else
-			BUG("should be able to skip past '%s' in '%s'!",
-			    prefix, old_branch_info.path);
 	}
 
 	if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {