generate method
Implementation
void generate([String? filePath, String? targetPath]) {
if (filePath == null || filePath.trim().isEmpty) {
filePath = 'i10n.csv';
}
if (targetPath == null || targetPath.trim().isEmpty) {
targetPath = 'i10n_words.dart';
}
final File file = File(filePath);
if (!file.existsSync()) {
logError('File $filePath does not exist');
return;
}
final List<String> lines = file.readAsLinesSync();
// Remove any blank lines.
lines.removeWhere((line) => line.isEmpty);
if (lines.isEmpty) {
logError('File is empty:\n $filePath');
return;
}
// Get the language codes.
final List<String> languages = _getLineOfWords(lines.first);
final Iterable<String> invalid = languages.where((code) {
return code.trim().length != 2;
});
if (invalid.isNotEmpty) {
logError('Not valid language code(s):\n $invalid');
return;
}
// Assume the first code is the 'default' language. The rest are the translations.
final List<String> supportedLanguages =
languages.sublist(1, languages.length);
final List<Map<String, String>> maps = [];
// Add a Map object the List with every Language.
// ignore: unused_local_variable
for (final lang in supportedLanguages) {
maps.add({});
}
List<String> lineOfWords;
String key;
List<String> words;
String translations;
bool noWord;
for (var linesIndex = 1; linesIndex < lines.length; linesIndex++) {
lineOfWords = _getLineOfWords(lines[linesIndex]);
// Assume the first word is the key.
key = lineOfWords.first;
if (RESERVED_WORDS.contains(key)) {
logError(
'$key is a reserved keyword and cannot be used as key (line ${linesIndex + 1})');
continue;
}
// Assume the rest of the words are the translations.
words = lineOfWords.sublist(1, lineOfWords.length);
if (words.length != supportedLanguages.length) {
logError(
'The line number ${linesIndex + 1} seems malformatted (${words.length} words for ${supportedLanguages.length} columns)');
}
for (var wordIndex = 0; wordIndex < words.length; wordIndex++) {
noWord = words[wordIndex].isEmpty;
maps[wordIndex][key] = noWord ? key : words[wordIndex];
if (noWord) {
logError(
'The line number ${linesIndex + 1} had no word and so key was used: $key');
}
}
}
translations = _makeTranslations(maps, supportedLanguages);
_writeInFile(translations, targetPath);
}