threads / patch / 52346

patchname-rev: use skip_prefix() instead of starts_with()

Subject: [PATCH] name-rev: use skip_prefix() instead of starts_with()

## tl;dr

2 messages between Nov 26, 2019 and Nov 26, 2019. Diffs are folded; open one to read it.

replies: 1people: 2as markdown or json

René Scharfe· Nov 26, 2019, 15:23 UTC · lore
Let skip_prefix() advance refname to get rid of two magic numbers.
Signed-off-by: René Scharfe <l.s.r@web.de>
---
 builtin/name-rev.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
Show changes to builtin/name-rev.c +2 −5
diff --git a/builtin/name-rev.c b/builtin/name-rev.c
index b0f0776947..c261d661d7 100644
--- a/builtin/name-rev.c
+++ b/builtin/name-rev.c
@@ -161,10 +161,8 @@ static const char *name_ref_abbrev(const char *refname, int shorten_unambiguous)
 {
 	if (shorten_unambiguous)
 		refname = shorten_unambiguous_ref(refname, 0);
-	else if (starts_with(refname, "refs/heads/"))
-		refname = refname + 11;
-	else if (starts_with(refname, "refs/"))
-		refname = refname + 5;
+	else if (!skip_prefix(refname, "refs/heads/", &refname))
+		skip_prefix(refname, "refs/", &refname);
 	return refname;
 }

--
2.24.0
Jeff King· Nov 26, 2019, 16:07 UTC · re: René Scharfe · lore

Re: [PATCH] name-rev: use skip_prefix() instead of starts_with()

On Tue, Nov 26, 2019 at 04:23:31PM +0100, René Scharfe wrote:
Show 15 quoted lines
> diff --git a/builtin/name-rev.c b/builtin/name-rev.c
> index b0f0776947..c261d661d7 100644
> --- a/builtin/name-rev.c
> +++ b/builtin/name-rev.c
> @@ -161,10 +161,8 @@ static const char *name_ref_abbrev(const char *refname, int shorten_unambiguous)
>  {
>  	if (shorten_unambiguous)
>  		refname = shorten_unambiguous_ref(refname, 0);
> -	else if (starts_with(refname, "refs/heads/"))
> -		refname = refname + 11;
> -	else if (starts_with(refname, "refs/"))
> -		refname = refname + 5;
> +	else if (!skip_prefix(refname, "refs/heads/", &refname))
> +		skip_prefix(refname, "refs/", &refname);
>  	return refname;

And this one is correct because we were already mutating the pointer. Good.

Collapsing the conditional makes sense. IMHO it might be a little easier to follow if we keep else-if non-negated, like:

  if (shorten_unambiguous)
         refname = shorten_unambiguous(refname, 0);
  else if (skip_prefix(refname, "refs/heads/", &refname))
         ; /* refname already advanced */
  else
         skip_prefix(refname, "refs/", &refname);
but I'm fine with it either way.

Also, I think we are leaking the result of shorten_unambiguous_refename here (the caller won't free it, as we return a const; but anyway we sometimes return a pointer into the existing const string so it wouldn't be safe). That's all outside your patch, obviously.

-Peff

← back to recent threads