[gen_l10n] Fallback feature for untranslated messages (#53374)

* Generate methods using template resources if they do not exist in other locales

* Added a flag to either output of messages that have not been translated with detail into a file, or display a summary on the terminal.

* Add integration test for fallback message usage
This commit is contained in:
Shi-Hao Hong
2020-04-08 18:55:50 -07:00
committed by GitHub
parent 173c93d9a2
commit 5d63637e43
5 changed files with 223 additions and 105 deletions

View File

@@ -40,6 +40,15 @@ void main(List<String> arguments) {
help: 'The filename for the output localization and localizations '
'delegate classes.',
);
parser.addOption(
'untranslated-messages-file',
help: 'The location of a file that describes the localization\n'
'messages have not been translated yet. Using this option will create\n'
'a JSON file at the target location, in the following format:\n\n'
'"locale": ["message_1", "message_2" ... "message_n"]\n\n'
'If this option is not specified, a summary of the messages that\n'
'have not been translated will be printed on the command line.'
);
parser.addOption(
'output-class',
defaultsTo: 'AppLocalizations',
@@ -84,6 +93,7 @@ void main(List<String> arguments) {
final String arbPathString = results['arb-dir'] as String;
final String outputFileString = results['output-localization-file'] as String;
final String templateArbFileName = results['template-arb-file'] as String;
final String untranslatedMessagesFile = results['untranslated-messages-file'] as String;
final String classNameString = results['output-class'] as String;
final String preferredSupportedLocaleString = results['preferred-supported-locales'] as String;
final String headerString = results['header'] as String;
@@ -104,7 +114,8 @@ void main(List<String> arguments) {
headerFile: headerFile,
)
..loadResources()
..writeOutputFile();
..writeOutputFile()
..outputUnimplementedMessages(untranslatedMessagesFile);
} on FileSystemException catch (e) {
exitWithError(e.message);
} on FormatException catch (e) {

View File

@@ -193,48 +193,6 @@ String generateMethod(Message message, AppResourceBundle bundle) {
.replaceAll('@(message)', generateMessage());
}
String generateBaseClassFile(
String className,
String fileName,
String header,
AppResourceBundle bundle,
Iterable<Message> messages,
) {
final LocaleInfo locale = bundle.locale;
final Iterable<String> methods = messages
.where((Message message) => bundle.translationFor(message) != null)
.map((Message message) => generateMethod(message, bundle));
return classFileTemplate
.replaceAll('@(header)', header)
.replaceAll('@(language)', describeLocale(locale.toString()))
.replaceAll('@(baseClass)', className)
.replaceAll('@(fileName)', fileName)
.replaceAll('@(class)', '$className${locale.camelCase()}')
.replaceAll('@(localeName)', locale.toString())
.replaceAll('@(methods)', methods.join('\n\n'));
}
String generateSubclass({
String className,
AppResourceBundle bundle,
Iterable<Message> messages,
}) {
final LocaleInfo locale = bundle.locale;
final String baseClassName = '$className${LocaleInfo.fromString(locale.languageCode).camelCase()}';
final Iterable<String> methods = messages
.where((Message message) => bundle.translationFor(message) != null)
.map((Message message) => generateMethod(message, bundle));
return subclassTemplate
.replaceAll('@(language)', describeLocale(locale.toString()))
.replaceAll('@(baseLanguageClassName)', baseClassName)
.replaceAll('@(class)', '$className${locale.camelCase()}')
.replaceAll('@(localeName)', locale.toString())
.replaceAll('@(methods)', methods.join('\n\n'));
}
String generateBaseClassMethod(Message message) {
final String comment = message.description ?? 'No description provided in @${message.resourceId}';
if (message.placeholders.isNotEmpty) {
@@ -373,6 +331,7 @@ class LocalizationsGenerator {
final file.FileSystem _fs;
Iterable<Message> _allMessages;
AppResourceBundleCollection _allBundles;
LocaleInfo _templateArbLocale;
/// The reference to the project's l10n directory.
///
@@ -436,6 +395,8 @@ class LocalizationsGenerator {
/// The header to be prepended to the generated Dart localization file.
String header = '';
final Map<LocaleInfo, List<String>> _unimplementedMessages = <LocaleInfo, List<String>>{};
/// Initializes [l10nDirectory], [templateArbFile], [outputFile] and [className].
///
/// Throws an [L10nException] when a provided configuration is not allowed
@@ -609,6 +570,7 @@ class LocalizationsGenerator {
// files in l10nDirectory. Also initialized: supportedLocales.
void loadResources() {
final AppResourceBundle templateBundle = AppResourceBundle(templateArbFile);
_templateArbLocale = templateBundle.locale;
_allMessages = templateBundle.resourceIds.map((String id) => Message(templateBundle.resources, id));
for (final String resourceId in templateBundle.resourceIds)
if (!_isValidGetterAndMethodName(resourceId)) {
@@ -639,6 +601,71 @@ class LocalizationsGenerator {
supportedLocales.addAll(allLocales);
}
void _addUnimplementedMessage(LocaleInfo locale, String message) {
if (_unimplementedMessages.containsKey(locale)) {
_unimplementedMessages[locale].add(message);
} else {
_unimplementedMessages.putIfAbsent(locale, () => <String>[message]);
}
}
String _generateBaseClassFile(
String className,
String fileName,
String header,
AppResourceBundle bundle,
AppResourceBundle templateBundle,
Iterable<Message> messages,
) {
final LocaleInfo locale = bundle.locale;
final Iterable<String> methods = messages.map((Message message) {
if (bundle.translationFor(message) == null) {
_addUnimplementedMessage(locale, message.resourceId);
}
return generateMethod(
message,
bundle.translationFor(message) == null ? templateBundle : bundle,
);
});
return classFileTemplate
.replaceAll('@(header)', header)
.replaceAll('@(language)', describeLocale(locale.toString()))
.replaceAll('@(baseClass)', className)
.replaceAll('@(fileName)', fileName)
.replaceAll('@(class)', '$className${locale.camelCase()}')
.replaceAll('@(localeName)', locale.toString())
.replaceAll('@(methods)', methods.join('\n\n'));
}
String _generateSubclass(
String className,
AppResourceBundle bundle,
Iterable<Message> messages,
) {
final LocaleInfo locale = bundle.locale;
final String baseClassName = '$className${LocaleInfo.fromString(locale.languageCode).camelCase()}';
messages
.where((Message message) => bundle.translationFor(message) == null)
.forEach((Message message) {
_addUnimplementedMessage(locale, message.resourceId);
});
final Iterable<String> methods = messages
.where((Message message) => bundle.translationFor(message) != null)
.map((Message message) => generateMethod(message, bundle));
return subclassTemplate
.replaceAll('@(language)', describeLocale(locale.toString()))
.replaceAll('@(baseLanguageClassName)', baseClassName)
.replaceAll('@(class)', '$className${locale.camelCase()}')
.replaceAll('@(localeName)', locale.toString())
.replaceAll('@(methods)', methods.join('\n\n'));
}
// Generate the AppLocalizations class, its LocalizationsDelegate subclass,
// and all AppLocalizations subclasses for every locale.
String generateCode() {
@@ -692,11 +719,12 @@ class LocalizationsGenerator {
// Generate the template for the base class file. Further string
// interpolation will be done to determine if there are
// subclasses that extend the base class.
final String languageBaseClassFile = generateBaseClassFile(
final String languageBaseClassFile = _generateBaseClassFile(
className,
outputFileName,
header,
_allBundles.bundleFor(locale),
_allBundles.bundleFor(_templateArbLocale),
_allMessages,
);
@@ -705,10 +733,10 @@ class LocalizationsGenerator {
// Generate every subclass that is needed for the particular language
final Iterable<String> subclasses = localesForLanguage.map<String>((LocaleInfo locale) {
return generateSubclass(
className: className,
bundle: _allBundles.bundleFor(locale),
messages: _allMessages,
return _generateSubclass(
className,
_allBundles.bundleFor(locale),
_allMessages,
);
});
@@ -741,4 +769,52 @@ class LocalizationsGenerator {
void writeOutputFile() {
outputFile.writeAsStringSync(generateCode());
}
void outputUnimplementedMessages(String untranslatedMessagesFile) {
if (untranslatedMessagesFile == null || untranslatedMessagesFile == '') {
_unimplementedMessages.forEach((LocaleInfo locale, List<String> messages) {
stdout.writeln('"$locale": ${messages.length} untranslated message(s).');
});
stdout.writeln(
'To see a detailed report, use the --unimplemented-messages-file \n'
'option in the tool to generate a JSON format file containing \n'
'all messages that need to be translated.'
);
} else {
_writeUnimplementedMessagesFile(untranslatedMessagesFile);
}
}
void _writeUnimplementedMessagesFile(String untranslatedMessagesFile) {
if (_unimplementedMessages.isEmpty) {
return;
}
final File unimplementedMessageTranslationsFile = _fs.file(untranslatedMessagesFile);
String resultingFile = '{\n';
int count = 0;
final int numberOfLocales = _unimplementedMessages.length;
_unimplementedMessages.forEach((LocaleInfo locale, List<String> messages) {
resultingFile += ' "$locale": [\n';
for (int i = 0; i < messages.length; i += 1) {
resultingFile += ' "${messages[i]}"';
if (i != messages.length - 1) {
resultingFile += ',';
}
resultingFile += '\n';
}
resultingFile += ' ]';
count += 1;
if (count < numberOfLocales) {
resultingFile += ',\n';
}
resultingFile += '\n';
});
resultingFile += '}\n';
unimplementedMessageTranslationsFile.writeAsStringSync(resultingFile);
}
}

View File

@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'package:file/file.dart';
@@ -25,6 +26,17 @@ const String singleMessageArbFileString = '''
"description": "Title for the application"
}
}''';
const String twoMessageArbFileString = '''
{
"title": "Title",
"@title": {
"description": "Title for the application"
},
"subtitle": "Subtitle",
"@subtitle": {
"description": "Subtitle for the application"
}
}''';
const String esArbFileName = 'app_es.arb';
const String singleEsMessageArbFileString = '''
{
@@ -277,6 +289,43 @@ void main() {
expect(generator.header, '/// Sample header in a text file');
});
test('correctly creates an unimplemented messages file', () {
fs.currentDirectory.childDirectory('lib').childDirectory('l10n')
..createSync(recursive: true)
..childFile(defaultTemplateArbFileName).writeAsStringSync(twoMessageArbFileString)
..childFile(esArbFileName).writeAsStringSync(singleEsMessageArbFileString);
LocalizationsGenerator generator;
try {
generator = LocalizationsGenerator(fs);
generator
..initialize(
l10nDirectoryPath: defaultArbPathString,
templateArbFileName: defaultTemplateArbFileName,
outputFileString: defaultOutputFileString,
classNameString: defaultClassNameString,
)
..loadResources()
..generateCode()
..outputUnimplementedMessages(path.join('lib', 'l10n', 'unimplemented_message_translations.json'));
} on L10nException catch (e) {
fail('Generating output should not fail: \n${e.message}');
}
final File unimplementedOutputFile = fs.file(
path.join('lib', 'l10n', 'unimplemented_message_translations.json'),
);
final String unimplementedOutputString = unimplementedOutputFile.readAsStringSync();
try {
// Since ARB file is essentially JSON, decoding it should not fail.
json.decode(unimplementedOutputString);
} on Exception {
fail('Parsing arb file should not fail');
}
expect(unimplementedOutputString, contains('es'));
expect(unimplementedOutputString, contains('subtitle'));
});
test('setting both a headerString and a headerFile should fail', () {
fs.currentDirectory.childDirectory('lib').childDirectory('l10n')
..createSync(recursive: true)