forked from firka/flutter
Cleanup in localizations code (#20018)
The following changes are made by this PR: * Translation bundles now implement MaterialLocalizations directly, and are public so that they can be directly extended. * The list of supported languages is now a generated constant. * The icuShortTimePattern/TimeOfDayFormat values are now pre-parsed. * Various other changes for consistency with the style guide and the rest of the codebase, e.g. the class names don't use `_`, the `path` library is imported as such, more dartdocs, fewer `// ignore`s, validation using exceptions. This reduces our technical debt benchmark.
This commit is contained in:
@@ -6,7 +6,8 @@
|
||||
/// package for the subset of locales supported by the flutter_localizations
|
||||
/// package.
|
||||
///
|
||||
/// The extracted data is written into packages/flutter_localizations/lib/src/l10n/date_localizations.dart.
|
||||
/// The extracted data is written into:
|
||||
/// packages/flutter_localizations/lib/src/l10n/date_localizations.dart
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
@@ -89,7 +90,7 @@ Future<Null> main(List<String> rawArgs) async {
|
||||
});
|
||||
buffer.writeln('};');
|
||||
|
||||
// Note: code that uses datePatterns expects it to contain values of type
|
||||
// Code that uses datePatterns expects it to contain values of type
|
||||
// Map<String, String> not Map<String, dynamic>.
|
||||
buffer.writeln('const Map<String, Map<String, String>> datePatterns = const <String, Map<String, String>> {');
|
||||
patternFiles.forEach((String locale, File data) {
|
||||
|
||||
@@ -30,17 +30,19 @@
|
||||
// dart dev/tools/gen_localizations.dart
|
||||
// ```
|
||||
//
|
||||
// If the data looks good, use the `-w` option to overwrite the
|
||||
// If the data looks good, use the `-w` or `--overwrite` option to overwrite the
|
||||
// packages/flutter_localizations/lib/src/l10n/localizations.dart file:
|
||||
//
|
||||
// ```
|
||||
// dart dev/tools/gen_localizations.dart --overwrite
|
||||
// ```
|
||||
|
||||
import 'dart:convert' show json;
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path/path.dart' as pathlib;
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
import 'localizations_utils.dart';
|
||||
import 'localizations_validator.dart';
|
||||
@@ -50,23 +52,36 @@ const String outputHeader = '''
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
// This file has been automatically generated. Please do not edit it manually.
|
||||
// This file has been automatically generated. Please do not edit it manually.
|
||||
// To regenerate the file, use:
|
||||
// @(regenerate)
|
||||
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart' as intl;
|
||||
|
||||
import '../material_localizations.dart';
|
||||
''';
|
||||
|
||||
/// Maps locales to resource key/value pairs.
|
||||
final Map<String, Map<String, String>> localeToResources = <String, Map<String, String>>{};
|
||||
|
||||
/// Maps locales to resource attributes.
|
||||
/// Maps locales to resource key/attributes pairs.
|
||||
///
|
||||
/// See also https://github.com/googlei18n/app-resource-bundle/wiki/ApplicationResourceBundleSpecification#resource-attributes
|
||||
/// See also: <https://github.com/googlei18n/app-resource-bundle/wiki/ApplicationResourceBundleSpecification#resource-attributes>
|
||||
final Map<String, Map<String, dynamic>> localeToResourceAttributes = <String, Map<String, dynamic>>{};
|
||||
|
||||
// Return s as a Dart-parseable raw string in single or double quotes. Expand double quotes:
|
||||
// foo => r'foo'
|
||||
// foo "bar" => r'foo "bar"'
|
||||
// foo 'bar' => r'foo ' "'" r'bar' "'"
|
||||
/// Return `s` as a Dart-parseable raw string in single or double quotes.
|
||||
///
|
||||
/// Double quotes are expanded:
|
||||
///
|
||||
/// ```
|
||||
/// foo => r'foo'
|
||||
/// foo "bar" => r'foo "bar"'
|
||||
/// foo 'bar' => r'foo ' "'" r'bar' "'"
|
||||
/// ```
|
||||
String generateString(String s) {
|
||||
if (!s.contains("'"))
|
||||
return "r'$s'";
|
||||
@@ -91,8 +106,10 @@ String generateString(String s) {
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
/// This is the core of this script; it generates the code used for translations.
|
||||
String generateTranslationBundles() {
|
||||
final StringBuffer output = new StringBuffer();
|
||||
final StringBuffer supportedLocales = new StringBuffer();
|
||||
|
||||
final Map<String, List<String>> languageToLocales = <String, List<String>>{};
|
||||
final Set<String> allResourceIdentifiers = new Set<String>();
|
||||
@@ -104,132 +121,262 @@ String generateTranslationBundles() {
|
||||
allResourceIdentifiers.addAll(localeToResources[locale].keys);
|
||||
}
|
||||
|
||||
// Generate the TranslationsBundle base class. It contains one getter
|
||||
// per resource identifier found in any of the .arb files.
|
||||
//
|
||||
// class TranslationsBundle {
|
||||
// const TranslationsBundle(this.parent);
|
||||
// final TranslationsBundle parent;
|
||||
// String get scriptCategory => parent?.scriptCategory;
|
||||
// ...
|
||||
// }
|
||||
output.writeln('''
|
||||
// The TranslationBundle subclasses defined here encode all of the translations
|
||||
// found in the flutter_localizations/lib/src/l10n/*.arb files.
|
||||
// The classes defined here encode all of the translations found in the
|
||||
// `flutter_localizations/lib/src/l10n/*.arb` files.
|
||||
//
|
||||
// The [MaterialLocalizations] class uses the (generated)
|
||||
// translationBundleForLocale() function to look up a const TranslationBundle
|
||||
// instance for a locale.
|
||||
// These classes are constructed by the [getTranslation] method at the bottom of
|
||||
// this file, and used by the [_MaterialLocalizationsDelegate.load] method defined
|
||||
// in `flutter_localizations/lib/src/material_localizations.dart`.''');
|
||||
|
||||
// ignore_for_file: public_member_api_docs
|
||||
// We generate one class per supported language (e.g.
|
||||
// `MaterialLocalizationEn`). These implement everything that is needed by
|
||||
// GlobalMaterialLocalizations.
|
||||
|
||||
import \'dart:ui\' show Locale;
|
||||
// We also generate one subclass for each locale with a country code (e.g.
|
||||
// `MaterialLocalizationEnGb`). Their superclasses are the aforementioned
|
||||
// language classes for the same locale but without a country code (e.g.
|
||||
// `MaterialLocalizationEn`). These classes only override getters that return
|
||||
// a different value than their superclass.
|
||||
|
||||
class TranslationBundle {
|
||||
const TranslationBundle(this.parent);
|
||||
final TranslationBundle parent;''');
|
||||
for (String key in allResourceIdentifiers)
|
||||
output.writeln(' String get $key => parent?.$key;');
|
||||
output.writeln('''
|
||||
}''');
|
||||
|
||||
// Generate one private TranslationBundle subclass per supported
|
||||
// language. Each of these classes overrides every resource identifier
|
||||
// getter. For example:
|
||||
//
|
||||
// class _Bundle_en extends TranslationBundle {
|
||||
// const _Bundle_en() : super(null);
|
||||
// @override String get scriptCategory => r'English-like';
|
||||
// ...
|
||||
// }
|
||||
for (String language in languageToLocales.keys) {
|
||||
final Map<String, String> resources = localeToResources[language];
|
||||
output.writeln('''
|
||||
|
||||
// ignore: camel_case_types
|
||||
class _Bundle_$language extends TranslationBundle {
|
||||
const _Bundle_$language() : super(null);''');
|
||||
for (String key in resources.keys) {
|
||||
final String value = generateString(resources[key]);
|
||||
output.writeln('''
|
||||
@override String get $key => $value;''');
|
||||
final List<String> allKeys = allResourceIdentifiers.toList()..sort();
|
||||
final List<String> languageCodes = languageToLocales.keys.toList()..sort();
|
||||
for (String languageName in languageCodes) {
|
||||
final String camelCaseLanguage = camelCase(languageName);
|
||||
final Map<String, String> languageResources = localeToResources[languageName];
|
||||
final String languageClassName = 'MaterialLocalization$camelCaseLanguage';
|
||||
final String constructor = generateConstructor(languageClassName, languageName);
|
||||
output.writeln('');
|
||||
output.writeln('/// The translations for ${describeLocale(languageName)} (`$languageName`).');
|
||||
output.writeln('class $languageClassName extends GlobalMaterialLocalizations {');
|
||||
output.writeln(constructor);
|
||||
for (String key in allKeys) {
|
||||
final Map<String, dynamic> attributes = localeToResourceAttributes['en'][key];
|
||||
output.writeln(generateGetter(key, languageResources[key], attributes));
|
||||
}
|
||||
output.writeln('''
|
||||
}''');
|
||||
}
|
||||
|
||||
// Generate one private TranslationBundle subclass for each locale
|
||||
// with a country code. The parent of these subclasses is a const
|
||||
// instance of a translation bundle for the same locale, but without
|
||||
// a country code. These subclasses only override getters that
|
||||
// return different value than the parent class, or a resource identifier
|
||||
// that's not defined in the parent class. For example:
|
||||
//
|
||||
// class _Bundle_en_CA extends TranslationBundle {
|
||||
// const _Bundle_en_CA() : super(const _Bundle_en());
|
||||
// @override String get licensesPageTitle => r'Licences';
|
||||
// ...
|
||||
// }
|
||||
for (String language in languageToLocales.keys) {
|
||||
final Map<String, String> languageResources = localeToResources[language];
|
||||
for (String localeName in languageToLocales[language]) {
|
||||
if (localeName == language)
|
||||
output.writeln('}');
|
||||
int countryCodeCount = 0;
|
||||
final List<String> localeCodes = languageToLocales[languageName]..sort();
|
||||
for (String localeName in localeCodes) {
|
||||
if (localeName == languageName)
|
||||
continue;
|
||||
countryCodeCount += 1;
|
||||
final String camelCaseLocaleName = camelCase(localeName);
|
||||
final Map<String, String> localeResources = localeToResources[localeName];
|
||||
output.writeln('''
|
||||
|
||||
// ignore: camel_case_types
|
||||
class _Bundle_$localeName extends TranslationBundle {
|
||||
const _Bundle_$localeName() : super(const _Bundle_$language());''');
|
||||
final String localeClassName = 'MaterialLocalization$camelCaseLocaleName';
|
||||
final String constructor = generateConstructor(localeClassName, localeName);
|
||||
output.writeln('');
|
||||
output.writeln('/// The translations for ${describeLocale(localeName)} (`$localeName`).');
|
||||
output.writeln('class $localeClassName extends $languageClassName {');
|
||||
output.writeln(constructor);
|
||||
for (String key in localeResources.keys) {
|
||||
if (languageResources[key] == localeResources[key])
|
||||
continue;
|
||||
final String value = generateString(localeResources[key]);
|
||||
output.writeln('''
|
||||
@override String get $key => $value;''');
|
||||
final Map<String, dynamic> attributes = localeToResourceAttributes['en'][key];
|
||||
output.writeln(generateGetter(key, localeResources[key], attributes));
|
||||
}
|
||||
output.writeln('''
|
||||
}''');
|
||||
output.writeln('}');
|
||||
}
|
||||
if (countryCodeCount == 0) {
|
||||
supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)}');
|
||||
} else if (countryCodeCount == 1) {
|
||||
supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)} (plus one variant)');
|
||||
} else {
|
||||
supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)} (plus $countryCodeCount variants)');
|
||||
}
|
||||
}
|
||||
|
||||
// Generate the translationBundleForLocale function. Given a Locale
|
||||
// it returns the corresponding const TranslationBundle.
|
||||
// Generate the getTranslation function. Given a Locale it returns the
|
||||
// corresponding const GlobalMaterialLocalizations.
|
||||
output.writeln('''
|
||||
|
||||
TranslationBundle translationBundleForLocale(Locale locale) {
|
||||
/// The set of supported languages, as language code strings.
|
||||
///
|
||||
/// The [GlobalMaterialLocalizations.delegate] can generate localizations for
|
||||
/// any [Locale] with a language code from this set, regardless of the region.
|
||||
/// Some regions have specific support (e.g. `de` covers all forms of German,
|
||||
/// but there is support for `de-CH` specifically to override some of the
|
||||
/// translations for Switzerland).
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [getTranslation], whose documentation describes these values.
|
||||
final Set<String> kSupportedLanguages = new HashSet<String>.from(const <String>[
|
||||
${languageCodes.map((String value) => " '$value', // ${describeLocale(value)}").toList().join('\n')}
|
||||
]);
|
||||
|
||||
/// Creates a [GlobalMaterialLocalizations] instance for the given `locale`.
|
||||
///
|
||||
/// All of the function's arguments except `locale` will be passed to the [new
|
||||
/// GlobalMaterialLocalizations] constructor. (The `localeName` argument of that
|
||||
/// constructor is specified by the actual subclass constructor by this
|
||||
/// function.)
|
||||
///
|
||||
/// The following locales are supported by this package:
|
||||
///
|
||||
/// {@template flutter.localizations.languages}
|
||||
$supportedLocales/// {@endtemplate}
|
||||
///
|
||||
/// Generally speaking, this method is only intended to be used by
|
||||
/// [GlobalMaterialLocalizations.delegate].
|
||||
GlobalMaterialLocalizations getTranslation(
|
||||
Locale locale,
|
||||
intl.DateFormat fullYearFormat,
|
||||
intl.DateFormat mediumDateFormat,
|
||||
intl.DateFormat longDateFormat,
|
||||
intl.DateFormat yearMonthFormat,
|
||||
intl.NumberFormat decimalFormat,
|
||||
intl.NumberFormat twoDigitZeroPaddedFormat,
|
||||
) {
|
||||
switch (locale.languageCode) {''');
|
||||
const String arguments = 'fullYearFormat: fullYearFormat, mediumDateFormat: mediumDateFormat, longDateFormat: longDateFormat, yearMonthFormat: yearMonthFormat, decimalFormat: decimalFormat, twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat';
|
||||
for (String language in languageToLocales.keys) {
|
||||
if (languageToLocales[language].length == 1) {
|
||||
output.writeln('''
|
||||
case \'$language\':
|
||||
return const _Bundle_${languageToLocales[language][0]}();''');
|
||||
case '$language':
|
||||
return new MaterialLocalization${camelCase(languageToLocales[language][0])}($arguments);''');
|
||||
} else {
|
||||
output.writeln('''
|
||||
case \'$language\': {
|
||||
switch (locale.toString()) {''');
|
||||
case '$language': {
|
||||
switch (locale.countryCode) {''');
|
||||
for (String localeName in languageToLocales[language]) {
|
||||
if (localeName == language)
|
||||
continue;
|
||||
assert(localeName.contains('_'));
|
||||
final String countryCode = localeName.substring(localeName.indexOf('_') + 1);
|
||||
output.writeln('''
|
||||
case \'$localeName\':
|
||||
return const _Bundle_$localeName();''');
|
||||
case '$countryCode':
|
||||
return new MaterialLocalization${camelCase(localeName)}($arguments);''');
|
||||
}
|
||||
output.writeln('''
|
||||
}
|
||||
return const _Bundle_$language();
|
||||
return new MaterialLocalization${camelCase(language)}($arguments);
|
||||
}''');
|
||||
}
|
||||
}
|
||||
output.writeln('''
|
||||
}
|
||||
return const TranslationBundle(null);
|
||||
assert(false, 'getTranslation() called for unsupported locale "\$locale"');
|
||||
return null;
|
||||
}''');
|
||||
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
void processBundle(File file, String locale) {
|
||||
/// Returns the appropriate type for getters with the given attributes.
|
||||
///
|
||||
/// Typically "String", but some (e.g. "timeOfDayFormat") return enums.
|
||||
///
|
||||
/// Used by [generateGetter] below.
|
||||
String generateType(Map<String, dynamic> attributes) {
|
||||
if (attributes != null) {
|
||||
switch (attributes['x-flutter-type']) {
|
||||
case 'icuShortTimePattern':
|
||||
return 'TimeOfDayFormat';
|
||||
}
|
||||
}
|
||||
return 'String';
|
||||
}
|
||||
|
||||
/// Returns the appropriate name for getters with the given attributes.
|
||||
///
|
||||
/// Typically this is the key unmodified, but some have parameters, and
|
||||
/// the GlobalMaterialLocalizations class does the substitution, and for
|
||||
/// those we have to therefore provide an alternate name.
|
||||
///
|
||||
/// Used by [generateGetter] below.
|
||||
String generateKey(String key, Map<String, dynamic> attributes) {
|
||||
if (attributes != null) {
|
||||
if (attributes.containsKey('parameters'))
|
||||
return '${key}Raw';
|
||||
switch (attributes['x-flutter-type']) {
|
||||
case 'icuShortTimePattern':
|
||||
return '${key}Raw';
|
||||
}
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
const Map<String, String> _icuTimeOfDayToEnum = <String, String>{
|
||||
'HH:mm': 'TimeOfDayFormat.HH_colon_mm',
|
||||
'HH.mm': 'TimeOfDayFormat.HH_dot_mm',
|
||||
"HH 'h' mm": 'TimeOfDayFormat.frenchCanadian',
|
||||
'HH:mm น.': 'TimeOfDayFormat.HH_colon_mm',
|
||||
'H:mm': 'TimeOfDayFormat.H_colon_mm',
|
||||
'h:mm a': 'TimeOfDayFormat.h_colon_mm_space_a',
|
||||
'a h:mm': 'TimeOfDayFormat.a_space_h_colon_mm',
|
||||
'ah:mm': 'TimeOfDayFormat.a_space_h_colon_mm',
|
||||
};
|
||||
|
||||
/// Returns the literal that describes the value returned by getters
|
||||
/// with the given attributes.
|
||||
///
|
||||
/// This handles cases like the value being a literal `null`, an enum, and so
|
||||
/// on. The default is to treat the value as a string and escape it and quote
|
||||
/// it.
|
||||
///
|
||||
/// Used by [generateGetter] below.
|
||||
String generateValue(String value, Map<String, dynamic> attributes) {
|
||||
if (value == null)
|
||||
return null;
|
||||
if (attributes != null) {
|
||||
switch (attributes['x-flutter-type']) {
|
||||
case 'icuShortTimePattern':
|
||||
if (!_icuTimeOfDayToEnum.containsKey(value)) {
|
||||
throw new Exception(
|
||||
'"$value" is not one of the ICU short time patterns supported '
|
||||
'by the material library. Here is the list of supported '
|
||||
'patterns:\n ' + _icuTimeOfDayToEnum.keys.join('\n ')
|
||||
);
|
||||
}
|
||||
return _icuTimeOfDayToEnum[value];
|
||||
}
|
||||
}
|
||||
return generateString(value);
|
||||
}
|
||||
|
||||
/// Combines [generateType], [generateKey], and [generateValue] to return
|
||||
/// the source of getters for the GlobalMaterialLocalizations subclass.
|
||||
String generateGetter(String key, String value, Map<String, dynamic> attributes) {
|
||||
final String type = generateType(attributes);
|
||||
key = generateKey(key, attributes);
|
||||
value = generateValue(value, attributes);
|
||||
return '''
|
||||
|
||||
@override
|
||||
$type get $key => $value;''';
|
||||
}
|
||||
|
||||
/// Returns the source of the constructor for a GlobalMaterialLocalizations
|
||||
/// subclass.
|
||||
String generateConstructor(String className, String localeName) {
|
||||
return '''
|
||||
/// Create an instance of the translation bundle for ${describeLocale(localeName)}.
|
||||
///
|
||||
/// For details on the meaning of the arguments, see [GlobalMaterialLocalizations].
|
||||
const $className({
|
||||
String localeName = '$localeName',
|
||||
@required intl.DateFormat fullYearFormat,
|
||||
@required intl.DateFormat mediumDateFormat,
|
||||
@required intl.DateFormat longDateFormat,
|
||||
@required intl.DateFormat yearMonthFormat,
|
||||
@required intl.NumberFormat decimalFormat,
|
||||
@required intl.NumberFormat twoDigitZeroPaddedFormat,
|
||||
}) : super(
|
||||
localeName: localeName,
|
||||
fullYearFormat: fullYearFormat,
|
||||
mediumDateFormat: mediumDateFormat,
|
||||
longDateFormat: longDateFormat,
|
||||
yearMonthFormat: yearMonthFormat,
|
||||
decimalFormat: decimalFormat,
|
||||
twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat,
|
||||
);''';
|
||||
}
|
||||
|
||||
/// Parse the data for a locale from a file, and store it in the [attributes]
|
||||
/// and [resources] keys.
|
||||
void processBundle(File file, { @required String locale }) {
|
||||
assert(locale != null);
|
||||
localeToResources[locale] ??= <String, String>{};
|
||||
localeToResourceAttributes[locale] ??= <String, dynamic>{};
|
||||
final Map<String, String> resources = localeToResources[locale];
|
||||
@@ -244,7 +391,7 @@ void processBundle(File file, String locale) {
|
||||
}
|
||||
}
|
||||
|
||||
void main(List<String> rawArgs) {
|
||||
Future<void> main(List<String> rawArgs) async {
|
||||
checkCwdIsRepoRoot('gen_localizations');
|
||||
final GeneratorOptions options = parseArgs(rawArgs);
|
||||
|
||||
@@ -252,32 +399,36 @@ void main(List<String> rawArgs) {
|
||||
// is the 2nd command line argument, lc is a language code and cc is the country
|
||||
// code. In most cases both codes are just two characters.
|
||||
|
||||
final Directory directory = new Directory(pathlib.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'));
|
||||
final Directory directory = new Directory(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'));
|
||||
final RegExp filenameRE = new RegExp(r'material_(\w+)\.arb$');
|
||||
|
||||
exitWithError(
|
||||
validateEnglishLocalizations(new File(pathlib.join(directory.path, 'material_en.arb')))
|
||||
);
|
||||
try {
|
||||
validateEnglishLocalizations(new File(path.join(directory.path, 'material_en.arb')));
|
||||
} on ValidationError catch (exception) {
|
||||
exitWithError('$exception');
|
||||
}
|
||||
|
||||
await precacheLanguageAndRegionTags();
|
||||
|
||||
for (FileSystemEntity entity in directory.listSync()) {
|
||||
final String path = entity.path;
|
||||
if (FileSystemEntity.isFileSync(path) && filenameRE.hasMatch(path)) {
|
||||
final String locale = filenameRE.firstMatch(path)[1];
|
||||
processBundle(new File(path), locale);
|
||||
final String entityPath = entity.path;
|
||||
if (FileSystemEntity.isFileSync(entityPath) && filenameRE.hasMatch(entityPath)) {
|
||||
processBundle(new File(entityPath), locale: filenameRE.firstMatch(entityPath)[1]);
|
||||
}
|
||||
}
|
||||
|
||||
exitWithError(
|
||||
validateLocalizations(localeToResources, localeToResourceAttributes)
|
||||
);
|
||||
try {
|
||||
validateLocalizations(localeToResources, localeToResourceAttributes);
|
||||
} on ValidationError catch (exception) {
|
||||
exitWithError('$exception');
|
||||
}
|
||||
|
||||
const String regenerate = 'dart dev/tools/gen_localizations.dart --overwrite';
|
||||
final StringBuffer buffer = new StringBuffer();
|
||||
buffer.writeln(outputHeader.replaceFirst('@(regenerate)', regenerate));
|
||||
buffer.writeln(outputHeader.replaceFirst('@(regenerate)', 'dart dev/tools/gen_localizations.dart --overwrite'));
|
||||
buffer.write(generateTranslationBundles());
|
||||
|
||||
if (options.writeToFile) {
|
||||
final File localizationsFile = new File(pathlib.join(directory.path, 'localizations.dart'));
|
||||
final File localizationsFile = new File(path.join(directory.path, 'localizations.dart'));
|
||||
localizationsFile.writeAsStringSync(buffer.toString());
|
||||
} else {
|
||||
stdout.write(buffer.toString());
|
||||
|
||||
@@ -2,15 +2,16 @@
|
||||
// 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:meta/meta.dart';
|
||||
|
||||
void exitWithError(String errorMessage) {
|
||||
if (errorMessage == null)
|
||||
return;
|
||||
stderr.writeln('Fatal Error: $errorMessage');
|
||||
assert(errorMessage != null);
|
||||
stderr.writeln('fatal: $errorMessage');
|
||||
exit(1);
|
||||
}
|
||||
|
||||
@@ -25,6 +26,13 @@ void checkCwdIsRepoRoot(String commandName) {
|
||||
}
|
||||
}
|
||||
|
||||
String camelCase(String locale) {
|
||||
return locale
|
||||
.split('_')
|
||||
.map((String part) => part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase())
|
||||
.join('');
|
||||
}
|
||||
|
||||
GeneratorOptions parseArgs(List<String> rawArgs) {
|
||||
final argslib.ArgParser argParser = new argslib.ArgParser()
|
||||
..addFlag(
|
||||
@@ -45,3 +53,90 @@ class GeneratorOptions {
|
||||
|
||||
final bool writeToFile;
|
||||
}
|
||||
|
||||
const String registry = 'https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry';
|
||||
|
||||
// See also //master/tools/gen_locale.dart in the engine repo.
|
||||
Map<String, List<String>> _parseSection(String section) {
|
||||
final Map<String, List<String>> result = <String, List<String>>{};
|
||||
List<String> lastHeading;
|
||||
for (String line in section.split('\n')) {
|
||||
if (line == '')
|
||||
continue;
|
||||
if (line.startsWith(' ')) {
|
||||
lastHeading[lastHeading.length - 1] = '${lastHeading.last}${line.substring(1)}';
|
||||
continue;
|
||||
}
|
||||
final int colon = line.indexOf(':');
|
||||
if (colon <= 0)
|
||||
throw 'not sure how to deal with "$line"';
|
||||
final String name = line.substring(0, colon);
|
||||
final String value = line.substring(colon + 2);
|
||||
lastHeading = result.putIfAbsent(name, () => <String>[]);
|
||||
result[name].add(value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
final Map<String, String> _languages = <String, String>{};
|
||||
final Map<String, String> _regions = <String, String>{};
|
||||
final Map<String, String> _scripts = <String, String>{};
|
||||
const String kProvincePrefix = ', Province of ';
|
||||
const String kParentheticalPrefix = ' (';
|
||||
|
||||
/// Prepares the data for the [describeLocale] method below.
|
||||
///
|
||||
/// The data is obtained from the official IANA registry.
|
||||
Future<void> precacheLanguageAndRegionTags() async {
|
||||
final HttpClient client = new HttpClient();
|
||||
final HttpClientRequest request = await client.getUrl(Uri.parse(registry));
|
||||
final HttpClientResponse response = await request.close();
|
||||
final String body = (await response.transform(utf8.decoder).toList()).join('');
|
||||
client.close(force: true);
|
||||
final List<Map<String, List<String>>> sections = body.split('%%').skip(1).map<Map<String, List<String>>>(_parseSection).toList();
|
||||
for (Map<String, List<String>> section in sections) {
|
||||
assert(section.containsKey('Type'), section.toString());
|
||||
final String type = section['Type'].single;
|
||||
if (type == 'language' || type == 'region' || type == 'script') {
|
||||
assert(section.containsKey('Subtag') && section.containsKey('Description'), section.toString());
|
||||
final String subtag = section['Subtag'].single;
|
||||
String description = section['Description'].join(' ');
|
||||
if (description.startsWith('United '))
|
||||
description = 'the $description';
|
||||
if (description.contains(kParentheticalPrefix))
|
||||
description = description.substring(0, description.indexOf(kParentheticalPrefix));
|
||||
if (description.contains(kProvincePrefix))
|
||||
description = description.substring(0, description.indexOf(kProvincePrefix));
|
||||
if (description.endsWith(' Republic'))
|
||||
description = 'the $description';
|
||||
switch (type) {
|
||||
case 'language':
|
||||
_languages[subtag] = description;
|
||||
break;
|
||||
case 'region':
|
||||
_regions[subtag] = description;
|
||||
break;
|
||||
case 'script':
|
||||
_scripts[subtag] = description;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String describeLocale(String tag) {
|
||||
final List<String> subtags = tag.split('_');
|
||||
assert(subtags.isNotEmpty);
|
||||
assert(_languages.containsKey(subtags[0]));
|
||||
final String language = _languages[subtags[0]];
|
||||
if (subtags.length >= 2) {
|
||||
final String region = _regions[subtags[1]];
|
||||
final String script = _scripts[subtags[1]];
|
||||
assert(region != null || script != null);
|
||||
if (region != null)
|
||||
return '$language, as used in $region';
|
||||
if (script != null)
|
||||
return '$language, using the $script script';
|
||||
}
|
||||
return '$language';
|
||||
}
|
||||
@@ -5,6 +5,18 @@
|
||||
import 'dart:convert' show json;
|
||||
import 'dart:io';
|
||||
|
||||
// The first suffix in kPluralSuffixes must be "Other". "Other" is special
|
||||
// because it's the only one that is required.
|
||||
const List<String> kPluralSuffixes = <String>['Other', 'Zero', 'One', 'Two', 'Few', 'Many'];
|
||||
final RegExp kPluralRegexp = new RegExp(r'(\w*)(' + kPluralSuffixes.skip(1).join(r'|') + r')$');
|
||||
|
||||
class ValidationError implements Exception {
|
||||
ValidationError(this. message);
|
||||
final String message;
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// Sanity checking of the @foo metadata in the English translations,
|
||||
/// material_en.arb.
|
||||
///
|
||||
@@ -14,13 +26,13 @@ import 'dart:io';
|
||||
/// - Each @foo resource must have a Map value with a String valued
|
||||
/// description entry.
|
||||
///
|
||||
/// Returns an error message upon failure, null on success.
|
||||
String validateEnglishLocalizations(File file) {
|
||||
/// Throws an exception upon failure.
|
||||
void validateEnglishLocalizations(File file) {
|
||||
final StringBuffer errorMessages = new StringBuffer();
|
||||
|
||||
if (!file.existsSync()) {
|
||||
errorMessages.writeln('English localizations do not exist: $file');
|
||||
return errorMessages.toString();
|
||||
throw new ValidationError(errorMessages.toString());
|
||||
}
|
||||
|
||||
final Map<String, dynamic> bundle = json.decode(file.readAsStringSync());
|
||||
@@ -36,7 +48,7 @@ String validateEnglishLocalizations(File file) {
|
||||
final int suffixIndex = resourceId.indexOf(suffix);
|
||||
return suffixIndex != -1 && bundle['@${resourceId.substring(0, suffixIndex)}'] != null;
|
||||
}
|
||||
if (<String>['Zero', 'One', 'Two', 'Few', 'Many', 'Other'].any(checkPluralResource))
|
||||
if (kPluralSuffixes.any(checkPluralResource))
|
||||
continue;
|
||||
|
||||
errorMessages.writeln('A value was not specified for @$resourceId');
|
||||
@@ -70,7 +82,8 @@ String validateEnglishLocalizations(File file) {
|
||||
}
|
||||
}
|
||||
|
||||
return errorMessages.isEmpty ? null : errorMessages.toString();
|
||||
if (errorMessages.isNotEmpty)
|
||||
throw new ValidationError(errorMessages.toString());
|
||||
}
|
||||
|
||||
/// Enforces the following invariants in our localizations:
|
||||
@@ -81,8 +94,8 @@ String validateEnglishLocalizations(File file) {
|
||||
/// Uses "en" localizations as the canonical source of locale keys that other
|
||||
/// locales are compared against.
|
||||
///
|
||||
/// If validation fails, return an error message, otherwise return null.
|
||||
String validateLocalizations(
|
||||
/// If validation fails, throws an exception.
|
||||
void validateLocalizations(
|
||||
Map<String, Map<String, String>> localeToResources,
|
||||
Map<String, Map<String, dynamic>> localeToAttributes,
|
||||
) {
|
||||
@@ -99,12 +112,9 @@ String validateLocalizations(
|
||||
// Many languages require only a subset of these variations, so we do not
|
||||
// require them so long as the "Other" variation exists.
|
||||
bool isPluralVariation(String key) {
|
||||
final RegExp pluralRegexp = new RegExp(r'(\w*)(Zero|One|Two|Few|Many)$');
|
||||
final Match pluralMatch = pluralRegexp.firstMatch(key);
|
||||
|
||||
final Match pluralMatch = kPluralRegexp.firstMatch(key);
|
||||
if (pluralMatch == null)
|
||||
return false;
|
||||
|
||||
final String prefix = pluralMatch[1];
|
||||
return resources.containsKey('${prefix}Other');
|
||||
}
|
||||
@@ -151,7 +161,6 @@ String validateLocalizations(
|
||||
..writeln(' "notUsed": "Sindhi time format does not use a.m. indicator"')
|
||||
..writeln('}');
|
||||
}
|
||||
return errorMessages.toString();
|
||||
throw new ValidationError(errorMessages.toString());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user