Re: [PATCH 8/8] worktree: simplify search for unique worktree
- From
- Martin Ågren <martin.agren@gmail.com>
- Date
- Sep 10, 2020, 19:48 UTC
- Message-ID
- <CAN0heSrUWiZ_xar3G5rZG-c=8OVp5-eByS6rMXOw9wfTA8kmbA@mail.gmail.com>
- In-Reply-To
- <CAPig+cT_VvOiKBCC=E_P0R8SXkoWPVUxxOOLovOmr8N377YNdQ@mail.gmail.com>
On Thu, 10 Sep 2020 at 21:28, Eric Sunshine <sunshine@sunshineco.com> wrote:
Show 35 quoted lines
>
> On Thu, Sep 10, 2020 at 3:08 PM Martin Ågren <martin.agren@gmail.com> wrote:
> > We track the number of worktrees we've found and break out of the loop
> > early once we hit 2. This is because we're not really interested in the
> > number of matches -- we just want to make sure that we don't find more
> > than one worktree that matches the suffix. This can be done just as well
> > by checking the NULL-ness of the pointer where we collect our
> > answer-to-be. Drop the redundant `nr_found` variable.
> >
> > Signed-off-by: Martin Ågren <martin.agren@gmail.com>
> > ---
> > diff --git a/worktree.c b/worktree.c
> > @@ -172,13 +172,13 @@ static struct worktree *find_worktree_by_suffix(struct worktree **list,
> > const char *suffix)
> > {
> > - for (; *list && nr_found < 2; list++) {
> > + for (; *list; list++) {
> > @@ -186,11 +186,12 @@ static struct worktree *find_worktree_by_suffix(struct worktree **list,
> > if ((!start || (start > 0 && is_dir_sep(path[start - 1]))) &&
> > !fspathcmp(suffix, path + start)) {
> > + if (found)
> > + return NULL;
> > found = *list;
> > - nr_found++;
> > }
> > }
> > - return nr_found == 1 ? found : NULL;
> > + return found;
>
> Although this change appears to be correct and does simplify the code,
> I think it also makes it a bit more opaque. With the explicit
> `nr_found == 1`, it is quite obvious that the function considers
> "success" to be when one and only one entry is found and any other
> number is failure. But with the revised code, it is harder to work out
> precisely what the conditions are.Thanks for commenting. I found the original trickier than it had to be. It spreads out the logic in several places and is careful to short-cut the loop. My first thought was "why doesn't this just use the standard form?". But I'm open to the idea that it might be a fairly personal standard form... If there's any risk that someone else comes along and simplifies this to use a `nr_found` variable, then maybe file this under code churning?
Show 5 quoted lines
> Having said that, I think a simple > comment before the function would suffice to clear up the opaqueness. > Perhaps something like: > > /* If exactly one worktree matches 'target', return it, else NULL. */
That's a good suggestion regardless.
Thanks Martin