findExistingServiceAccountKey static method

DiscoveredServiceAccount? findExistingServiceAccountKey({
  1. required String outputDir,
  2. String? serverPackageName,
})

Walks the user's filesystem looking for a pre-existing service-account.json so the wizard can offer to reuse it instead of asking the user to drop in another copy of the same key.

Search order (first match wins):

  1. <outputDir>/service-account.json
  2. <outputDir>/config/keys/service-account.json
  3. <outputDir>/<serverPackageName>/service-account.json (when serverPackageName is provided)
  4. <currentDir>/service-account.json
  5. The first ancestor of outputDir (and of Directory.current) that contains a service-account.json, walking up at most 6 levels. This catches the common "I keep my SA at the workspace root" pattern (e.g. running oracular from a folder that has service-account.json next to multiple project subdirs).

Returns null when nothing matches.

Implementation

static DiscoveredServiceAccount? findExistingServiceAccountKey({
  required String outputDir,
  String? serverPackageName,
}) {
  final List<String> candidates = <String>[];

  void addIfNotEmpty(String path) {
    if (path.trim().isEmpty) return;
    candidates.add(p.normalize(p.absolute(path)));
  }

  addIfNotEmpty(p.join(outputDir, _canonicalFileName));
  addIfNotEmpty(p.join(outputDir, 'config', 'keys', _canonicalFileName));
  if (serverPackageName != null && serverPackageName.trim().isNotEmpty) {
    addIfNotEmpty(p.join(outputDir, serverPackageName, _canonicalFileName));
  }
  addIfNotEmpty(p.join(Directory.current.path, _canonicalFileName));

  // Walk ancestors of both outputDir and the current working directory.
  // Six levels is more than enough for typical workspace layouts and
  // guards against runaway loops on broken filesystems.
  for (final String start in <String>{
    p.normalize(p.absolute(outputDir)),
    p.normalize(p.absolute(Directory.current.path)),
  }) {
    String dir = start;
    for (int depth = 0; depth < 6; depth++) {
      final String parent = p.dirname(dir);
      if (parent == dir) break; // reached filesystem root
      dir = parent;
      addIfNotEmpty(p.join(dir, _canonicalFileName));
    }
  }

  final Set<String> seen = <String>{};
  for (final String candidate in candidates) {
    if (!seen.add(candidate)) continue;
    final File file = File(candidate);
    if (!file.existsSync()) continue;
    return _readDiscoveredServiceAccount(file);
  }
  return null;
}