From: Karthik Nayak Date: Thu, 09 Apr 2026 11:55:05 GMT Subject: Re: [PATCH 02/18] setup: stop using `the_repository` in `is_inside_worktree()` Message-ID: In-Reply-To: <20260330-pks-setup-wo-the-repository-v1-2-0d2e822837aa@pks.im> Patrick Steinhardt writes: > The function `is_inside_worktree()` verifies whether or not the current > working directory is located inside the worktree of `the_repository`. > This is done by taking the worktree path and verifying that it's a > prefix of the current working directory. > > This information is cached so that we don't have to re-do this change > multiple times. Furthermore, we proactively set the value in multiple > locations so that we don't even have to perform the check when we have > discovered the repository. > > While we could simply move the caching variable into the repository, the > current layout doesn't really feel sensible in the first place: > > - It can easily lead to false positives or negatives if at any point > in time we may switch the current working directory. > > - We don't call the function in a hot loop, and neither is it overly > expensive to compute. > > Drop the caching infrastructure and instead compute the property ad-hoc > via an injected repository. > I was thinking we could cache the variable as 'static' within the function, but that too would have the staleness issue and require invalidation. So this looks sensible. > Note that there is one small gotcha: we sometimes may end up with > relative directory paths, and if so `is_inside_dir()` might fail. This > wasn't an issue before because of how we proactively set the cached > value during repository discovery. Now that we stop doing that it > becomes a problem though, but it is worked around by resolving the > repository directory via `realpath()`. > Ah! [snip] > -int is_inside_work_tree(void) > +int is_inside_work_tree(struct repository *repo) > { > - if (inside_work_tree < 0) > - inside_work_tree = is_inside_dir(repo_get_work_tree(the_repository)); > - return inside_work_tree; > + static struct strbuf buf = STRBUF_INIT; > + const char *worktree = repo_get_work_tree(repo); > + if (!worktree) > + return 0; > + return is_inside_dir(strbuf_realpath(&buf, worktree, 1)); > } We statically allocate the buf to avoid reallocation. Okay. [snip]