libgit2sharp icon indicating copy to clipboard operation
libgit2sharp copied to clipboard

gitdir

Open vincat77 opened this issue 8 months ago • 1 comments

Problem Description

The Worktree API in LibGit2Sharp does not expose any property to retrieve the actual working directory path associated with a worktree (i.e., the folder where the code is checked out).

Currently, the Worktree object only provides:

  • Name → the name of the worktree (e.g., "core")
  • GitDirectory → the path .git/worktrees/<name>, which does not correspond to the working directory

Due to this limitation, consumers must manually:

  1. Read the content of .git/worktrees/<name>/gitdir
  2. Use Directory.GetParent() to resolve the real worktree folder path

This approach is both fragile and undocumented.

Expected Behavior

Expose a property like Worktree.WorkingDirectory (similar to Repository.Info.WorkingDirectory) that returns the actual working directory path of the worktree (e.g., C:\repo-core).

Example Workaround

var worktreePaths = new List<string>();
var gitDir = Path.Combine(repoPath, ".git", "worktrees");

foreach (var folder in Directory.GetDirectories(gitDir))
{
    var gitdirFile = Path.Combine(folder, "gitdir");
    if (File.Exists(gitdirFile))
    {
        var gitdirPath = File.ReadAllText(gitdirFile).Trim();
        var worktreePath = Directory.GetParent(gitdirPath)?.FullName;
        if (!string.IsNullOrEmpty(worktreePath))
            worktreePaths.Add(worktreePath);
    }
}

This code reads the .git/worktrees/<name>/gitdir file and manually resolves the worktree’s root folder. A native API would make this more reliable and developer-friendly.

vincat77 avatar Apr 25 '25 06:04 vincat77

This is git_worktree_path in libgit2, so this is a LibGit2Sharp issue.

ethomson avatar Jun 06 '25 12:06 ethomson