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);