gen_l10n.dart tool testing (#44856)

* Add tests to gen_l10n.dart tool

* Separate out LocalizationsGenerator class to improve testability of code

* Add testing dependencies to dev/tools

* Integrate dev/tools testing to flutter CI

* Restructure dev/tools folder for testing

* Fix license headers
This commit is contained in:
Shi-Hao Hong
2019-12-06 11:35:08 -08:00
committed by GitHub
parent 066b5a1667
commit 37e66b2179
7 changed files with 1111 additions and 159 deletions

View File

@@ -0,0 +1,101 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:args/args.dart' as argslib;
import 'package:file/local.dart' as local;
import 'package:path/path.dart' as path;
import '../gen_l10n.dart';
import '../localizations_utils.dart';
Future<void> main(List<String> arguments) async {
final argslib.ArgParser parser = argslib.ArgParser();
parser.addFlag(
'help',
defaultsTo: false,
negatable: false,
help: 'Print this help message.',
);
parser.addOption(
'arb-dir',
defaultsTo: path.join('lib', 'l10n'),
help: 'The directory where all localization files should reside. For '
'example, the template and translated arb files should be located here. '
'Also, the generated output messages Dart files for each locale and the '
'generated localizations classes will be created here.',
);
parser.addOption(
'template-arb-file',
defaultsTo: 'app_en.arb',
help: 'The template arb file that will be used as the basis for '
'generating the Dart localization and messages files.',
);
parser.addOption(
'output-localization-file',
defaultsTo: 'app_localizations.dart',
help: 'The filename for the output localization and localizations '
'delegate classes.',
);
parser.addOption(
'output-class',
defaultsTo: 'AppLocalizations',
help: 'The Dart class name to use for the output localization and '
'localizations delegate classes.',
);
final argslib.ArgResults results = parser.parse(arguments);
if (results['help'] == true) {
print(parser.usage);
exit(0);
}
final String arbPathString = results['arb-dir'];
final String outputFileString = results['output-localization-file'];
final String templateArbFileName = results['template-arb-file'];
final String classNameString = results['output-class'];
const local.LocalFileSystem fs = local.LocalFileSystem();
final LocalizationsGenerator localizationsGenerator = LocalizationsGenerator(fs);
try {
localizationsGenerator
..initialize(
l10nDirectoryPath: arbPathString,
templateArbFileName: templateArbFileName,
outputFileString: outputFileString,
classNameString: classNameString,
)
..parseArbFiles()
..generateClassMethods()
..generateOutputFile();
} on FileSystemException catch (e) {
exitWithError(e.message);
} on FormatException catch (e) {
exitWithError(e.message);
} on L10nException catch (e) {
exitWithError(e.message);
}
final ProcessResult pubGetResult = await Process.run('flutter', <String>['pub', 'get']);
if (pubGetResult.exitCode != 0) {
stderr.write(pubGetResult.stderr);
exit(1);
}
final ProcessResult generateFromArbResult = await Process.run('flutter', <String>[
'pub',
'run',
'intl_translation:generate_from_arb',
'--output-dir=${localizationsGenerator.l10nDirectory.path}',
'--no-use-deferred-loading',
localizationsGenerator.outputFile.path,
...localizationsGenerator.arbFilenames,
]);
if (generateFromArbResult.exitCode != 0) {
stderr.write(generateFromArbResult.stderr);
exit(1);
}
}

View File

@@ -2,11 +2,11 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:args/args.dart' as argslib;
import 'package:file/file.dart' as file;
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
import 'localizations_utils.dart';
@@ -149,10 +149,6 @@ const String pluralMethodTemplate = '''
}
''';
int sortFilesByPath (FileSystemEntity a, FileSystemEntity b) {
return a.path.compareTo(b.path);
}
List<String> genMethodParameters(Map<String, dynamic> bundle, String key, String type) {
final Map<String, dynamic> attributesMap = bundle['@$key'] as Map<String, dynamic>;
if (attributesMap != null && attributesMap.containsKey('placeholders')) {
@@ -193,7 +189,7 @@ String genSimpleMethod(Map<String, dynamic> bundle, String key) {
final Map<String, dynamic> attributesMap = bundle['@$key'] as Map<String, dynamic>;
if (attributesMap == null)
exitWithError(
throw L10nException(
'Resource attribute "@$key" was not found. Please ensure that each '
'resource id has a corresponding resource attribute.'
);
@@ -238,7 +234,7 @@ String genPluralMethod(Map<String, dynamic> bundle, String key) {
...genIntlMethodArgs(bundle, key),
];
for(String pluralKey in pluralIds.keys) {
for (String pluralKey in pluralIds.keys) {
final RegExp expRE = RegExp('($pluralKey){([^}]+)}');
final RegExpMatch match = expRE.firstMatch(message);
if (match != null && match.groupCount == 2) {
@@ -289,6 +285,19 @@ bool _isValidClassName(String className) {
return true;
}
bool _isNotReadable(FileStat fileStat) {
final String rawStatString = fileStat.modeString();
// Removes potential prepended permission bits, such as '(suid)' and '(guid)'.
final String statString = rawStatString.substring(rawStatString.length - 9);
return !(statString[0] == 'r' || statString[3] == 'r' || statString[6] == 'r');
}
bool _isNotWritable(FileStat fileStat) {
final String rawStatString = fileStat.modeString();
// Removes potential prepended permission bits, such as '(suid)' and '(guid)'.
final String statString = rawStatString.substring(rawStatString.length - 9);
return !(statString[1] == 'w' || statString[4] == 'w' || statString[7] == 'w');
}
bool _isValidGetterAndMethodName(String name) {
// Dart getter and method name cannot contain non-alphanumeric symbols
if (name.contains(RegExp(r'[^a-zA-Z\d]')))
@@ -302,184 +311,250 @@ bool _isValidGetterAndMethodName(String name) {
return true;
}
bool _isDirectoryReadableAndWritable(String statString) {
if (statString[0] == '-' || statString[1] == '-')
return false;
return true;
}
/// The localizations generation class used to generate the localizations
/// classes, as well as all pertinent Dart files required to internationalize a
/// Flutter application.
class LocalizationsGenerator {
/// Creates an instance of the localizations generator class.
///
/// It takes in a [FileSystem] representation that the class will act upon.
LocalizationsGenerator(this._fs);
String _importFilePath(String path, String fileName) {
final String replaceLib = path.replaceAll('lib/', '');
return '$replaceLib/$fileName';
}
static RegExp arbFilenameLocaleRE = RegExp(r'^[^_]*_(\w+)\.arb$');
static RegExp arbFilenameRE = RegExp(r'(\w+)\.arb$');
static RegExp pluralValueRE = RegExp(r'^\s*\{[\w\s,]*,\s*plural\s*,');
Future<void> main(List<String> arguments) async {
final argslib.ArgParser parser = argslib.ArgParser();
parser.addFlag(
'help',
defaultsTo: false,
negatable: false,
help: 'Print this help message.',
);
parser.addOption(
'arb-dir',
defaultsTo: path.join('lib', 'l10n'),
help: 'The directory where all localization files should reside. For '
'example, the template and translated arb files should be located here. '
'Also, the generated output messages Dart files for each locale and the '
'generated localizations classes will be created here.',
);
parser.addOption(
'template-arb-file',
defaultsTo: 'app_en.arb',
help: 'The template arb file that will be used as the basis for '
'generating the Dart localization and messages files.',
);
parser.addOption(
'output-localization-file',
defaultsTo: 'app_localizations.dart',
help: 'The filename for the output localization and localizations '
'delegate classes.',
);
parser.addOption(
'output-class',
defaultsTo: 'AppLocalizations',
help: 'The Dart class name to use for the output localization and '
'localizations delegate classes.',
);
final file.FileSystem _fs;
final argslib.ArgResults results = parser.parse(arguments);
if (results['help'] == true) {
print(parser.usage);
exit(0);
}
/// The reference to the project's l10n directory.
///
/// It is assumed that all input files (e.g. [templateArbFile], arb files
/// for translated messages) and output files (e.g. The localizations
/// [outputFile], `messages_<locale>.dart` and `messages_all.dart`)
/// will reside here.
///
/// This directory is specified with the [initialize] method.
Directory l10nDirectory;
final String arbPathString = results['arb-dir'] as String;
final String outputFileString = results['output-localization-file'] as String;
/// The input arb file which defines all of the messages that will be
/// exported by the generated class that's written to [outputFile].
///
/// This file is specified with the [initialize] method.
File templateArbFile;
final Directory l10nDirectory = Directory(arbPathString);
final File templateArbFile = File(path.join(l10nDirectory.path, results['template-arb-file'] as String));
final File outputFile = File(path.join(l10nDirectory.path, outputFileString));
final String stringsClassName = results['output-class'] as String;
/// The file to write the generated localizations and localizations delegate
/// classes to.
///
/// This file is specified with the [initialize] method.
File outputFile;
if (!l10nDirectory.existsSync())
exitWithError(
"The 'arb-dir' directory, $l10nDirectory, does not exist.\n"
'Make sure that the correct path was provided.'
);
final String l10nDirectoryStatModeString = l10nDirectory.statSync().modeString();
if (!_isDirectoryReadableAndWritable(l10nDirectoryStatModeString))
exitWithError(
"The 'arb-dir' directory, $l10nDirectory, doesn't allow reading and writing.\n"
'Please ensure that the user has read and write permissions.'
);
final String templateArbFileStatModeString = templateArbFile.statSync().modeString();
if (templateArbFileStatModeString[0] == '-')
exitWithError(
"The 'template-arb-file', $templateArbFile, is not readable.\n"
'Please ensure that the user has read permissions.'
);
if (!_isValidClassName(stringsClassName))
exitWithError(
"The 'output-class', $stringsClassName, is not valid Dart class name.\n"
);
/// The class name to be used for the localizations class in [outputFile].
///
/// For example, if 'AppLocalizations' is passed in, a class named
/// AppLocalizations will be used for localized message lookups.
///
/// The class name is specified with the [initialize] method.
String get className => _className;
String _className;
/// Sets the [className] for the localizations and localizations delegate
/// classes.
/// The list of all arb files in [l10nDirectory].
final List<String> arbFilenames = <String>[];
/// The supported language codes as found in the arb files located in
/// [l10nDirectory].
final Set<String> supportedLanguageCodes = <String>{};
/// The supported locales as found in the arb files located in
/// [l10nDirectory].
final Set<LocaleInfo> supportedLocales = <LocaleInfo>{};
for (FileSystemEntity entity in l10nDirectory.listSync().toList()..sort(sortFilesByPath)) {
final String entityPath = entity.path;
/// The class methods that will be generated in the localizations class
/// based on messages found in the template arb file.
final List<String> classMethods = <String>[];
if (FileSystemEntity.isFileSync(entityPath)) {
final RegExp arbFilenameRE = RegExp(r'(\w+)\.arb$');
if (arbFilenameRE.hasMatch(entityPath)) {
final File arbFile = File(entityPath);
final Map<String, dynamic> arbContents = json.decode(arbFile.readAsStringSync()) as Map<String, dynamic>;
String localeString = arbContents['@@locale'] as String;
/// Initializes [l10nDirectory], [templateArbFile], [outputFile] and [className].
///
/// Throws an [L10nException] when a provided configuration is not allowed
/// by [LocalizationsGenerator].
///
/// Throws a [FileSystemException] when a file operation necessary for setting
/// up the [LocalizationsGenerator] cannot be completed.
void initialize({
String l10nDirectoryPath,
String templateArbFileName,
String outputFileString,
String classNameString,
}) {
setL10nDirectory(l10nDirectoryPath);
setTemplateArbFile(templateArbFileName);
setOutputFile(outputFileString);
className = classNameString;
}
/// Sets the reference [Directory] for [l10nDirectory].
@visibleForTesting
void setL10nDirectory(String arbPathString) {
if (arbPathString == null)
throw L10nException('arbPathString argument cannot be null');
l10nDirectory = _fs.directory(arbPathString);
if (!l10nDirectory.existsSync())
throw FileSystemException(
"The 'arb-dir' directory, $l10nDirectory, does not exist.\n"
'Make sure that the correct path was provided.'
);
final FileStat fileStat = l10nDirectory.statSync();
if (_isNotReadable(fileStat) || _isNotWritable(fileStat))
throw FileSystemException(
"The 'arb-dir' directory, $l10nDirectory, doesn't allow reading and writing.\n"
'Please ensure that the user has read and write permissions.'
);
}
/// Sets the reference [File] for [templateArbFile].
@visibleForTesting
void setTemplateArbFile(String templateArbFileName) {
if (templateArbFileName == null)
throw L10nException('templateArbFileName argument cannot be null');
if (l10nDirectory == null)
throw L10nException('l10nDirectory cannot be null when setting template arb file');
templateArbFile = _fs.file(path.join(l10nDirectory.path, templateArbFileName));
final String templateArbFileStatModeString = templateArbFile.statSync().modeString();
if (templateArbFileStatModeString[0] == '-' && templateArbFileStatModeString[3] == '-')
throw FileSystemException(
"The 'template-arb-file', $templateArbFile, is not readable.\n"
'Please ensure that the user has read permissions.'
);
}
/// Sets the reference [File] for the localizations delegate [outputFile].
@visibleForTesting
void setOutputFile(String outputFileString) {
if (outputFileString == null)
throw L10nException('outputFileString argument cannot be null');
outputFile = _fs.file(path.join(l10nDirectory.path, outputFileString));
}
@visibleForTesting
set className(String classNameString) {
if (classNameString == null)
throw L10nException('classNameString argument cannot be null');
if (!_isValidClassName(classNameString))
throw L10nException(
"The 'output-class', $classNameString, is not a valid Dart class name.\n"
);
_className = classNameString;
}
/// Scans [l10nDirectory] for arb files and parses them for language and locale
/// information.
void parseArbFiles() {
final List<File> fileSystemEntityList = l10nDirectory
.listSync()
.whereType<File>()
.toList();
final List<LocaleInfo> localeInfoList = <LocaleInfo>[];
for (File file in fileSystemEntityList) {
final String filePath = file.path;
if (arbFilenameRE.hasMatch(filePath)) {
final Map<String, dynamic> arbContents = json.decode(file.readAsStringSync());
String localeString = arbContents['@@locale'];
if (localeString == null) {
final RegExp arbFilenameLocaleRE = RegExp(r'^[^_]*_(\w+)\.arb$');
final RegExpMatch arbFileMatch = arbFilenameLocaleRE.firstMatch(entityPath);
final RegExpMatch arbFileMatch = arbFilenameLocaleRE.firstMatch(filePath);
if (arbFileMatch == null) {
exitWithError(
throw L10nException(
"The following .arb file's locale could not be determined: \n"
'$entityPath \n'
'$filePath \n'
"Make sure that the locale is specified in the '@@locale' "
'property or as part of the filename (ie. file_en.arb)'
'property or as part of the filename (e.g. file_en.arb)'
);
}
localeString = arbFilenameLocaleRE.firstMatch(entityPath)[1];
localeString = arbFilenameLocaleRE.firstMatch(filePath)[1];
}
arbFilenames.add(entityPath);
arbFilenames.add(filePath);
final LocaleInfo localeInfo = LocaleInfo.fromString(localeString);
if (supportedLocales.contains(localeInfo))
exitWithError(
if (localeInfoList.contains(localeInfo))
throw L10nException(
'Multiple arb files with the same locale detected. \n'
'Ensure that there is exactly one arb file for each locale.'
);
supportedLocales.add(localeInfo);
supportedLanguageCodes.add('\'${localeInfo.languageCode}\'');
localeInfoList.add(localeInfo);
}
}
localeInfoList.sort();
supportedLocales.addAll(localeInfoList);
supportedLanguageCodes.addAll(localeInfoList.map((LocaleInfo localeInfo) {
return '\'${localeInfo.languageCode}\'';
}));
}
/// Generates the methods for the localizations class.
///
/// The method parses [templateArbFile] and uses its resource ids as the
/// Dart method and getter names. It then uses each resource id's
/// corresponding resource value to figure out how to define these getters.
///
/// For example, a message with plurals will be handled differently from
/// a simple, singular message.
///
/// Throws an [L10nException] when a provided configuration is not allowed
/// by [LocalizationsGenerator].
///
/// Throws a [FileSystemException] when a file operation necessary for setting
/// up the [LocalizationsGenerator] cannot be completed.
///
/// Throws a [FormatException] when parsing the arb file is unsuccessful.
void generateClassMethods() {
Map<String, dynamic> bundle;
try {
bundle = json.decode(templateArbFile.readAsStringSync());
} on FileSystemException catch (e) {
throw FileSystemException('Unable to read input arb file: $e');
} on FormatException catch (e) {
throw FormatException('Unable to parse arb file: $e');
}
final List<String> sortedArbKeys = bundle.keys.toList()..sort();
for (String key in sortedArbKeys) {
if (key.startsWith('@'))
continue;
if (!_isValidGetterAndMethodName(key))
throw L10nException(
'Invalid key format: $key \n It has to be in camel case, cannot start '
'with a number, and cannot contain non-alphanumeric characters.'
);
if (pluralValueRE.hasMatch(bundle[key]))
classMethods.add(genPluralMethod(bundle, key));
else
classMethods.add(genSimpleMethod(bundle, key));
}
}
final List<String> classMethods = <String>[];
Map<String, dynamic> bundle;
try {
bundle = json.decode(templateArbFile.readAsStringSync()) as Map<String, dynamic>;
} on FileSystemException catch (e) {
exitWithError('Unable to read input arb file: $e');
} on FormatException catch (e) {
exitWithError('Unable to parse arb file: $e');
}
final RegExp pluralValueRE = RegExp(r'^\s*\{[\w\s,]*,\s*plural\s*,');
for (String key in bundle.keys.toList()..sort()) {
if (key.startsWith('@'))
continue;
if (!_isValidGetterAndMethodName(key))
exitWithError(
'Invalid key format: $key \n It has to be in camel case, cannot start '
'with a number, and cannot contain non-alphanumeric characters.'
);
if (pluralValueRE.hasMatch(bundle[key] as String))
classMethods.add(genPluralMethod(bundle, key));
else
classMethods.add(genSimpleMethod(bundle, key));
}
outputFile.writeAsStringSync(
defaultFileTemplate
.replaceAll('@className', stringsClassName)
.replaceAll('@classMethods', classMethods.join('\n'))
.replaceAll('@importFile', _importFilePath(arbPathString, outputFileString))
.replaceAll('@supportedLocales', genSupportedLocaleProperty(supportedLocales))
.replaceAll('@supportedLanguageCodes', supportedLanguageCodes.toList().join(', '))
);
final ProcessResult pubGetResult = await Process.run('flutter', <String>['pub', 'get']);
if (pubGetResult.exitCode != 0) {
stderr.write(pubGetResult.stderr);
exit(1);
}
final ProcessResult generateFromArbResult = await Process.run('flutter', <String>[
'pub',
'pub',
'run',
'intl_translation:generate_from_arb',
'--output-dir=${l10nDirectory.path}',
'--no-use-deferred-loading',
outputFile.path,
...arbFilenames,
]);
if (generateFromArbResult.exitCode != 0) {
stderr.write(generateFromArbResult.stderr);
exit(1);
/// Generates a file that contains the localizations class and the
/// LocalizationsDelegate class.
void generateOutputFile() {
final String directory = path.basename(l10nDirectory.path);
final String outputFileName = path.basename(outputFile.path);
outputFile.writeAsStringSync(
defaultFileTemplate
.replaceAll('@className', className)
.replaceAll('@classMethods', classMethods.join('\n'))
.replaceAll('@importFile', '$directory/$outputFileName')
.replaceAll('@supportedLocales', genSupportedLocaleProperty(supportedLocales))
.replaceAll('@supportedLanguageCodes', supportedLanguageCodes.toList().join(', '))
);
}
}
class L10nException implements Exception {
L10nException(this.message);
final String message;
}