findGitRoot function
Find the git root by walking up the directory tree. Looks for a .git directory or file (worktrees/submodules use a file).
Implementation
String? findGitRoot(String startPath) {
if (_gitRootCache.containsKey(startPath)) return _gitRootCache[startPath];
var current = p.absolute(startPath);
final root = p.rootPrefix(current);
while (true) {
try {
final gitPath = p.join(current, '.git');
final stat = FileStat.statSync(gitPath);
if (stat.type == FileSystemEntityType.directory ||
stat.type == FileSystemEntityType.file) {
_gitRootCache[startPath] = current;
return current;
}
} catch (_) {}
final parent = p.dirname(current);
if (parent == current || parent == root) {
// Check root as well
try {
final gitPath = p.join(root, '.git');
final stat = FileStat.statSync(gitPath);
if (stat.type == FileSystemEntityType.directory ||
stat.type == FileSystemEntityType.file) {
_gitRootCache[startPath] = root;
return root;
}
} catch (_) {}
break;
}
current = parent;
}
_gitRootCache[startPath] = null;
return null;
}