findUserConfig function

UserConfig? findUserConfig({
  1. String? explicitPath,
  2. String? inputPath,
})

Searches for user config in order:

  1. explicitPath (if specified)
  2. inputPath/localizable_user.json (if inputPath is specified)
  3. ./localizable_user.json
  4. ~/.localizable/localizable_user.json
  5. ~/.config/localizable/localizable_user.json
  6. ~/localizable_user.json
  7. LOCALIZABLE_USER_KEY or LOCALIZABLE_USER_CONFIG environment variables

Implementation

UserConfig? findUserConfig({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 UserConfig.fromJson(parsed);
      } catch (e) {
        throw Exception('Unable to parse user config at "$explicitPath": $e');
      }
    } else {
      throw Exception('User 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_user.json');
    if (file.existsSync()) {
      try {
        final parsed =
            json.decode(file.readAsStringSync()) as Map<String, dynamic>;
        return UserConfig.fromJson(parsed);
      } catch (_) {}
    }
    final parent = dir.parent;
    if (parent.path == dir.path) break;
    dir = parent;
  }

  final home = _userHome;
  if (home != null) {
    final candidatePaths = [
      '$home/.localizable/localizable_user.json',
      '$home/.config/localizable/localizable_user.json',
      '$home/localizable_user.json',
    ];
    for (final path in candidatePaths) {
      final file = File(path);
      if (file.existsSync()) {
        try {
          final parsed =
              json.decode(file.readAsStringSync()) as Map<String, dynamic>;
          return UserConfig.fromJson(parsed);
        } catch (_) {}
      }
    }
  }

  final envKey = Platform.environment['LOCALIZABLE_USER_KEY'];
  if (envKey != null && envKey.isNotEmpty) {
    return UserConfig(jws: envKey);
  }

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

  return null;
}