fix method
Fix missing keys by generating entries in JSON files.
Implementation
Future<FixResult> fix(
ComparisonResult comparison,
ExtractionResult extracted,
) async {
final filesModified = <String>{};
final warnings = <String>[];
var keysAdded = 0;
if (comparison.missingInJson.isEmpty) {
_log('No missing keys to add.');
return FixResult(
filesModified: [],
keysAdded: 0,
keysRemoved: 0,
isDryRun: dryRun,
);
}
// Group missing keys by target shard file
final keysByShard = <String, Map<String, dynamic>>{};
final comparator = JsonComparator(
i18nPath: i18nPath,
referenceLocale: referenceLocale,
);
for (final key in comparison.missingInJson) {
// Find the source file for this key to determine shard
final keyLocations = extracted.keys.where((k) => k.key == key);
final sourceFile = keyLocations.isNotEmpty
? keyLocations.first.filePath
: null;
final shard = comparator.detectShard(key, sourceFile);
keysByShard.putIfAbsent(shard, () => {});
// Generate the value
if (extracted.pluralKeys.contains(key)) {
// Generate plural form structure
keysByShard[shard]![key] = _generatePluralTemplate(key, extracted);
} else {
// Simple string: msgid = value
keysByShard[shard]![key] = key;
}
}
// Write to each shard file
for (final entry in keysByShard.entries) {
final shardFile = entry.key;
final newKeys = entry.value;
final targetPath = p.join(i18nPath, referenceLocale, shardFile);
try {
await _mergeIntoFile(targetPath, newKeys);
filesModified.add(targetPath);
keysAdded += newKeys.length;
_log(
'${dryRun ? "[DRY RUN] Would add" : "Added"} ${newKeys.length} key(s) to $shardFile',
);
} catch (e) {
warnings.add('Could not write to $targetPath: $e');
}
}
return FixResult(
filesModified: filesModified.toList(),
keysAdded: keysAdded,
keysRemoved: 0,
warnings: warnings,
isDryRun: dryRun,
);
}