Cupertino localization step 3: in-place move some material tools around to make room for cupertino (#29644)

This commit is contained in:
xster
2019-03-29 15:57:09 -07:00
committed by GitHub
parent d166a8d81e
commit f2d671c15c
11 changed files with 43 additions and 44 deletions

View File

@@ -0,0 +1,180 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// This program extracts localized date symbols and patterns from the intl
/// package for the subset of locales supported by the flutter_localizations
/// package.
///
/// The extracted data is written into:
/// packages/flutter_localizations/lib/src/l10n/generated_date_localizations.dart
///
/// ## Usage
///
/// Run this program from the root of the git repository.
///
/// The following outputs the generated Dart code to the console as a dry run:
///
/// ```
/// dart dev/tools/localization/gen_date_localizations.dart
/// ```
///
/// If the data looks good, use the `--overwrite` option to overwrite the
/// lib/src/l10n/date_localizations.dart file:
///
/// ```
/// dart dev/tools/localization/gen_date_localizations.dart --overwrite
/// ```
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'localizations_utils.dart';
const String _kCommandName = 'gen_date_localizations.dart';
Future<void> main(List<String> rawArgs) async {
checkCwdIsRepoRoot(_kCommandName);
final bool writeToFile = parseArgs(rawArgs).writeToFile;
final File dotPackagesFile = File(path.join('packages', 'flutter_localizations', '.packages'));
final bool dotPackagesExists = dotPackagesFile.existsSync();
if (!dotPackagesExists) {
exitWithError(
'File not found: ${dotPackagesFile.path}. $_kCommandName must be run '
'after a successful "flutter update-packages".'
);
}
final String pathToIntl = dotPackagesFile
.readAsStringSync()
.split('\n')
.firstWhere(
(String line) => line.startsWith('intl:'),
orElse: () {
exitWithError('intl dependency not found in ${dotPackagesFile.path}');
return null; // unreachable
},
)
.split(':')
.last;
final Directory dateSymbolsDirectory = Directory(path.join(pathToIntl, 'src', 'data', 'dates', 'symbols'));
final Map<String, File> symbolFiles = _listIntlData(dateSymbolsDirectory);
final Directory datePatternsDirectory = Directory(path.join(pathToIntl, 'src', 'data', 'dates', 'patterns'));
final Map<String, File> patternFiles = _listIntlData(datePatternsDirectory);
final List<String> materialLocales = _materialLocales().toList();
final StringBuffer buffer = StringBuffer();
buffer.writeln(
'''
// Copyright 2017 The Chromium Authors. All rights reserved.
// 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.
// To regenerate run (omit --overwrite to print to console instead of the file):
// dart --enable-asserts dev/tools/localization/gen_date_localizations.dart --overwrite
'''
);
buffer.writeln('''
/// The subset of date symbols supported by the intl package which are also
/// supported by flutter_localizations.''');
buffer.writeln('const Map<String, dynamic> dateSymbols = <String, dynamic> {');
symbolFiles.forEach((String locale, File data) {
if (materialLocales.contains(locale))
buffer.writeln(_jsonToMapEntry(locale, json.decode(data.readAsStringSync())));
});
buffer.writeln('};');
// Code that uses datePatterns expects it to contain values of type
// Map<String, String> not Map<String, dynamic>.
buffer.writeln('''
/// The subset of date patterns supported by the intl package which are also
/// supported by flutter_localizations.''');
buffer.writeln('const Map<String, Map<String, String>> datePatterns = <String, Map<String, String>> {');
patternFiles.forEach((String locale, File data) {
if (materialLocales.contains(locale)) {
final Map<String, dynamic> patterns = json.decode(data.readAsStringSync());
buffer.writeln("'$locale': <String, String>{");
patterns.forEach((String key, dynamic value) {
assert(value is String);
buffer.writeln(_jsonToMapEntry(key, value));
});
buffer.writeln('},');
}
});
buffer.writeln('};');
if (writeToFile) {
final File dateLocalizationsFile = File(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n', 'generated_date_localizations.dart'));
dateLocalizationsFile.writeAsStringSync(buffer.toString());
Process.runSync(path.join('bin', 'cache', 'dart-sdk', 'bin', 'dartfmt'), <String>[
'-w',
dateLocalizationsFile.path,
]);
} else {
print(buffer);
}
}
String _jsonToMapEntry(String key, dynamic value) {
return "'$key': ${_jsonToMap(value)},";
}
String _jsonToMap(dynamic json) {
if (json == null || json is num || json is bool)
return '$json';
if (json is String) {
if (json.contains("'"))
return 'r"""$json"""';
else
return "r'''$json'''";
}
if (json is Iterable)
return '<dynamic>[${json.map<String>(_jsonToMap).join(',')}]';
if (json is Map<String, dynamic>) {
final StringBuffer buffer = StringBuffer('<String, dynamic>{');
json.forEach((String key, dynamic value) {
buffer.writeln(_jsonToMapEntry(key, value));
});
buffer.write('}');
return buffer.toString();
}
throw 'Unsupported JSON type ${json.runtimeType} of value $json.';
}
Iterable<String> _materialLocales() sync* {
final RegExp filenameRE = RegExp(r'material_(\w+)\.arb$');
final Directory materialLocalizationsDirectory = Directory(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'));
for (FileSystemEntity entity in materialLocalizationsDirectory.listSync()) {
final String filePath = entity.path;
if (FileSystemEntity.isFileSync(filePath) && filenameRE.hasMatch(filePath))
yield filenameRE.firstMatch(filePath)[1];
}
}
Map<String, File> _listIntlData(Directory directory) {
final Map<String, File> localeFiles = <String, File>{};
for (FileSystemEntity entity in directory.listSync()) {
final String filePath = entity.path;
if (FileSystemEntity.isFileSync(filePath) && filePath.endsWith('.json')) {
final String locale = path.basenameWithoutExtension(filePath);
localeFiles[locale] = entity;
}
}
final List<String> locales = localeFiles.keys.toList(growable: false);
locales.sort();
return Map<String, File>.fromIterable(locales, value: (dynamic locale) => localeFiles[locale]);
}

View File

@@ -0,0 +1,639 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This program generates a getMaterialTranslation() function that looks up the
// translations provided by the arb files. The returned value is a generated
// instance of GlobalMaterialLocalizations that corresponds to a single
// locale.
//
// The *.arb files are in packages/flutter_localizations/lib/src/l10n.
//
// The arb (JSON) format files must contain a single map indexed by locale.
// Each map value is itself a map with resource identifier keys and localized
// resource string values.
//
// The arb filenames are expected to have the form "material_(\w+)\.arb", where
// the group following "_" identifies the language code and the country code,
// e.g. "material_en.arb" or "material_en_GB.arb". In most cases both codes are
// just two characters.
//
// This app is typically run by hand when a module's .arb files have been
// updated.
//
// ## Usage
//
// Run this program from the root of the git repository.
//
// The following outputs the generated Dart code to the console as a dry run:
//
// ```
// dart dev/tools/localization/gen_localizations.dart
// ```
//
// If the data looks good, use the `-w` or `--overwrite` option to overwrite the
// packages/flutter_localizations/lib/src/l10n/generated_material_localizations.dart file:
//
// ```
// dart dev/tools/localization/gen_localizations.dart --overwrite
// ```
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:meta/meta.dart';
import 'localizations_utils.dart';
import 'localizations_validator.dart';
const String outputHeader = '''
// Copyright 2017 The Chromium Authors. All rights reserved.
// 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.
// 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<LocaleInfo, Map<String, String>> localeToResources = <LocaleInfo, Map<String, String>>{};
/// Maps locales to resource key/attributes pairs.
///
/// See also: <https://github.com/googlei18n/app-resource-bundle/wiki/ApplicationResourceBundleSpecification#resource-attributes>
final Map<LocaleInfo, Map<String, dynamic>> localeToResourceAttributes = <LocaleInfo, Map<String, dynamic>>{};
/// Set that holds the locales that were assumed from the existing locales.
///
/// For example, when the data lacks data for zh_Hant, we will use the data of
/// the first Hant Chinese locale as a default by repeating the data. If an
/// explicit match is later found, we can reference this set to see if we should
/// overwrite the existing assumed data.
final Set<LocaleInfo> assumedLocales = <LocaleInfo>{};
/// 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'";
final StringBuffer output = StringBuffer();
bool started = false; // Have we started writing a raw string.
for (int i = 0; i < s.length; i++) {
if (s[i] == "'") {
if (started)
output.write("'");
output.write(' "\'" ');
started = false;
} else if (!started) {
output.write("r'${s[i]}");
started = true;
} else {
output.write(s[i]);
}
}
if (started)
output.write("'");
return output.toString();
}
/// This is the core of this script; it generates the code used for translations.
String generateTranslationBundles() {
final StringBuffer output = StringBuffer();
final StringBuffer supportedLocales = StringBuffer();
final Map<String, List<LocaleInfo>> languageToLocales = <String, List<LocaleInfo>>{};
final Map<String, Set<String>> languageToScriptCodes = <String, Set<String>>{};
// Used to calculate if there are any corresponding countries for a given language and script.
final Map<LocaleInfo, Set<String>> languageAndScriptToCountryCodes = <LocaleInfo, Set<String>>{};
final Set<String> allResourceIdentifiers = <String>{};
for (LocaleInfo locale in localeToResources.keys.toList()..sort()) {
if (locale.scriptCode != null) {
languageToScriptCodes[locale.languageCode] ??= <String>{};
languageToScriptCodes[locale.languageCode].add(locale.scriptCode);
}
if (locale.countryCode != null && locale.scriptCode != null) {
final LocaleInfo key = LocaleInfo.fromString(locale.languageCode + '_' + locale.scriptCode);
languageAndScriptToCountryCodes[key] ??= <String>{};
languageAndScriptToCountryCodes[key].add(locale.countryCode);
}
languageToLocales[locale.languageCode] ??= <LocaleInfo>[];
languageToLocales[locale.languageCode].add(locale);
allResourceIdentifiers.addAll(localeToResources[locale].keys);
}
output.writeln('''
// The classes defined here encode all of the translations found in the
// `flutter_localizations/lib/src/l10n/*.arb` files.
//
// These classes are constructed by the [getMaterialTranslation] method at the
// bottom of this file, and used by the [_MaterialLocalizationsDelegate.load]
// method defined in `flutter_localizations/lib/src/material_localizations.dart`.''');
// We generate one class per supported language (e.g.
// `MaterialLocalizationEn`). These implement everything that is needed by
// GlobalMaterialLocalizations.
// We also generate one subclass for each locale with a script code (e.g.
// `MaterialLocalizationZhHant`). Their superclasses are the aforementioned
// language classes for the same locale but without a script code (e.g.
// `MaterialLocalizationZh`).
// 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`).
// If scriptCodes for a language are defined, we expect a scriptCode to be
// defined for locales that contain a countryCode. The superclass becomes
// the script sublcass (e.g. `MaterialLocalizationZhHant`) and the generated
// subclass will also contain the script code (e.g. `MaterialLocalizationZhHantTW`).
// When scriptCodes are not defined for languages that use scriptCodes to distinguish
// between significantly differing scripts, we assume the scriptCodes in the
// [LocaleInfo.fromString] factory and add it to the [LocaleInfo]. We then generate
// the script classes based on the first locale that we assume to use the script.
final List<String> allKeys = allResourceIdentifiers.toList()..sort();
final List<String> languageCodes = languageToLocales.keys.toList()..sort();
final LocaleInfo canonicalLocale = LocaleInfo.fromString('en');
for (String languageName in languageCodes) {
final LocaleInfo languageLocale = LocaleInfo.fromString(languageName);
writeClassHeader(output, languageLocale, 'GlobalMaterialLocalizations');
final Map<String, String> languageResources = localeToResources[languageLocale];
for (String key in allKeys) {
final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key];
output.writeln(generateGetter(key, languageResources[key], attributes));
}
output.writeln('}');
int countryCodeCount = 0;
int scriptCodeCount = 0;
if (languageToScriptCodes.containsKey(languageName)) {
scriptCodeCount = languageToScriptCodes[languageName].length;
// Language has scriptCodes, so we need to properly fallback countries to corresponding
// script default values before language default values.
for (String scriptCode in languageToScriptCodes[languageName]) {
final LocaleInfo scriptBaseLocale = LocaleInfo.fromString(languageName + '_' + scriptCode);
writeClassHeader(output, scriptBaseLocale, 'MaterialLocalization${camelCase(languageLocale)}');
final Map<String, String> scriptResources = localeToResources[scriptBaseLocale];
for (String key in scriptResources.keys) {
if (languageResources[key] == scriptResources[key])
continue;
final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key];
output.writeln(generateGetter(key, scriptResources[key], attributes));
}
output.writeln('}');
final List<LocaleInfo> localeCodes = languageToLocales[languageName]..sort();
for (LocaleInfo locale in localeCodes) {
if (locale.originalString == languageName)
continue;
if (locale.originalString == languageName + '_' + scriptCode)
continue;
if (locale.scriptCode != scriptCode)
continue;
countryCodeCount += 1;
writeClassHeader(output, locale, 'MaterialLocalization${camelCase(scriptBaseLocale)}');
final Map<String, String> localeResources = localeToResources[locale];
for (String key in localeResources.keys) {
// When script fallback contains the key, we compare to it instead of language fallback.
if (scriptResources.containsKey(key) ? scriptResources[key] == localeResources[key] : languageResources[key] == localeResources[key])
continue;
final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key];
output.writeln(generateGetter(key, localeResources[key], attributes));
}
output.writeln('}');
}
}
} else {
// No scriptCode. Here, we do not compare against script default (because it
// doesn't exist).
final List<LocaleInfo> localeCodes = languageToLocales[languageName]..sort();
for (LocaleInfo locale in localeCodes) {
if (locale.originalString == languageName)
continue;
countryCodeCount += 1;
final Map<String, String> localeResources = localeToResources[locale];
writeClassHeader(output, locale, 'MaterialLocalization${camelCase(languageLocale)}');
for (String key in localeResources.keys) {
if (languageResources[key] == localeResources[key])
continue;
final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key];
output.writeln(generateGetter(key, localeResources[key], attributes));
}
output.writeln('}');
}
}
final String scriptCodeMessage = scriptCodeCount == 0 ? '' : ' and $scriptCodeCount script' + (scriptCodeCount == 1 ? '' : 's');
if (countryCodeCount == 0) {
if (scriptCodeCount == 0)
supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)}');
else
supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)} (plus $scriptCodeCount script' + (scriptCodeCount == 1 ? '' : 's') + ')');
} else if (countryCodeCount == 1) {
supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)} (plus one country variation$scriptCodeMessage)');
} else {
supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)} (plus $countryCodeCount country variations$scriptCodeMessage)');
}
}
// Generate the getMaterialTranslation function. Given a Locale it returns the
// corresponding const GlobalMaterialLocalizations.
output.writeln('''
/// 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:
///
/// * [getMaterialTranslation], whose documentation describes these values.
final Set<String> kSupportedLanguages = HashSet<String>.from(const <String>[
${languageCodes.map<String>((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 getMaterialTranslation(
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) {
// Only one instance of the language.
if (languageToLocales[language].length == 1) {
output.writeln('''
case '$language':
return MaterialLocalization${camelCase(languageToLocales[language][0])}($arguments);''');
} else if (!languageToScriptCodes.containsKey(language)) { // Does not distinguish between scripts. Switch on countryCode directly.
output.writeln('''
case '$language': {
switch (locale.countryCode) {''');
for (LocaleInfo locale in languageToLocales[language]) {
if (locale.originalString == language)
continue;
assert(locale.length > 1);
final String countryCode = locale.countryCode;
output.writeln('''
case '$countryCode':
return MaterialLocalization${camelCase(locale)}($arguments);''');
}
output.writeln('''
}
return MaterialLocalization${camelCase(LocaleInfo.fromString(language))}($arguments);
}''');
} else { // Language has scriptCode, add additional switch logic.
bool hasCountryCode = false;
output.writeln('''
case '$language': {
switch (locale.scriptCode) {''');
for (String scriptCode in languageToScriptCodes[language]) {
final LocaleInfo scriptLocale = LocaleInfo.fromString(language + '_' + scriptCode);
output.writeln('''
case '$scriptCode': {''');
if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) {
output.writeln('''
switch (locale.countryCode) {''');
for (LocaleInfo locale in languageToLocales[language]) {
if (locale.countryCode == null)
continue;
else
hasCountryCode = true;
if (locale.originalString == language)
continue;
if (locale.scriptCode != scriptCode && locale.scriptCode != null)
continue;
final String countryCode = locale.countryCode;
output.writeln('''
case '$countryCode':
return MaterialLocalization${camelCase(locale)}($arguments);''');
}
}
// Return a fallback locale that matches scriptCode, but not countryCode.
//
// Explicitly defined scriptCode fallback:
if (languageToLocales[language].contains(scriptLocale)) {
if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) {
output.writeln('''
}''');
}
output.writeln('''
return MaterialLocalization${camelCase(scriptLocale)}($arguments);
}''');
} else {
// Not Explicitly defined, fallback to first locale with the same language and
// script:
for (LocaleInfo locale in languageToLocales[language]) {
if (locale.scriptCode != scriptCode)
continue;
if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) {
output.writeln('''
}''');
}
output.writeln('''
return MaterialLocalization${camelCase(scriptLocale)}($arguments);
}''');
break;
}
}
}
output.writeln('''
}''');
if (hasCountryCode) {
output.writeln('''
switch (locale.countryCode) {''');
for (LocaleInfo locale in languageToLocales[language]) {
if (locale.originalString == language)
continue;
assert(locale.length > 1);
if (locale.countryCode == null)
continue;
final String countryCode = locale.countryCode;
output.writeln('''
case '$countryCode':
return MaterialLocalization${camelCase(locale)}($arguments);''');
}
output.writeln('''
}''');
}
output.writeln('''
return MaterialLocalization${camelCase(LocaleInfo.fromString(language))}($arguments);
}''');
}
}
output.writeln('''
}
assert(false, 'getMaterialTranslation() called for unsupported locale "\$locale"');
return null;
}''');
return output.toString();
}
/// Writes the header of each class which corresponds to a locale.
void writeClassHeader(StringBuffer output, LocaleInfo locale, String superClass) {
final String camelCaseName = camelCase(locale);
final String className = 'MaterialLocalization$camelCaseName';
final String constructor = generateConstructor(className, locale);
output.writeln('');
output.writeln('/// The translations for ${describeLocale(locale.originalString)} (`${locale.originalString}`).');
output.writeln('class $className extends $superClass {');
output.writeln(constructor);
}
/// 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';
case 'scriptCategory':
return 'ScriptCategory';
}
}
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',
};
const Map<String, String> _scriptCategoryToEnum = <String, String>{
'English-like': 'ScriptCategory.englishLike',
'dense': 'ScriptCategory.dense',
'tall': 'ScriptCategory.tall',
};
/// 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 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];
case 'scriptCategory':
if (!_scriptCategoryToEnum.containsKey(value)) {
throw Exception(
'"$value" is not one of the scriptCategory values supported '
'by the material library. Here is the list of supported '
'values:\n ' + _scriptCategoryToEnum.keys.join('\n ')
);
}
return _scriptCategoryToEnum[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, LocaleInfo locale) {
final String localeName = locale.originalString;
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 localeString }) {
assert(localeString != null);
// Helper method to fill the maps with the correct data from file.
void populateResources(LocaleInfo locale) {
final Map<String, String> resources = localeToResources[locale];
final Map<String, dynamic> attributes = localeToResourceAttributes[locale];
final Map<String, dynamic> bundle = json.decode(file.readAsStringSync());
for (String key in bundle.keys) {
// The ARB file resource "attributes" for foo are called @foo.
if (key.startsWith('@'))
attributes[key.substring(1)] = bundle[key];
else
resources[key] = bundle[key];
}
}
// Only pre-assume scriptCode if there is a country or script code to assume off of.
// When we assume scriptCode based on languageCode-only, we want this initial pass
// to use the un-assumed version as a base class.
LocaleInfo locale = LocaleInfo.fromString(localeString, deriveScriptCode: localeString.split('_').length > 1);
// Allow overwrite if the existing data is assumed.
if (assumedLocales.contains(locale)) {
localeToResources[locale] = <String, String>{};
localeToResourceAttributes[locale] = <String, dynamic>{};
assumedLocales.remove(locale);
} else {
localeToResources[locale] ??= <String, String>{};
localeToResourceAttributes[locale] ??= <String, dynamic>{};
}
populateResources(locale);
// Add an assumed locale to default to when there is no info on scriptOnly locales.
locale = LocaleInfo.fromString(localeString, deriveScriptCode: true);
if (locale.scriptCode != null) {
final LocaleInfo scriptLocale = LocaleInfo.fromString(locale.languageCode + '_' + locale.scriptCode);
if (!localeToResources.containsKey(scriptLocale)) {
assumedLocales.add(scriptLocale);
localeToResources[scriptLocale] ??= <String, String>{};
localeToResourceAttributes[scriptLocale] ??= <String, dynamic>{};
populateResources(scriptLocale);
}
}
}
Future<void> main(List<String> rawArgs) async {
checkCwdIsRepoRoot('gen_localizations');
final GeneratorOptions options = parseArgs(rawArgs);
// filenames are assumed to end in "prefix_lc.arb" or "prefix_lc_cc.arb", where prefix
// 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 = Directory(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'));
final RegExp materialFilenameRE = RegExp(r'material_(\w+)\.arb$');
try {
validateEnglishLocalizations(File(path.join(directory.path, 'material_en.arb')));
} on ValidationError catch (exception) {
exitWithError('$exception');
}
await precacheLanguageAndRegionTags();
for (FileSystemEntity entity in directory.listSync()) {
final String entityPath = entity.path;
if (FileSystemEntity.isFileSync(entityPath) && materialFilenameRE.hasMatch(entityPath)) {
processBundle(File(entityPath), localeString: materialFilenameRE.firstMatch(entityPath)[1]);
}
}
try {
validateLocalizations(localeToResources, localeToResourceAttributes);
} on ValidationError catch (exception) {
exitWithError('$exception');
}
final StringBuffer buffer = StringBuffer();
buffer.writeln(outputHeader.replaceFirst('@(regenerate)', 'dart dev/tools/localization/gen_localizations.dart --overwrite'));
buffer.write(generateTranslationBundles());
if (options.writeToFile) {
final File localizationsFile = File(path.join(directory.path, 'generated_material_localizations.dart'));
localizationsFile.writeAsStringSync(buffer.toString(), flush: true);
} else {
stdout.write(buffer.toString());
}
}

View File

@@ -0,0 +1,269 @@
// Copyright 2017 The Chromium 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:convert';
import 'dart:io';
import 'package:args/args.dart' as argslib;
import 'package:meta/meta.dart';
/// Simple data class to hold parsed locale. Does not promise validity of any data.
class LocaleInfo implements Comparable<LocaleInfo> {
LocaleInfo({
this.languageCode,
this.scriptCode,
this.countryCode,
this.length,
this.originalString,
});
/// Simple parser. Expects the locale string to be in the form of 'language_script_COUNTRY'
/// where the langauge is 2 characters, script is 4 characters with the first uppercase,
/// and country is 2-3 characters and all uppercase.
///
/// 'language_COUNTRY' or 'language_script' are also valid. Missing fields will be null.
///
/// When `deriveScriptCode` is true, if [scriptCode] was unspecified, it will
/// be derived from the [languageCode] and [countryCode] if possible.
factory LocaleInfo.fromString(String locale, { bool deriveScriptCode = false }) {
final List<String> codes = locale.split('_'); // [language, script, country]
assert(codes.isNotEmpty && codes.length < 4);
final String languageCode = codes[0];
String scriptCode;
String countryCode;
int length = codes.length;
String originalString = locale;
if (codes.length == 2) {
scriptCode = codes[1].length >= 4 ? codes[1] : null;
countryCode = codes[1].length < 4 ? codes[1] : null;
} else if (codes.length == 3) {
scriptCode = codes[1].length > codes[2].length ? codes[1] : codes[2];
countryCode = codes[1].length < codes[2].length ? codes[1] : codes[2];
}
assert(codes[0] != null && codes[0].isNotEmpty);
assert(countryCode == null || countryCode.isNotEmpty);
assert(scriptCode == null || scriptCode.isNotEmpty);
/// Adds scriptCodes to locales where we are able to assume it to provide
/// finer granularity when resolving locales.
///
/// The basis of the assumptions here are based off of known usage of scripts
/// across various countries. For example, we know Taiwan uses traditional (Hant)
/// script, so it is safe to apply (Hant) to Taiwanese languages.
if (deriveScriptCode && scriptCode == null) {
switch (languageCode) {
case 'zh': {
if (countryCode == null) {
scriptCode = 'Hans';
}
switch (countryCode) {
case 'CN':
case 'SG':
scriptCode = 'Hans';
break;
case 'TW':
case 'HK':
case 'MO':
scriptCode = 'Hant';
break;
}
break;
}
case 'sr': {
if (countryCode == null) {
scriptCode = 'Cyrl';
}
break;
}
}
// Increment length if we were able to assume a scriptCode.
if (scriptCode != null) {
length += 1;
}
// Update the base string to reflect assumed scriptCodes.
originalString = languageCode;
if (scriptCode != null)
originalString += '_' + scriptCode;
if (countryCode != null)
originalString += '_' + countryCode;
}
return LocaleInfo(
languageCode: languageCode,
scriptCode: scriptCode,
countryCode: countryCode,
length: length,
originalString: originalString,
);
}
final String languageCode;
final String scriptCode;
final String countryCode;
final int length; // The number of fields. Ranges from 1-3.
final String originalString; // Original un-parsed locale string.
@override
bool operator ==(Object other) {
if (!(other is LocaleInfo))
return false;
final LocaleInfo otherLocale = other;
return originalString == otherLocale.originalString;
}
@override
int get hashCode {
return originalString.hashCode;
}
@override
String toString() {
return originalString;
}
@override
int compareTo(LocaleInfo other) {
return originalString.compareTo(other.originalString);
}
}
void exitWithError(String errorMessage) {
assert(errorMessage != null);
stderr.writeln('fatal: $errorMessage');
exit(1);
}
void checkCwdIsRepoRoot(String commandName) {
final bool isRepoRoot = Directory('.git').existsSync();
if (!isRepoRoot) {
exitWithError(
'$commandName must be run from the root of the Flutter repository. The '
'current working directory is: ${Directory.current.path}'
);
}
}
String camelCase(LocaleInfo locale) {
return locale.originalString
.split('_')
.map<String>((String part) => part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase())
.join('');
}
GeneratorOptions parseArgs(List<String> rawArgs) {
final argslib.ArgParser argParser = argslib.ArgParser()
..addFlag(
'overwrite',
abbr: 'w',
defaultsTo: false,
);
final argslib.ArgResults args = argParser.parse(rawArgs);
final bool writeToFile = args['overwrite'];
return GeneratorOptions(writeToFile: writeToFile);
}
class GeneratorOptions {
GeneratorOptions({
@required this.writeToFile,
});
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 = HttpClient();
final HttpClientRequest request = await client.getUrl(Uri.parse(registry));
final HttpClientResponse response = await request.close();
final String body = (await response.transform<String>(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]];
String output = '$language';
String region;
String script;
if (subtags.length == 2) {
region = _regions[subtags[1]];
script = _scripts[subtags[1]];
assert(region != null || script != null);
} else if (subtags.length >= 3) {
region = _regions[subtags[2]];
script = _scripts[subtags[1]];
assert(region != null && script != null);
}
if (region != null)
output += ', as used in $region';
if (script != null)
output += ', using the $script script';
return output;
}

View File

@@ -0,0 +1,165 @@
// Copyright 2017 The Chromium 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:convert' show json;
import 'dart:io';
import 'localizations_utils.dart';
// 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 = 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, *_en.arb.
///
/// - For each foo, resource, there must be a corresponding @foo.
/// - For each @foo resource, there must be a corresponding foo, except
/// for plurals, for which there must be a fooOther.
/// - Each @foo resource must have a Map value with a String valued
/// description entry.
///
/// Throws an exception upon failure.
void validateEnglishLocalizations(File file) {
final StringBuffer errorMessages = StringBuffer();
if (!file.existsSync()) {
errorMessages.writeln('English localizations do not exist: $file');
throw ValidationError(errorMessages.toString());
}
final Map<String, dynamic> bundle = json.decode(file.readAsStringSync());
for (String resourceId in bundle.keys) {
if (resourceId.startsWith('@'))
continue;
if (bundle['@$resourceId'] != null)
continue;
bool checkPluralResource(String suffix) {
final int suffixIndex = resourceId.indexOf(suffix);
return suffixIndex != -1 && bundle['@${resourceId.substring(0, suffixIndex)}'] != null;
}
if (kPluralSuffixes.any(checkPluralResource))
continue;
errorMessages.writeln('A value was not specified for @$resourceId');
}
for (String atResourceId in bundle.keys) {
if (!atResourceId.startsWith('@'))
continue;
final dynamic atResourceValue = bundle[atResourceId];
final Map<String, dynamic> atResource =
atResourceValue is Map<String, dynamic> ? atResourceValue : null;
if (atResource == null) {
errorMessages.writeln('A map value was not specified for $atResourceId');
continue;
}
final String description = atResource['description'];
if (description == null)
errorMessages.writeln('No description specified for $atResourceId');
final String plural = atResource['plural'];
final String resourceId = atResourceId.substring(1);
if (plural != null) {
final String resourceIdOther = '${resourceId}Other';
if (!bundle.containsKey(resourceIdOther))
errorMessages.writeln('Default plural resource $resourceIdOther undefined');
} else {
if (!bundle.containsKey(resourceId))
errorMessages.writeln('No matching $resourceId defined for $atResourceId');
}
}
if (errorMessages.isNotEmpty)
throw ValidationError(errorMessages.toString());
}
/// Enforces the following invariants in our localizations:
///
/// - Resource keys are valid, i.e. they appear in the canonical list.
/// - Resource keys are complete for language-level locales, e.g. "es", "he".
///
/// Uses "en" localizations as the canonical source of locale keys that other
/// locales are compared against.
///
/// If validation fails, throws an exception.
void validateLocalizations(
Map<LocaleInfo, Map<String, String>> localeToResources,
Map<LocaleInfo, Map<String, dynamic>> localeToAttributes,
) {
final Map<String, String> canonicalLocalizations = localeToResources[LocaleInfo.fromString('en')];
final Set<String> canonicalKeys = Set<String>.from(canonicalLocalizations.keys);
final StringBuffer errorMessages = StringBuffer();
bool explainMissingKeys = false;
for (final LocaleInfo locale in localeToResources.keys) {
final Map<String, String> resources = localeToResources[locale];
// Whether `key` corresponds to one of the plural variations of a key with
// the same prefix and suffix "Other".
//
// 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 Match pluralMatch = kPluralRegexp.firstMatch(key);
if (pluralMatch == null)
return false;
final String prefix = pluralMatch[1];
return resources.containsKey('${prefix}Other');
}
final Set<String> keys = Set<String>.from(
resources.keys.where((String key) => !isPluralVariation(key))
);
// Make sure keys are valid (i.e. they also exist in the canonical
// localizations)
final Set<String> invalidKeys = keys.difference(canonicalKeys);
if (invalidKeys.isNotEmpty)
errorMessages.writeln('Locale "$locale" contains invalid resource keys: ${invalidKeys.join(', ')}');
// For language-level locales only, check that they have a complete list of
// keys, or opted out of using certain ones.
if (locale.length == 1) {
final Map<String, dynamic> attributes = localeToAttributes[locale];
final List<String> missingKeys = <String>[];
for (final String missingKey in canonicalKeys.difference(keys)) {
final dynamic attribute = attributes[missingKey];
final bool intentionallyOmitted = attribute is Map && attribute.containsKey('notUsed');
if (!intentionallyOmitted && !isPluralVariation(missingKey))
missingKeys.add(missingKey);
}
if (missingKeys.isNotEmpty) {
explainMissingKeys = true;
errorMessages.writeln('Locale "$locale" is missing the following resource keys: ${missingKeys.join(', ')}');
}
}
}
if (errorMessages.isNotEmpty) {
if (explainMissingKeys) {
errorMessages
..writeln()
..writeln(
'If a resource key is intentionally omitted, add an attribute corresponding '
'to the key name with a "notUsed" property explaining why. Example:'
)
..writeln()
..writeln('"@anteMeridiemAbbreviation": {')
..writeln(' "notUsed": "Sindhi time format does not use a.m. indicator"')
..writeln('}');
}
throw ValidationError(errorMessages.toString());
}
}