Auto-format Framework (#160545)

This auto-formats all *.dart files in the repository outside of the
`engine` subdirectory and enforces that these files stay formatted with
a presubmit check.

**Reviewers:** Please carefully review all the commits except for the
one titled "formatted". The "formatted" commit was auto-generated by
running `dev/tools/format.sh -a -f`. The other commits were hand-crafted
to prepare the repo for the formatting change. I recommend reviewing the
commits one-by-one via the "Commits" tab and avoiding Github's "Files
changed" tab as it will likely slow down your browser because of the
size of this PR.

---------

Co-authored-by: Kate Lovett <katelovett@google.com>
Co-authored-by: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com>
This commit is contained in:
Michael Goderbauer
2024-12-19 12:06:21 -08:00
committed by GitHub
parent 8e0993eda8
commit 5491c8c146
4411 changed files with 455108 additions and 415991 deletions

View File

@@ -37,10 +37,11 @@ void _encodeBundleTranslations(Map<String, dynamic> bundle) {
final String translation = bundle[key] as String;
// Rewrite the string as a series of unicode characters in JSON format.
// Like "\u0012\u0123\u1234".
bundle[key] = translation.runes.map((int code) {
final String codeString = '00${code.toRadixString(16)}';
return '\\u${codeString.substring(codeString.length - 4)}';
}).join();
bundle[key] =
translation.runes.map((int code) {
final String codeString = '00${code.toRadixString(16)}';
return '\\u${codeString.substring(codeString.length - 4)}';
}).join();
}
}
@@ -49,7 +50,9 @@ void _checkEncodedTranslations(Map<String, dynamic> encodedBundle, Map<String, d
const JsonDecoder decoder = JsonDecoder();
for (final String key in bundle.keys) {
if (decoder.convert('"${encodedBundle[key]}"') != bundle[key]) {
stderr.writeln(' encodedTranslation for $key does not match original value "${bundle[key]}"');
stderr.writeln(
' encodedTranslation for $key does not match original value "${bundle[key]}"',
);
errorFound = true;
}
}

View File

@@ -46,19 +46,21 @@ Future<void> main(List<String> rawArgs) async {
final bool writeToFile = parseArgs(rawArgs).writeToFile;
final File packageConfigFile = File(path.join('packages', 'flutter_localizations', '.dart_tool', 'package_config.json'));
final File packageConfigFile = File(
path.join('packages', 'flutter_localizations', '.dart_tool', 'package_config.json'),
);
final bool packageConfigExists = packageConfigFile.existsSync();
if (!packageConfigExists) {
exitWithError(
'File not found: ${packageConfigFile.path}. $_kCommandName must be run '
'after a successful "flutter update-packages".'
'after a successful "flutter update-packages".',
);
}
final List<Object?> packages = (
json.decode(packageConfigFile.readAsStringSync()) as Map<String, Object?>
)['packages']! as List<Object?>;
final List<Object?> packages =
(json.decode(packageConfigFile.readAsStringSync()) as Map<String, Object?>)['packages']!
as List<Object?>;
String? pathToIntl;
for (final Object? package in packages) {
@@ -72,19 +74,22 @@ Future<void> main(List<String> rawArgs) async {
if (pathToIntl == null) {
exitWithError(
'Could not find "intl" package. $_kCommandName must be run '
'after a successful "flutter update-packages".'
'after a successful "flutter update-packages".',
);
}
final Directory dateSymbolsDirectory = Directory(path.join(pathToIntl!, 'lib', 'src', 'data', 'dates', 'symbols'));
final Directory dateSymbolsDirectory = Directory(
path.join(pathToIntl!, 'lib', 'src', 'data', 'dates', 'symbols'),
);
final Map<String, File> symbolFiles = _listIntlData(dateSymbolsDirectory);
final Directory datePatternsDirectory = Directory(path.join(pathToIntl, 'lib', 'src', 'data', 'dates', 'patterns'));
final Directory datePatternsDirectory = Directory(
path.join(pathToIntl, 'lib', 'src', 'data', 'dates', 'patterns'),
);
final Map<String, File> patternFiles = _listIntlData(datePatternsDirectory);
final StringBuffer buffer = StringBuffer();
final Set<String> supportedLocales = _supportedLocales();
buffer.writeln(
'''
buffer.writeln('''
// 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.
@@ -95,8 +100,7 @@ Future<void> main(List<String> rawArgs) async {
import 'package:intl/date_symbols.dart' as intl;
'''
);
''');
buffer.writeln('''
/// The subset of date symbols supported by the intl package which are also
/// supported by flutter_localizations.''');
@@ -104,7 +108,8 @@ import 'package:intl/date_symbols.dart' as intl;
symbolFiles.forEach((String locale, File data) {
currentLocale = locale;
if (supportedLocales.contains(locale)) {
final Map<String, Object?> objData = json.decode(data.readAsStringSync()) as Map<String, Object?>;
final Map<String, Object?> objData =
json.decode(data.readAsStringSync()) as Map<String, Object?>;
buffer.writeln("'$locale': intl.DateSymbols(");
objData.forEach((String key, Object? value) {
if (value == null) {
@@ -123,10 +128,13 @@ import 'package:intl/date_symbols.dart' as intl;
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>> {');
buffer.writeln(
'const Map<String, Map<String, String>> datePatterns = <String, Map<String, String>> {',
);
patternFiles.forEach((String locale, File data) {
if (supportedLocales.contains(locale)) {
final Map<String, dynamic> patterns = json.decode(data.readAsStringSync()) as Map<String, dynamic>;
final Map<String, dynamic> patterns =
json.decode(data.readAsStringSync()) as Map<String, dynamic>;
buffer.writeln("'$locale': <String, String>{");
patterns.forEach((String key, dynamic value) {
assert(value is String);
@@ -138,13 +146,22 @@ import 'package:intl/date_symbols.dart' as intl;
buffer.writeln('};');
if (writeToFile) {
final File dateLocalizationsFile = File(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n', 'generated_date_localizations.dart'));
final File dateLocalizationsFile = File(
path.join(
'packages',
'flutter_localizations',
'lib',
'src',
'l10n',
'generated_date_localizations.dart',
),
);
dateLocalizationsFile.writeAsStringSync(buffer.toString());
final String extension = Platform.isWindows ? '.exe' : '';
final ProcessResult result = Process.runSync(path.join('bin', 'cache', 'dart-sdk', 'bin', 'dart$extension'), <String>[
'format',
dateLocalizationsFile.path,
]);
final ProcessResult result = Process.runSync(
path.join('bin', 'cache', 'dart-sdk', 'bin', 'dart$extension'),
<String>['format', dateLocalizationsFile.path],
);
if (result.exitCode != 0) {
print(result.exitCode);
print(result.stdout);
@@ -220,11 +237,11 @@ Set<String> _supportedLocales() {
// date patterns and symbols may cause problems.
//
// For more context, see https://github.com/flutter/flutter/issues/67644.
final Set<String> supportedLocales = <String>{
'en_US',
};
final Set<String> supportedLocales = <String>{'en_US'};
final RegExp filenameRE = RegExp(r'(?:material|cupertino)_(\w+)\.arb$');
final Directory supportedLocalesDirectory = Directory(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'));
final Directory supportedLocalesDirectory = Directory(
path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'),
);
for (final FileSystemEntity entity in supportedLocalesDirectory.listSync()) {
final String filePath = entity.path;
if (FileSystemEntity.isFileSync(filePath) && filenameRE.hasMatch(filePath)) {
@@ -237,10 +254,9 @@ Set<String> _supportedLocales() {
Map<String, File> _listIntlData(Directory directory) {
final Map<String, File> localeFiles = <String, File>{};
final Iterable<File> files = directory
.listSync()
.whereType<File>()
.where((File file) => file.path.endsWith('.json'));
final Iterable<File> files = directory.listSync().whereType<File>().where(
(File file) => file.path.endsWith('.json'),
);
for (final File file in files) {
final String locale = path.basenameWithoutExtension(file.path);
localeFiles[locale] = file;

View File

@@ -83,7 +83,9 @@ String generateArbBasedLocalizationSubclasses({
assert(supportedLanguagesDocMacro.isNotEmpty);
generateConstructorForCountrySubClass ??= generateConstructor;
final StringBuffer output = StringBuffer();
output.writeln(generateHeader('dart dev/tools/localization/bin/gen_localizations.dart --overwrite'));
output.writeln(
generateHeader('dart dev/tools/localization/bin/gen_localizations.dart --overwrite'),
);
final StringBuffer supportedLocales = StringBuffer();
@@ -141,7 +143,8 @@ String generateArbBasedLocalizationSubclasses({
final Map<String, String> languageResources = localeToResources[languageLocale]!;
for (final String key in allKeys) {
final Map<String, dynamic>? attributes = localeToResourceAttributes[canonicalLocale]![key] as Map<String, dynamic>?;
final Map<String, dynamic>? attributes =
localeToResourceAttributes[canonicalLocale]![key] as Map<String, dynamic>?;
output.writeln(generateGetter(key, languageResources[key], attributes, languageLocale));
}
output.writeln('}');
@@ -153,18 +156,21 @@ String generateArbBasedLocalizationSubclasses({
// script default values before language default values.
for (final String scriptCode in languageToScriptCodes[languageName]!) {
final LocaleInfo scriptBaseLocale = LocaleInfo.fromString('${languageName}_$scriptCode');
output.writeln(generateClassDeclaration(
scriptBaseLocale,
generatedClassPrefix,
'$generatedClassPrefix${languageLocale.camelCase()}',
));
output.writeln(
generateClassDeclaration(
scriptBaseLocale,
generatedClassPrefix,
'$generatedClassPrefix${languageLocale.camelCase()}',
),
);
output.writeln(generateConstructorForCountrySubClass(scriptBaseLocale));
final Map<String, String> scriptResources = localeToResources[scriptBaseLocale]!;
for (final String key in scriptResources.keys.toList()..sort()) {
if (languageResources[key] == scriptResources[key]) {
continue;
}
final Map<String, dynamic>? attributes = localeToResourceAttributes[canonicalLocale]![key] as Map<String, dynamic>?;
final Map<String, dynamic>? attributes =
localeToResourceAttributes[canonicalLocale]![key] as Map<String, dynamic>?;
output.writeln(generateGetter(key, scriptResources[key], attributes, languageLocale));
}
output.writeln('}');
@@ -181,22 +187,27 @@ String generateArbBasedLocalizationSubclasses({
continue;
}
countryCodeCount += 1;
output.writeln(generateClassDeclaration(
locale,
generatedClassPrefix,
'$generatedClassPrefix${scriptBaseLocale.camelCase()}',
));
output.writeln(
generateClassDeclaration(
locale,
generatedClassPrefix,
'$generatedClassPrefix${scriptBaseLocale.camelCase()}',
),
);
output.writeln(generateConstructorForCountrySubClass(locale));
final Map<String, String> localeResources = localeToResources[locale]!;
for (final 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]) {
if (scriptResources.containsKey(key)
? scriptResources[key] == localeResources[key]
: languageResources[key] == localeResources[key]) {
continue;
}
final Map<String, dynamic>? attributes = localeToResourceAttributes[canonicalLocale]![key] as Map<String, dynamic>?;
final Map<String, dynamic>? attributes =
localeToResourceAttributes[canonicalLocale]![key] as Map<String, dynamic>?;
output.writeln(generateGetter(key, localeResources[key], attributes, languageLocale));
}
output.writeln('}');
output.writeln('}');
}
}
} else {
@@ -209,35 +220,46 @@ String generateArbBasedLocalizationSubclasses({
}
countryCodeCount += 1;
final Map<String, String> localeResources = localeToResources[locale]!;
output.writeln(generateClassDeclaration(
locale,
generatedClassPrefix,
'$generatedClassPrefix${languageLocale.camelCase()}',
));
output.writeln(
generateClassDeclaration(
locale,
generatedClassPrefix,
'$generatedClassPrefix${languageLocale.camelCase()}',
),
);
output.writeln(generateConstructorForCountrySubClass(locale));
for (final String key in localeResources.keys) {
if (languageResources[key] == localeResources[key]) {
continue;
}
final Map<String, dynamic>? attributes = localeToResourceAttributes[canonicalLocale]![key] as Map<String, dynamic>?;
final Map<String, dynamic>? attributes =
localeToResourceAttributes[canonicalLocale]![key] as Map<String, dynamic>?;
output.writeln(generateGetter(key, localeResources[key], attributes, languageLocale));
}
output.writeln('}');
output.writeln('}');
}
}
final String scriptCodeMessage = scriptCodeCount == 0 ? '' : ' and $scriptCodeCount script${scriptCodeCount == 1 ? '' : 's'}';
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'})');
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)');
supportedLocales.writeln(
'/// * `$languageName` - ${describeLocale(languageName)} (plus one country variation$scriptCodeMessage)',
);
} else {
supportedLocales.writeln('/// * `$languageName` - ${describeLocale(languageName)} (plus $countryCodeCount country variations$scriptCodeMessage)');
supportedLocales.writeln(
'/// * `$languageName` - ${describeLocale(languageName)} (plus $countryCodeCount country variations$scriptCodeMessage)',
);
}
}
@@ -279,10 +301,13 @@ $factoryDeclaration
for (final String language in languageToLocales.keys) {
// Only one instance of the language.
if (languageToLocales[language]!.length == 1) {
output.writeln('''
output.writeln(
'''
case '$language':
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${languageToLocales[language]![0].camelCase()}($factoryArguments);''');
} else if (!languageToScriptCodes.containsKey(language)) { // Does not distinguish between scripts. Switch on countryCode directly.
return ${callsFactoryWithConst ? 'const ' : ''}$generatedClassPrefix${languageToLocales[language]![0].camelCase()}($factoryArguments);''',
);
} else if (!languageToScriptCodes.containsKey(language)) {
// Does not distinguish between scripts. Switch on countryCode directly.
output.writeln('''
case '$language': {
switch (locale.countryCode) {''');
@@ -292,15 +317,18 @@ $factoryDeclaration
}
assert(locale.length > 1);
final String countryCode = locale.countryCode!;
output.writeln('''
output.writeln(
'''
case '$countryCode':
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${locale.camelCase()}($factoryArguments);''');
return ${callsFactoryWithConst ? 'const ' : ''}$generatedClassPrefix${locale.camelCase()}($factoryArguments);''',
);
}
output.writeln('''
}
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${LocaleInfo.fromString(language).camelCase()}($factoryArguments);
return ${callsFactoryWithConst ? 'const ' : ''}$generatedClassPrefix${LocaleInfo.fromString(language).camelCase()}($factoryArguments);
}''');
} else { // Language has scriptCode, add additional switch logic.
} else {
// Language has scriptCode, add additional switch logic.
bool hasCountryCode = false;
output.writeln('''
case '$language': {
@@ -325,9 +353,11 @@ $factoryDeclaration
continue;
}
final String countryCode = locale.countryCode!;
output.writeln('''
output.writeln(
'''
case '$countryCode':
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${locale.camelCase()}($factoryArguments);''');
return ${callsFactoryWithConst ? 'const ' : ''}$generatedClassPrefix${locale.camelCase()}($factoryArguments);''',
);
}
}
// Return a fallback locale that matches scriptCode, but not countryCode.
@@ -339,7 +369,7 @@ $factoryDeclaration
}''');
}
output.writeln('''
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${scriptLocale.camelCase()}($factoryArguments);
return ${callsFactoryWithConst ? 'const ' : ''}$generatedClassPrefix${scriptLocale.camelCase()}($factoryArguments);
}''');
} else {
// Not Explicitly defined, fallback to first locale with the same language and
@@ -353,7 +383,7 @@ $factoryDeclaration
}''');
}
output.writeln('''
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${scriptLocale.camelCase()}($factoryArguments);
return ${callsFactoryWithConst ? 'const ' : ''}$generatedClassPrefix${scriptLocale.camelCase()}($factoryArguments);
}''');
break;
}
@@ -362,7 +392,7 @@ $factoryDeclaration
output.writeln('''
}''');
if (hasCountryCode) {
output.writeln('''
output.writeln('''
switch (locale.countryCode) {''');
for (final LocaleInfo locale in languageToLocales[language]!) {
if (locale.originalString == language) {
@@ -373,15 +403,17 @@ $factoryDeclaration
continue;
}
final String countryCode = locale.countryCode!;
output.writeln('''
output.writeln(
'''
case '$countryCode':
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${locale.camelCase()}($factoryArguments);''');
return ${callsFactoryWithConst ? 'const ' : ''}$generatedClassPrefix${locale.camelCase()}($factoryArguments);''',
);
}
output.writeln('''
}''');
}
output.writeln('''
return ${callsFactoryWithConst ? 'const ': ''}$generatedClassPrefix${LocaleInfo.fromString(language).camelCase()}($factoryArguments);
return ${callsFactoryWithConst ? 'const ' : ''}$generatedClassPrefix${LocaleInfo.fromString(language).camelCase()}($factoryArguments);
}''');
}
}
@@ -472,7 +504,7 @@ String? generateValue(String? value, Map<String, dynamic>? attributes, LocaleInf
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 ')}'
'patterns:\n ${_icuTimeOfDayToEnum.keys.join('\n ')}',
);
}
return _icuTimeOfDayToEnum[value];
@@ -481,23 +513,28 @@ String? generateValue(String? value, Map<String, dynamic>? attributes, LocaleInf
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 ')}'
'values:\n ${_scriptCategoryToEnum.keys.join('\n ')}',
);
}
return _scriptCategoryToEnum[value];
}
}
return generateEncodedString(locale.languageCode, value);
return generateEncodedString(locale.languageCode, value);
}
/// Combines [generateType], [generateKey], and [generateValue] to return
/// the source of getters for the GlobalMaterialLocalizations subclass.
/// The locale is the locale for which the getter is being generated.
String generateGetter(String key, String? value, Map<String, dynamic>? attributes, LocaleInfo locale) {
String generateGetter(
String key,
String? value,
Map<String, dynamic>? attributes,
LocaleInfo locale,
) {
final String type = generateType(attributes);
key = generateKey(key, attributes);
final String? generatedValue = generateValue(value, attributes, locale);
return '''
return '''
@override
$type get $key => $generatedValue;''';
@@ -511,7 +548,9 @@ 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 = Directory(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'));
final Directory directory = Directory(
path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'),
);
final RegExp widgetsFilenameRE = RegExp(r'widgets_(\w+)\.arb$');
final RegExp materialFilenameRE = RegExp(r'material_(\w+)\.arb$');
final RegExp cupertinoFilenameRE = RegExp(r'cupertino_(\w+)\.arb$');
@@ -537,22 +576,28 @@ void main(List<String> rawArgs) {
precacheLanguageAndRegionTags();
// Maps of locales to resource key/value pairs for Widgets ARBs.
final Map<LocaleInfo, Map<String, String>> widgetsLocaleToResources = <LocaleInfo, Map<String, String>>{};
final Map<LocaleInfo, Map<String, String>> widgetsLocaleToResources =
<LocaleInfo, Map<String, String>>{};
// Maps of locales to resource key/attributes pairs for Widgets ARBs.
// https://github.com/googlei18n/app-resource-bundle/wiki/ApplicationResourceBundleSpecification#resource-attributes
final Map<LocaleInfo, Map<String, dynamic>> widgetsLocaleToResourceAttributes = <LocaleInfo, Map<String, dynamic>>{};
final Map<LocaleInfo, Map<String, dynamic>> widgetsLocaleToResourceAttributes =
<LocaleInfo, Map<String, dynamic>>{};
// Maps of locales to resource key/value pairs for Material ARBs.
final Map<LocaleInfo, Map<String, String>> materialLocaleToResources = <LocaleInfo, Map<String, String>>{};
final Map<LocaleInfo, Map<String, String>> materialLocaleToResources =
<LocaleInfo, Map<String, String>>{};
// Maps of locales to resource key/attributes pairs for Material ARBs.
// https://github.com/googlei18n/app-resource-bundle/wiki/ApplicationResourceBundleSpecification#resource-attributes
final Map<LocaleInfo, Map<String, dynamic>> materialLocaleToResourceAttributes = <LocaleInfo, Map<String, dynamic>>{};
final Map<LocaleInfo, Map<String, dynamic>> materialLocaleToResourceAttributes =
<LocaleInfo, Map<String, dynamic>>{};
// Maps of locales to resource key/value pairs for Cupertino ARBs.
final Map<LocaleInfo, Map<String, String>> cupertinoLocaleToResources = <LocaleInfo, Map<String, String>>{};
final Map<LocaleInfo, Map<String, String>> cupertinoLocaleToResources =
<LocaleInfo, Map<String, String>>{};
// Maps of locales to resource key/attributes pairs for Cupertino ARBs.
// https://github.com/googlei18n/app-resource-bundle/wiki/ApplicationResourceBundleSpecification#resource-attributes
final Map<LocaleInfo, Map<String, dynamic>> cupertinoLocaleToResourceAttributes = <LocaleInfo, Map<String, dynamic>>{};
final Map<LocaleInfo, Map<String, dynamic>> cupertinoLocaleToResourceAttributes =
<LocaleInfo, Map<String, dynamic>>{};
loadMatchingArbsIntoBundleMaps(
directory: directory,
@@ -574,9 +619,21 @@ void main(List<String> rawArgs) {
);
try {
validateLocalizations(widgetsLocaleToResources, widgetsLocaleToResourceAttributes, removeUndefined: options.removeUndefined);
validateLocalizations(materialLocaleToResources, materialLocaleToResourceAttributes, removeUndefined: options.removeUndefined);
validateLocalizations(cupertinoLocaleToResources, cupertinoLocaleToResourceAttributes, removeUndefined: options.removeUndefined);
validateLocalizations(
widgetsLocaleToResources,
widgetsLocaleToResourceAttributes,
removeUndefined: options.removeUndefined,
);
validateLocalizations(
materialLocaleToResources,
materialLocaleToResourceAttributes,
removeUndefined: options.removeUndefined,
);
validateLocalizations(
cupertinoLocaleToResources,
cupertinoLocaleToResourceAttributes,
removeUndefined: options.removeUndefined,
);
} on ValidationError catch (exception) {
exitWithError('$exception');
}
@@ -586,62 +643,71 @@ void main(List<String> rawArgs) {
removeUndefinedLocalizations(cupertinoLocaleToResources);
}
final String? widgetsLocalizations = options.writeToFile || !options.cupertinoOnly
? generateArbBasedLocalizationSubclasses(
localeToResources: widgetsLocaleToResources,
localeToResourceAttributes: widgetsLocaleToResourceAttributes,
generatedClassPrefix: 'WidgetsLocalization',
baseClass: 'GlobalWidgetsLocalizations',
generateHeader: generateWidgetsHeader,
generateConstructor: generateWidgetsConstructor,
generateConstructorForCountrySubClass: generateWidgetsConstructorForCountrySubclass,
factoryName: widgetsFactoryName,
factoryDeclaration: widgetsFactoryDeclaration,
callsFactoryWithConst: true,
factoryArguments: widgetsFactoryArguments,
supportedLanguagesConstant: widgetsSupportedLanguagesConstant,
supportedLanguagesDocMacro: widgetsSupportedLanguagesDocMacro,
)
: null;
final String? materialLocalizations = options.writeToFile || !options.cupertinoOnly
? generateArbBasedLocalizationSubclasses(
localeToResources: materialLocaleToResources,
localeToResourceAttributes: materialLocaleToResourceAttributes,
generatedClassPrefix: 'MaterialLocalization',
baseClass: 'GlobalMaterialLocalizations',
generateHeader: generateMaterialHeader,
generateConstructor: generateMaterialConstructor,
factoryName: materialFactoryName,
factoryDeclaration: materialFactoryDeclaration,
callsFactoryWithConst: false,
factoryArguments: materialFactoryArguments,
supportedLanguagesConstant: materialSupportedLanguagesConstant,
supportedLanguagesDocMacro: materialSupportedLanguagesDocMacro,
)
: null;
final String? cupertinoLocalizations = options.writeToFile || !options.materialOnly
? generateArbBasedLocalizationSubclasses(
localeToResources: cupertinoLocaleToResources,
localeToResourceAttributes: cupertinoLocaleToResourceAttributes,
generatedClassPrefix: 'CupertinoLocalization',
baseClass: 'GlobalCupertinoLocalizations',
generateHeader: generateCupertinoHeader,
generateConstructor: generateCupertinoConstructor,
factoryName: cupertinoFactoryName,
factoryDeclaration: cupertinoFactoryDeclaration,
callsFactoryWithConst: false,
factoryArguments: cupertinoFactoryArguments,
supportedLanguagesConstant: cupertinoSupportedLanguagesConstant,
supportedLanguagesDocMacro: cupertinoSupportedLanguagesDocMacro,
)
: null;
final String? widgetsLocalizations =
options.writeToFile || !options.cupertinoOnly
? generateArbBasedLocalizationSubclasses(
localeToResources: widgetsLocaleToResources,
localeToResourceAttributes: widgetsLocaleToResourceAttributes,
generatedClassPrefix: 'WidgetsLocalization',
baseClass: 'GlobalWidgetsLocalizations',
generateHeader: generateWidgetsHeader,
generateConstructor: generateWidgetsConstructor,
generateConstructorForCountrySubClass: generateWidgetsConstructorForCountrySubclass,
factoryName: widgetsFactoryName,
factoryDeclaration: widgetsFactoryDeclaration,
callsFactoryWithConst: true,
factoryArguments: widgetsFactoryArguments,
supportedLanguagesConstant: widgetsSupportedLanguagesConstant,
supportedLanguagesDocMacro: widgetsSupportedLanguagesDocMacro,
)
: null;
final String? materialLocalizations =
options.writeToFile || !options.cupertinoOnly
? generateArbBasedLocalizationSubclasses(
localeToResources: materialLocaleToResources,
localeToResourceAttributes: materialLocaleToResourceAttributes,
generatedClassPrefix: 'MaterialLocalization',
baseClass: 'GlobalMaterialLocalizations',
generateHeader: generateMaterialHeader,
generateConstructor: generateMaterialConstructor,
factoryName: materialFactoryName,
factoryDeclaration: materialFactoryDeclaration,
callsFactoryWithConst: false,
factoryArguments: materialFactoryArguments,
supportedLanguagesConstant: materialSupportedLanguagesConstant,
supportedLanguagesDocMacro: materialSupportedLanguagesDocMacro,
)
: null;
final String? cupertinoLocalizations =
options.writeToFile || !options.materialOnly
? generateArbBasedLocalizationSubclasses(
localeToResources: cupertinoLocaleToResources,
localeToResourceAttributes: cupertinoLocaleToResourceAttributes,
generatedClassPrefix: 'CupertinoLocalization',
baseClass: 'GlobalCupertinoLocalizations',
generateHeader: generateCupertinoHeader,
generateConstructor: generateCupertinoConstructor,
factoryName: cupertinoFactoryName,
factoryDeclaration: cupertinoFactoryDeclaration,
callsFactoryWithConst: false,
factoryArguments: cupertinoFactoryArguments,
supportedLanguagesConstant: cupertinoSupportedLanguagesConstant,
supportedLanguagesDocMacro: cupertinoSupportedLanguagesDocMacro,
)
: null;
if (options.writeToFile) {
final File widgetsLocalizationsFile = File(path.join(directory.path, 'generated_widgets_localizations.dart'));
final File widgetsLocalizationsFile = File(
path.join(directory.path, 'generated_widgets_localizations.dart'),
);
widgetsLocalizationsFile.writeAsStringSync(widgetsLocalizations!, flush: true);
final File materialLocalizationsFile = File(path.join(directory.path, 'generated_material_localizations.dart'));
final File materialLocalizationsFile = File(
path.join(directory.path, 'generated_material_localizations.dart'),
);
materialLocalizationsFile.writeAsStringSync(materialLocalizations!, flush: true);
final File cupertinoLocalizationsFile = File(path.join(directory.path, 'generated_cupertino_localizations.dart'));
final File cupertinoLocalizationsFile = File(
path.join(directory.path, 'generated_cupertino_localizations.dart'),
);
cupertinoLocalizationsFile.writeAsStringSync(cupertinoLocalizations!, flush: true);
} else {
if (options.cupertinoOnly) {

View File

@@ -33,7 +33,13 @@ Future<void> main(List<String> rawArgs) async {
}
checkCwdIsRepoRoot('gen_missing_localizations');
final String localizationPath = path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n');
final String localizationPath = path.join(
'packages',
'flutter_localizations',
'lib',
'src',
'l10n',
);
updateMissingResources(localizationPath, 'material', removeUndefined: removeUndefined);
updateMissingResources(localizationPath, 'cupertino', removeUndefined: removeUndefined);
}
@@ -58,7 +64,7 @@ void writeBundle(File file, Map<String, dynamic> bundle) {
Set<String> resourceKeys(Map<String, dynamic> bundle) {
return Set<String>.from(
// Skip any attribute keys
bundle.keys.where((String key) => !key.startsWith('@'))
bundle.keys.where((String key) => !key.startsWith('@')),
);
}
@@ -79,14 +85,21 @@ bool isPluralVariation(String key, Map<String, dynamic> bundle) {
return bundle.containsKey('${prefix}Other');
}
void updateMissingResources(String localizationPath, String groupPrefix, {bool removeUndefined = false}) {
void updateMissingResources(
String localizationPath,
String groupPrefix, {
bool removeUndefined = false,
}) {
final Directory localizationDir = Directory(localizationPath);
final RegExp filenamePattern = RegExp('${groupPrefix}_(\\w+)\\.arb');
final Map<String, dynamic> englishBundle = loadBundle(File(path.join(localizationPath, '${groupPrefix}_en.arb')));
final Map<String, dynamic> englishBundle = loadBundle(
File(path.join(localizationPath, '${groupPrefix}_en.arb')),
);
final Set<String> requiredKeys = resourceKeys(englishBundle);
for (final FileSystemEntity entity in localizationDir.listSync().toList()..sort(sortFilesByPath)) {
for (final FileSystemEntity entity
in localizationDir.listSync().toList()..sort(sortFilesByPath)) {
final String entityPath = entity.path;
if (FileSystemEntity.isFileSync(entityPath) && filenamePattern.hasMatch(entityPath)) {
final String localeString = filenamePattern.firstMatch(entityPath)![1]!;
@@ -105,17 +118,15 @@ void updateMissingResources(String localizationPath, String groupPrefix, {bool r
// --remove-undefined is passed.
if (removeUndefined) {
bool isIncluded(String key) {
return !isPluralVariation(key, localeBundle)
&& !intentionallyOmitted(key, localeBundle);
return !isPluralVariation(key, localeBundle) &&
!intentionallyOmitted(key, localeBundle);
}
// Find any resources in this locale that don't appear in the
// canonical locale, and skipping any which should not be included
// (plurals and intentionally omitted).
final Set<String> extraResources = localeResources
.difference(requiredKeys)
.where(isIncluded)
.toSet();
final Set<String> extraResources =
localeResources.difference(requiredKeys).where(isIncluded).toSet();
// Remove them.
localeBundle.removeWhere((String key, dynamic value) {
@@ -132,12 +143,21 @@ void updateMissingResources(String localizationPath, String groupPrefix, {bool r
// Add in any resources that are in the canonical locale and not present
// in this locale.
final Set<String> missingResources = requiredKeys.difference(localeResources).where(
(String key) => !isPluralVariation(key, localeBundle) && !intentionallyOmitted(key, localeBundle)
).toSet();
final Set<String> missingResources =
requiredKeys
.difference(localeResources)
.where(
(String key) =>
!isPluralVariation(key, localeBundle) &&
!intentionallyOmitted(key, localeBundle),
)
.toSet();
if (missingResources.isNotEmpty) {
localeBundle.addEntries(missingResources.map((String k) =>
MapEntry<String, String>(k, englishBundle[k].toString())));
localeBundle.addEntries(
missingResources.map(
(String k) => MapEntry<String, String>(k, englishBundle[k].toString()),
),
);
shouldWrite = true;
print('Updating $entityPath with missing entries for $missingResources');
}

View File

@@ -5,7 +5,8 @@
import 'dart:convert';
import 'dart:io';
const String registry = 'https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry';
const String registry =
'https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry';
/// A script to generate a Dart cache of https://www.iana.org. This should be
/// run occasionally. It was created since iana.org was found to be flaky.
@@ -15,9 +16,12 @@ Future<void> main() 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.cast<List<int>>().transform<String>(utf8.decoder).toList()).join();
final String body =
(await response.cast<List<int>>().transform<String>(utf8.decoder).toList()).join();
final File subtagRegistry = File('../language_subtag_registry.dart');
final File subtagRegistryFlutterTools = File('../../../../packages/flutter_tools/lib/src/localizations/language_subtag_registry.dart');
final File subtagRegistryFlutterTools = File(
'../../../../packages/flutter_tools/lib/src/localizations/language_subtag_registry.dart',
);
final String content = '''
// Copyright 2014 The Flutter Authors. All rights reserved.
@@ -27,7 +31,6 @@ Future<void> main() async {
/// Cache of $registry.
const String languageSubtagRegistry = \'\'\'$body\'\'\';''';
subtagRegistry.writeAsStringSync(content);
subtagRegistryFlutterTools.writeAsStringSync(content);

View File

@@ -26,7 +26,10 @@ import '../cupertino_localizations.dart';
//
// These classes are constructed by the [getCupertinoTranslation] method at the
// bottom of this file, and used by the [_GlobalCupertinoLocalizationsDelegate.load]
// method defined in `flutter_localizations/lib/src/cupertino_localizations.dart`.''';
// method defined in `flutter_localizations/lib/src/cupertino_localizations.dart`.
// TODO(goderbauer): Extend the generator to properly format the output.
// dart format off''';
}
/// Returns the source of the constructor for a GlobalCupertinoLocalizations

View File

@@ -26,7 +26,10 @@ import '../material_localizations.dart';
//
// 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`.''';
// method defined in `flutter_localizations/lib/src/material_localizations.dart`.
// TODO(goderbauer): Extend the generator to properly format the output.
// dart format off''';
}
/// Returns the source of the constructor for a GlobalMaterialLocalizations

View File

@@ -33,7 +33,10 @@ import '../widgets_localizations.dart';
//
// These classes are constructed by the [getWidgetsTranslation] method at the
// bottom of this file, and used by the [_WidgetsLocalizationsDelegate.load]
// method defined in `flutter_localizations/lib/src/widgets_localizations.dart`.''';
// method defined in `flutter_localizations/lib/src/widgets_localizations.dart`.
// TODO(goderbauer): Extend the generator to properly format the output.
// dart format off''';
}
/// Returns the source of the constructor for a GlobalWidgetsLocalizations
@@ -41,7 +44,8 @@ import '../widgets_localizations.dart';
String generateWidgetsConstructor(LocaleInfo locale) {
final String localeName = locale.originalString;
final String language = locale.languageCode.toLowerCase();
final String textDirection = _rtlLanguages.contains(language) ? 'TextDirection.rtl' : 'TextDirection.ltr';
final String textDirection =
_rtlLanguages.contains(language) ? 'TextDirection.rtl' : 'TextDirection.ltr';
return '''
/// Create an instance of the translation bundle for ${describeLocale(localeName)}.
///

View File

@@ -13,7 +13,7 @@ import 'language_subtag_registry.dart';
typedef HeaderGenerator = String Function(String regenerateInstructions);
typedef ConstructorGenerator = String Function(LocaleInfo locale);
int sortFilesByPath (FileSystemEntity a, FileSystemEntity b) {
int sortFilesByPath(FileSystemEntity a, FileSystemEntity b) {
return a.path.compareTo(b.path);
}
@@ -36,7 +36,7 @@ class LocaleInfo implements Comparable<LocaleInfo> {
///
/// 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 }) {
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];
@@ -94,20 +94,21 @@ class LocaleInfo implements Comparable<LocaleInfo> {
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.
final int length; // The number of fields. Ranges from 1-3.
final String originalString; // Original un-parsed locale string.
String camelCase() {
return originalString
.split('_')
.map<String>((String part) => part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase())
.join();
.split('_')
.map<String>(
(String part) => part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase(),
)
.join();
}
@override
bool operator ==(Object other) {
return other is LocaleInfo
&& other.originalString == originalString;
return other is LocaleInfo && other.originalString == originalString;
}
@override
@@ -132,7 +133,6 @@ void loadMatchingArbsIntoBundleMaps({
required Map<LocaleInfo, Map<String, String>> localeToResources,
required Map<LocaleInfo, Map<String, dynamic>> localeToResourceAttributes,
}) {
/// 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
@@ -151,7 +151,8 @@ void loadMatchingArbsIntoBundleMaps({
void populateResources(LocaleInfo locale, File file) {
final Map<String, String> resources = localeToResources[locale]!;
final Map<String, dynamic> attributes = localeToResourceAttributes[locale]!;
final Map<String, dynamic> bundle = json.decode(file.readAsStringSync()) as Map<String, dynamic>;
final Map<String, dynamic> bundle =
json.decode(file.readAsStringSync()) as Map<String, dynamic>;
for (final String key in bundle.keys) {
// The ARB file resource "attributes" for foo are called @foo.
if (key.startsWith('@')) {
@@ -161,10 +162,14 @@ void loadMatchingArbsIntoBundleMaps({
}
}
}
// 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);
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>{};
@@ -178,7 +183,9 @@ void loadMatchingArbsIntoBundleMaps({
// 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}');
final LocaleInfo scriptLocale = LocaleInfo.fromString(
'${locale.languageCode}_${locale.scriptCode}',
);
if (!localeToResources.containsKey(scriptLocale)) {
assumedLocales.add(scriptLocale);
localeToResources[scriptLocale] ??= <String, String>{};
@@ -201,39 +208,35 @@ void checkCwdIsRepoRoot(String commandName) {
if (!isRepoRoot) {
exitWithError(
'$commandName must be run from the root of the Flutter repository. The '
'current working directory is: ${Directory.current.path}'
'current working directory is: ${Directory.current.path}',
);
}
}
GeneratorOptions parseArgs(List<String> rawArgs) {
final argslib.ArgParser argParser = argslib.ArgParser()
..addFlag(
'help',
abbr: 'h',
help: 'Print the usage message for this command',
)
..addFlag(
'overwrite',
abbr: 'w',
help: 'Overwrite existing localizations',
)
..addFlag(
'remove-undefined',
help: 'Remove any localizations that are not defined in the canonical locale.',
)
..addFlag(
'widgets',
help: 'Whether to print the generated classes for the Widgets package only. Ignored when --overwrite is passed.',
)
..addFlag(
'material',
help: 'Whether to print the generated classes for the Material package only. Ignored when --overwrite is passed.',
)
..addFlag(
'cupertino',
help: 'Whether to print the generated classes for the Cupertino package only. Ignored when --overwrite is passed.',
);
final argslib.ArgParser argParser =
argslib.ArgParser()
..addFlag('help', abbr: 'h', help: 'Print the usage message for this command')
..addFlag('overwrite', abbr: 'w', help: 'Overwrite existing localizations')
..addFlag(
'remove-undefined',
help: 'Remove any localizations that are not defined in the canonical locale.',
)
..addFlag(
'widgets',
help:
'Whether to print the generated classes for the Widgets package only. Ignored when --overwrite is passed.',
)
..addFlag(
'material',
help:
'Whether to print the generated classes for the Material package only. Ignored when --overwrite is passed.',
)
..addFlag(
'cupertino',
help:
'Whether to print the generated classes for the Cupertino package only. Ignored when --overwrite is passed.',
);
final argslib.ArgResults args = argParser.parse(rawArgs);
if (args.wasParsed('help') && args['help'] == true) {
stderr.writeln(argParser.usage);
@@ -305,12 +308,19 @@ const String kParentheticalPrefix = ' (';
/// The data is obtained from the official IANA registry.
void precacheLanguageAndRegionTags() {
final List<Map<String, List<String>>> sections =
languageSubtagRegistry.split('%%').skip(1).map<Map<String, List<String>>>(_parseSection).toList();
languageSubtagRegistry
.split('%%')
.skip(1)
.map<Map<String, List<String>>>(_parseSection)
.toList();
for (final 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());
assert(
section.containsKey('Subtag') && section.containsKey('Description'),
section.toString(),
);
final String subtag = section['Subtag']!.single;
String description = section['Description']!.join(' ');
if (description.startsWith('United ')) {
@@ -364,11 +374,7 @@ String describeLocale(String tag) {
}
/// Writes the header of each class which corresponds to a locale.
String generateClassDeclaration(
LocaleInfo locale,
String classNamePrefix,
String superClass,
) {
String generateClassDeclaration(LocaleInfo locale, String classNamePrefix, String superClass) {
final String camelCaseName = locale.camelCase();
return '''
@@ -417,23 +423,23 @@ String generateString(String value) {
!value.contains(backslash),
'Input string cannot contain the sequence: '
'"__BACKSLASH__", as it is used as part of '
'backslash character processing.'
'backslash character processing.',
);
value = value
// Replace backslashes with a placeholder for now to properly parse
// other special characters.
.replaceAll(r'\', backslash)
.replaceAll(r'$', r'\$')
.replaceAll("'", r"\'")
.replaceAll('"', r'\"')
.replaceAll('\n', r'\n')
.replaceAll('\f', r'\f')
.replaceAll('\t', r'\t')
.replaceAll('\r', r'\r')
.replaceAll('\b', r'\b')
// Reintroduce escaped backslashes into generated Dart string.
.replaceAll(backslash, r'\\');
// Replace backslashes with a placeholder for now to properly parse
// other special characters.
.replaceAll(r'\', backslash)
.replaceAll(r'$', r'\$')
.replaceAll("'", r"\'")
.replaceAll('"', r'\"')
.replaceAll('\n', r'\n')
.replaceAll('\f', r'\f')
.replaceAll('\t', r'\t')
.replaceAll('\r', r'\r')
.replaceAll('\b', r'\b')
// Reintroduce escaped backslashes into generated Dart string.
.replaceAll(backslash, r'\\');
return "'$value'";
}
@@ -446,6 +452,7 @@ String generateEncodedString(String? locale, String value) {
return generateString(value);
}
final String unicodeEscapes = value.runes.map((int code) => '\\u{${code.toRadixString(16)}}').join();
final String unicodeEscapes =
value.runes.map((int code) => '\\u{${code.toRadixString(16)}}').join();
return "'$unicodeEscapes'";
}

View File

@@ -13,7 +13,7 @@ const List<String> kPluralSuffixes = <String>['Other', 'Zero', 'One', 'Two', 'Fe
final RegExp kPluralRegexp = RegExp(r'(\w*)(' + kPluralSuffixes.skip(1).join(r'|') + r')$');
class ValidationError implements Exception {
ValidationError(this. message);
ValidationError(this.message);
final String message;
@override
String toString() => message;
@@ -51,6 +51,7 @@ void validateEnglishLocalizations(File file) {
final int suffixIndex = resourceId.indexOf(suffix);
return suffixIndex != -1 && bundle['@${resourceId.substring(0, suffixIndex)}'] != null;
}
if (kPluralSuffixes.any(checkPluralResource)) {
continue;
}
@@ -107,10 +108,9 @@ void validateEnglishLocalizations(File file) {
/// keys in the resources for this locale, but which _aren't_ keys in the
/// canonical list.
/// 5. Removes the invalid mappings from this resource's locale.
void removeUndefinedLocalizations(
Map<LocaleInfo, Map<String, String>> localeToResources,
) {
final Map<String, String> canonicalLocalizations = localeToResources[LocaleInfo.fromString('en')]!;
void removeUndefinedLocalizations(Map<LocaleInfo, Map<String, String>> localeToResources) {
final Map<String, String> canonicalLocalizations =
localeToResources[LocaleInfo.fromString('en')]!;
final Set<String> canonicalKeys = Set<String>.from(canonicalLocalizations.keys);
localeToResources.forEach((LocaleInfo locale, Map<String, String> resources) {
@@ -124,7 +124,7 @@ void removeUndefinedLocalizations(
}
final Set<String> keys = Set<String>.from(
resources.keys.where((String key) => !isPluralVariation(key))
resources.keys.where((String key) => !isPluralVariation(key)),
);
final Set<String> invalidKeys = keys.difference(canonicalKeys);
@@ -146,7 +146,8 @@ void validateLocalizations(
Map<LocaleInfo, Map<String, dynamic>> localeToAttributes, {
bool removeUndefined = false,
}) {
final Map<String, String> canonicalLocalizations = localeToResources[LocaleInfo.fromString('en')]!;
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;
@@ -168,14 +169,16 @@ void validateLocalizations(
}
final Set<String> keys = Set<String>.from(
resources.keys.where((String key) => !isPluralVariation(key))
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 && !removeUndefined) {
errorMessages.writeln('Locale "$locale" contains invalid resource keys: ${invalidKeys.join(', ')}');
errorMessages.writeln(
'Locale "$locale" contains invalid resource keys: ${invalidKeys.join(', ')}',
);
}
// For language-level locales only, check that they have a complete list of
@@ -183,7 +186,7 @@ void validateLocalizations(
if (locale.length == 1) {
final Map<String, dynamic>? attributes = localeToAttributes[locale];
final List<String?> missingKeys = <String?>[];
for (final String missingKey in canonicalKeys.difference(keys)) {
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)) {
@@ -192,23 +195,25 @@ void validateLocalizations(
}
if (missingKeys.isNotEmpty) {
explainMissingKeys = true;
errorMessages.writeln('Locale "$locale" is missing the following resource keys: ${missingKeys.join(', ')}');
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('}');
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());
}