findProjectConfig function

ProjectConfig? findProjectConfig({
  1. String? explicitPath,
  2. String? inputPath,
})

Implementation

ProjectConfig? findProjectConfig({String? explicitPath, String? inputPath}) {
  if (explicitPath != null && explicitPath.isNotEmpty) {
    final file = File(explicitPath);
    if (file.existsSync()) {
      try {
        final parsed =
            json.decode(file.readAsStringSync()) as Map<String, dynamic>;
        return ProjectConfig.fromJson(parsed);
      } catch (e) {
        throw Exception('Unable to parse project config at "$explicitPath": $e');
      }
    } else {
      throw Exception('Project config file not found at "$explicitPath"');
    }
  }

  // Search from inputPath or current directory, traversing upwards through parent directories
  var dir = Directory(inputPath ?? Directory.current.path).absolute;
  while (true) {
    final file = File('${dir.path}/localizable_project.json');
    if (file.existsSync()) {
      try {
        final parsed =
            json.decode(file.readAsStringSync()) as Map<String, dynamic>;
        return ProjectConfig.fromJson(parsed);
      } catch (_) {}
    }
    final parent = dir.parent;
    if (parent.path == dir.path) break;
    dir = parent;
  }

  final envConfig = Platform.environment['LOCALIZABLE_PROJECT_CONFIG'];
  if (envConfig != null && envConfig.isNotEmpty) {
    final file = File(envConfig);
    if (file.existsSync()) {
      try {
        final parsed =
            json.decode(file.readAsStringSync()) as Map<String, dynamic>;
        return ProjectConfig.fromJson(parsed);
      } catch (_) {}
    }
  }

  return null;
}