checkLanguages function
Keys the default language file has that another language file doesn't.
Implementation
DoctorCheck checkLanguages({String projectRoot = '.'}) {
final _Project p = _Project(projectRoot);
final List<String> files = p.files('lang', extension: '.json');
if (files.isEmpty) {
return const DoctorCheck(
'Languages',
DoctorStatus.skipped,
'No lang/*.json files',
);
}
final String? locale = _envValues(p.read('.env') ?? '')['DEFAULT_LOCALE'];
final String base = files.contains('lang/$locale.json')
? 'lang/$locale.json'
: files.contains('lang/en.json')
? 'lang/en.json'
: files.first;
final String baseName = base.substring('lang/'.length);
final Map<String, Set<String>> keys = {};
final List<String> invalid = [];
for (final String file in files) {
try {
final Object? json = jsonDecode(p.read(file)!);
if (json is! Map) throw const FormatException('not a JSON object');
keys[file] = _flatKeys(json);
} on FormatException {
invalid.add(file);
}
}
if (files.length == 1 && invalid.isEmpty) {
return DoctorCheck(
'Languages',
DoctorStatus.ok,
'$baseName is the only language file',
);
}
final Map<String, List<String>> missing = {
if (keys[base] case final Set<String> baseKeys)
for (final String file in files)
if (file != base && keys[file] != null)
if (baseKeys.difference(keys[file]!).toList()..sort()
case final List<String> gaps when gaps.isNotEmpty)
file: gaps,
};
if (missing.isEmpty && invalid.isEmpty) {
return DoctorCheck(
'Languages',
DoctorStatus.ok,
files.length == 2
? '${files.firstWhere((String file) => file != base).substring('lang/'.length)} has every key $baseName has'
: 'All ${files.length - 1} language files have every key $baseName has',
);
}
const int shown = 10;
final int count = missing.length + invalid.length;
final String summary;
if (count > 1) {
summary = '$count language files need a look';
} else if (invalid.isNotEmpty) {
summary = '${invalid.single} isn\'t a valid JSON object';
} else {
final MapEntry<String, List<String>> only = missing.entries.single;
summary =
'${only.key.substring('lang/'.length)} is missing '
'${_plural(only.value.length, 'key')} that $baseName has';
}
return DoctorCheck(
'Languages',
DoctorStatus.problem,
summary,
details: [
for (final String file in invalid)
if (count > 1) '$file isn\'t a valid JSON object',
for (final MapEntry<String, List<String>> entry in missing.entries) ...[
if (count > 1)
'${entry.key} is missing ${_plural(entry.value.length, 'key')}:',
for (final String key in entry.value.take(shown))
count > 1 ? ' $key' : key,
if (entry.value.length > shown)
'${count > 1 ? ' ' : ''}and ${entry.value.length - shown} more',
],
],
);
}