resolveCanonicalGitRoot function

String resolveCanonicalGitRoot(
  1. String gitRoot
)

Resolve a git root to the canonical main repository root. For worktrees follows .git file -> gitdir: -> commondir chain.

Implementation

String resolveCanonicalGitRoot(String gitRoot) {
  try {
    final gitFile = File(p.join(gitRoot, '.git'));
    final gitContent = gitFile.readAsStringSync().trim();
    if (!gitContent.startsWith('gitdir:')) return gitRoot;

    final worktreeGitDir = p.normalize(
      p.join(gitRoot, gitContent.substring('gitdir:'.length).trim()),
    );

    final commondirFile = File(p.join(worktreeGitDir, 'commondir'));
    final commonDir = p.normalize(
      p.join(worktreeGitDir, commondirFile.readAsStringSync().trim()),
    );

    // Validate structure matches git worktree add
    if (p.normalize(p.dirname(worktreeGitDir)) !=
        p.join(commonDir, 'worktrees')) {
      return gitRoot;
    }

    // Validate back-link
    try {
      final backlink = File(
        p.join(worktreeGitDir, 'gitdir'),
      ).readAsStringSync().trim();
      final resolvedBacklink = File(backlink).resolveSymbolicLinksSync();
      final resolvedGitRoot = p.join(
        Directory(gitRoot).resolveSymbolicLinksSync(),
        '.git',
      );
      if (resolvedBacklink != resolvedGitRoot) return gitRoot;
    } catch (_) {
      return gitRoot;
    }

    // Bare-repo worktrees: common dir is not inside a working directory.
    if (p.basename(commonDir) != '.git') return commonDir;
    return p.dirname(commonDir);
  } catch (_) {
    return gitRoot;
  }
}