findProjectOrWorkspaceRoot function

Directory findProjectOrWorkspaceRoot([
  1. Directory? startDir
])

Automatically searches for and resolves the project root directory.

Implementation

Directory findProjectOrWorkspaceRoot([Directory? startDir]) {
  final dir = startDir ?? Directory.current;

  // 1. Check if current directory contains pubspec.yaml
  if (File('${dir.path}/pubspec.yaml').existsSync()) {
    final parent = dir.parent;
    if (parent.path != dir.path) {
      if (File('${parent.path}/melos.yaml').existsSync()) {
        return parent;
      }
    }
    return dir;
  }

  // 2. Search upward for pubspec.yaml or monorepo markers
  var probe = dir;
  while (probe.path != probe.parent.path) {
    if (File('${probe.path}/pubspec.yaml').existsSync() ||
        File('${probe.path}/melos.yaml').existsSync()) {
      return probe;
    }
    probe = probe.parent;
  }

  return dir;
}