Subject: Re: [PATCH v2 07/11] git-gui: try harder to find worktree from gitdir

From: Mark Levedahl <[email-masked]>
Date: Thu, 21 May 2026 13:45:41 -0400

On 5/21/26 12:55 AM, Shroom Moo wrote:
> On 5/21/26 4:24 AM, Mark Levedahl wrote:
>> +	} elseif [file exists {gitdir}] {
>> +		if {[catch {
>> +			set fd_gitdir [open {gitdir} {r}]
>> +			set gitlink_parent [file dirname [read $fd_gitdir]]
>> +			catch {close $fd_gitdir}
>> +			set worktree [git -C $gitlink_parent rev-parse --show-toplevel]
>> +			set parent_gitdir [git -C $worktree rev-parse --absolute-git-dir]
>> +			if {$::_gitdir ne $parent_gitdir} {
>> +				set worktree {}
>> +			}
>> +		}]} {
>> +			catch {close $fd_gitdir}
>> +			set worktree {}
>> +		}
>> +	}
> There is also an unaddressed issue: 
> In [file exists {gitdir}] and [open {gitdir} r], {gitdir} is a 
> literal string referring to a file named gitdir in the current 
> working directory. However, in the context of a linked worktree 
> (created via git worktree add), the actual file path is 
> $_gitdir/gitdir (e.g., .git/worktrees/<name>/gitdir). While the 
> current working directory could be anywhere (even inside the .git 
> directory), $_gitdir is an absolute path pointing to that worktree's 
> gitdir (e.g., /path/to/main/.git/worktrees/branch). The gitdir file 
> resides within the $_gitdir directory and contains a relative path 
> like ../../.git/worktrees/branch. The current code logic will never 
> locate this file. 
You have to be in the particular worktree's gitdir for this to work. I there exists
    worktrees/foo
    worktrees/frotz
    worktrees/bar
Which would we expore? The code above must be in foo, frotz, bar

The main worktree is found not from worktrees/*, but from the root of the gitdir.
>
> Additionally, [file exists {gitdir}] checks for the gitdir file in 
> the current working directory. Since the function has not yet 
> switched to $_gitdir when this check runs, it is almost impossible 
> to find the file. Consequently, this logic never triggers, preventing 
> linked worktrees from being recognized. 
>
> Maybe the identification of linked worktree should not directly look 
> for the gitdir file, but should check whether there is a.git file and 
> its content points to... /.git/worktrees/... ? Anyways, using the 
> literal {gitdir} to search in the current directory lead to risks. 
>
> Shroom
>
We cannot get to this code if not inside the gitdir, and if the user set GIT_DIR and/or
GIT_WORK_TREE to do something clever, that either worked or the code already threw an
error. git, without GIT_WORK_TREE set, uses the current directory as the worktree, or the
parent directory containing .git. So, we must be inside the gitdir if this code path gets hit.

Mark

Mark