Move gen_l10n into flutter_tools (#65025)

This commit is contained in:
Shi-Hao Hong
2020-09-04 00:26:58 +08:00
committed by GitHub
parent eddf0a8abf
commit b80b432555
15 changed files with 48784 additions and 486 deletions

View File

@@ -4,199 +4,26 @@
import 'dart:io';
import 'package:args/args.dart' as argslib;
import 'package:file/local.dart' as local;
import 'package:path/path.dart' as path;
import '../gen_l10n.dart';
import '../gen_l10n_types.dart';
import '../localizations_utils.dart';
void main(List<String> arguments) {
final argslib.ArgParser parser = argslib.ArgParser();
parser.addFlag(
'help',
defaultsTo: false,
negatable: false,
help: 'Print this help message.',
);
parser.addOption(
'arb-dir',
defaultsTo: path.join('lib', 'l10n'),
help: 'The directory where the template and translated arb files are located.',
);
parser.addOption(
'output-dir',
help: 'The directory where the generated localization classes will be written '
'if the synthetic-package flag is set to false.'
'\n\n'
'If output-dir is specified and the synthetic-package flag is enabled, '
'this option will be ignored by the tool.'
'\n\n'
'The app must import the file specified in the \'output-localization-file\' '
'option from this directory. If unspecified, this defaults to the same '
'directory as the input directory specified in \'arb-dir\'.',
);
parser.addOption(
'template-arb-file',
defaultsTo: 'app_en.arb',
help: 'The template arb file that will be used as the basis for '
'generating the Dart localization and messages files.',
);
parser.addOption(
'output-localization-file',
defaultsTo: 'app_localizations.dart',
help: 'The filename for the output localization and localizations '
'delegate classes.',
);
parser.addOption(
'untranslated-messages-file',
help: 'The location of a file that describes the localization\n'
'messages have not been translated yet. Using this option will create\n'
'a JSON file at the target location, in the following format:\n\n'
'"locale": ["message_1", "message_2" ... "message_n"]\n\n'
'If this option is not specified, a summary of the messages that\n'
'have not been translated will be printed on the command line.'
);
parser.addOption(
'output-class',
defaultsTo: 'AppLocalizations',
help: 'The Dart class name to use for the output localization and '
'localizations delegate classes.',
);
parser.addOption(
'preferred-supported-locales',
help: 'The list of preferred supported locales for the application. '
'By default, the tool will generate the supported locales list in '
'alphabetical order. Use this flag if you would like to default to '
'a different locale. \n\n'
"For example, pass in ['en_US'] if you would like your app to "
'default to American English if a device supports it.',
);
parser.addOption(
'header',
help: 'The header to prepend to the generated Dart localizations '
'files. This option takes in a string. \n\n'
'For example, pass in "/// All localized files." if you would '
'like this string prepended to the generated Dart file. \n\n'
'Alternatively, see the `header-file` option to pass in a text '
'file for longer headers.'
);
parser.addOption(
'header-file',
help: 'The header to prepend to the generated Dart localizations '
'files. The value of this option is the name of the file that '
'contains the header text which will be inserted at the top '
'of each generated Dart file. \n\n'
'Alternatively, see the `header` option to pass in a string '
'for a simpler header. \n\n'
'This file should be placed in the directory specified in \'arb-dir\'.'
);
parser.addFlag(
'use-deferred-loading',
defaultsTo: false,
help: 'Whether to generate the Dart localization file with locales imported'
' as deferred, allowing for lazy loading of each locale in Flutter web.\n'
'\n'
'This can reduce a web app’s initial startup time by decreasing the '
'size of the JavaScript bundle. When this flag is set to true, the '
'messages for a particular locale are only downloaded and loaded by the '
'Flutter app as they are needed. For projects with a lot of different '
'locales and many localization strings, it can be an performance '
'improvement to have deferred loading. For projects with a small number '
'of locales, the difference is negligible, and might slow down the start '
'up compared to bundling the localizations with the rest of the '
'application.\n\n'
'Note that this flag does not affect other platforms such as mobile or '
'desktop.',
);
parser.addOption(
'gen-inputs-and-outputs-list',
valueHelp: 'path-to-output-directory',
help: 'When specified, the tool generates a JSON file containing the '
'tool\'s inputs and outputs named gen_l10n_inputs_and_outputs.json.'
'\n\n'
'This can be useful for keeping track of which files of the Flutter '
'project were used when generating the latest set of localizations. '
'For example, the Flutter tool\'s build system uses this file to '
'keep track of when to call gen_l10n during hot reload.\n\n'
'The value of this option is the directory where the JSON file will be '
'generated.'
'\n\n'
'When null, the JSON file will not be generated.'
);
parser.addFlag(
'synthetic-package',
defaultsTo: true,
help: 'Determines whether or not the generated output files will be '
'generated as a synthetic package or at a specified directory in '
'the Flutter project.'
'\n\n'
'This flag is set to true by default.'
'\n\n'
'When synthetic-package is set to false, it will generate the '
'localizations files in the directory specified by arb-dir by default. '
'\n\n'
'If output-dir is specified, files will be generated there.',
);
parser.addOption(
'project-dir',
valueHelp: 'absolute/path/to/flutter/project',
help: 'When specified, the tool uses the path passed into this option '
'as the directory of the root Flutter project.'
'\n\n'
'When null, the relative path to the present working directory will be used.'
/// Runs `flutter generate_localizations with arguments passed in.
///
/// This script exists as a legacy entrypoint, since existing users of
/// gen_l10n tool used to call
/// `dart ${FLUTTER}/dev/tools/localizations/bin/gen_l10n.dart <options>` to
/// generate their Flutter project's localizations resources.
///
/// Now, the appropriate way to use this tool is to either define an `l10n.yaml`
/// file in the Flutter project repository, or call
/// `flutter generate_localizations <options>`, since the code has moved
/// into `flutter_tools`.
Future<void> main(List<String> rawArgs) async {
final ProcessResult result = await Process.run(
'flutter',
<String>[
'generate_localizations',
...rawArgs,
],
);
final argslib.ArgResults results = parser.parse(arguments);
if (results['help'] == true) {
print(parser.usage);
exit(0);
}
precacheLanguageAndRegionTags();
final String inputPathString = results['arb-dir'] as String;
final String outputPathString = results['output-dir'] as String;
final String outputFileString = results['output-localization-file'] as String;
final String templateArbFileName = results['template-arb-file'] as String;
final String untranslatedMessagesFile = results['untranslated-messages-file'] as String;
final String classNameString = results['output-class'] as String;
final String preferredSupportedLocaleString = results['preferred-supported-locales'] as String;
final String headerString = results['header'] as String;
final String headerFile = results['header-file'] as String;
final bool useDeferredLoading = results['use-deferred-loading'] as bool;
final String inputsAndOutputsListPath = results['gen-inputs-and-outputs-list'] as String;
final bool useSyntheticPackage = results['synthetic-package'] as bool;
final String projectPathString = results['project-dir'] as String;
const local.LocalFileSystem fs = local.LocalFileSystem();
final LocalizationsGenerator localizationsGenerator = LocalizationsGenerator(fs);
try {
localizationsGenerator
..initialize(
inputPathString: inputPathString,
outputPathString: outputPathString,
templateArbFileName: templateArbFileName,
outputFileString: outputFileString,
classNameString: classNameString,
preferredSupportedLocaleString: preferredSupportedLocaleString,
headerString: headerString,
headerFile: headerFile,
useDeferredLoading: useDeferredLoading,
inputsAndOutputsListPath: inputsAndOutputsListPath,
useSyntheticPackage: useSyntheticPackage,
projectPathString: projectPathString,
)
..loadResources()
..writeOutputFiles()
..outputUnimplementedMessages(untranslatedMessagesFile);
} on FileSystemException catch (e) {
exitWithError(e.message);
} on FormatException catch (e) {
exitWithError(e.message);
} on L10nException catch (e) {
exitWithError(e.message);
}
stdout.write(result.stdout);
stderr.write(result.stderr);
}

View File

@@ -17,11 +17,19 @@ Future<void> main() async {
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('');
print('''// Copyright 2014 The Flutter Authors. All rights reserved.
final File subtagRegistry = File('../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.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Cache of $registry.
const String languageSubtagRegistry = \'\'\'$body\'\'\';''');
const String languageSubtagRegistry = \'\'\'$body\'\'\';''';
subtagRegistry.writeAsStringSync(content);
subtagRegistryFlutterTools.writeAsStringSync(content);
client.close(force: true);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,252 +0,0 @@
// 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.
const String fileTemplate = '''
@(header)
import 'dart:async';
// ignore: unused_import
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart' as intl;
@(messageClassImports)
/// Callers can lookup localized strings with an instance of @(class) returned
/// by `@(class).of(context)`.
///
/// Applications need to include `@(class).delegate()` in their app\'s
/// localizationDelegates list, and the locales they support in the app\'s
/// supportedLocales list. For example:
///
/// ```
/// import '@(importFile)';
///
/// return MaterialApp(
/// localizationsDelegates: @(class).localizationsDelegates,
/// supportedLocales: @(class).supportedLocales,
/// home: MyApplicationHome(),
/// );
/// ```
///
/// ## Update pubspec.yaml
///
/// Please make sure to update your pubspec.yaml to include the following
/// packages:
///
/// ```
/// dependencies:
/// # Internationalization support.
/// flutter_localizations:
/// sdk: flutter
/// intl: 0.16.1
///
/// # rest of dependencies
/// ```
///
/// ## iOS Applications
///
/// iOS applications define key application metadata, including supported
/// locales, in an Info.plist file that is built into the application bundle.
/// To configure the locales supported by your app, you’ll need to edit this
/// file.
///
/// First, open your project’s ios/Runner.xcworkspace Xcode workspace file.
/// Then, in the Project Navigator, open the Info.plist file under the Runner
/// project’s Runner folder.
///
/// Next, select the Information Property List item, select Add Item from the
/// Editor menu, then select Localizations from the pop-up menu.
///
/// Select and expand the newly-created Localizations item then, for each
/// locale your application supports, add a new item and select the locale
/// you wish to add from the pop-up menu in the Value field. This list should
/// be consistent with the languages listed in the @(class).supportedLocales
/// property.
abstract class @(class) {
@(class)(String locale) : assert(locale != null), localeName = intl.Intl.canonicalizedLocale(locale.toString());
// ignore: unused_field
final String localeName;
static @(class) of(BuildContext context) {
return Localizations.of<@(class)>(context, @(class));
}
static const LocalizationsDelegate<@(class)> delegate = _@(class)Delegate();
/// A list of this localizations delegate along with the default localizations
/// delegates.
///
/// Returns a list of localizations delegates containing this delegate along with
/// GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
/// and GlobalWidgetsLocalizations.delegate.
///
/// Additional delegates can be added by appending to this list in
/// MaterialApp. This list does not have to be used at all if a custom list
/// of delegates is preferred or required.
static const List<LocalizationsDelegate<dynamic>> localizationsDelegates = <LocalizationsDelegate<dynamic>>[
delegate,
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
];
/// A list of this localizations delegate's supported locales.
static const List<Locale> supportedLocales = <Locale>[
@(supportedLocales)
];
@(methods)}
@(delegateClass)
''';
const String numberFormatTemplate = '''
final intl.NumberFormat @(placeholder)NumberFormat = intl.NumberFormat.@(format)(
locale: localeName,
@(parameters)
);
final String @(placeholder)String = @(placeholder)NumberFormat.format(@(placeholder));
''';
const String dateFormatTemplate = '''
final intl.DateFormat @(placeholder)DateFormat = intl.DateFormat.@(format)(localeName);
final String @(placeholder)String = @(placeholder)DateFormat.format(@(placeholder));
''';
const String getterTemplate = '''
@override
String get @(name) => @(message);''';
const String methodTemplate = '''
@override
String @(name)(@(parameters)) {
return @(message);
}''';
const String formatMethodTemplate = '''
@override
String @(name)(@(parameters)) {
@(dateFormatting)
@(numberFormatting)
return @(message);
}''';
const String pluralMethodTemplate = '''
@override
String @(name)(@(parameters)) {
@(dateFormatting)
@(numberFormatting)
return intl.Intl.pluralLogic(
@(count),
locale: localeName,
@(pluralLogicArgs),
);
}''';
const String classFileTemplate = '''
@(header)
// ignore: unused_import
import 'package:intl/intl.dart' as intl;
import '@(fileName)';
// ignore_for_file: unnecessary_brace_in_string_interps
/// The translations for @(language) (`@(localeName)`).
class @(class) extends @(baseClass) {
@(class)([String locale = '@(localeName)']) : super(locale);
@(methods)
}
@(subclasses)''';
const String subclassTemplate = '''
/// The translations for @(language) (`@(localeName)`).
class @(class) extends @(baseLanguageClassName) {
@(class)(): super('@(localeName)');
@(methods)
}
''';
const String baseClassGetterTemplate = '''
// @(comment)
String get @(name);
''';
const String baseClassMethodTemplate = '''
// @(comment)
String @(name)(@(parameters));
''';
// DELEGATE CLASS TEMPLATES
const String delegateClassTemplate = '''
class _@(class)Delegate extends LocalizationsDelegate<@(class)> {
const _@(class)Delegate();
@override
Future<@(class)> load(Locale locale) {
@(loadBody)
}
@override
bool isSupported(Locale locale) => <String>[@(supportedLanguageCodes)].contains(locale.languageCode);
@override
bool shouldReload(_@(class)Delegate old) => false;
}
@(lookupFunction)''';
const String loadBodyTemplate = '''return SynchronousFuture<@(class)>(@(lookupName)(locale));''';
const String loadBodyDeferredLoadingTemplate = '''return @(lookupName)(locale);''';
// DELEGATE LOOKUP TEMPLATES
const String lookupFunctionTemplate = '''
@(class) @(lookupName)(Locale locale) {
@(lookupBody)
assert(false, '@(class).delegate failed to load unsupported locale "\$locale"');
return null;
}''';
const String lookupFunctionDeferredLoadingTemplate = '''
Future<@(class)> @(lookupName)(Locale locale) {
@(lookupBody)
assert(false, '@(class).delegate failed to load unsupported locale "\$locale"');
return null;
}''';
const String lookupBodyTemplate = '''@(lookupAllCodesSpecified)
@(lookupScriptCodeSpecified)
@(lookupCountryCodeSpecified)
@(lookupLanguageCodeSpecified)''';
const String switchClauseTemplate = '''case '@(case)': return @(localeClass)();''';
const String switchClauseDeferredLoadingTemplate = '''case '@(case)': return @(library).loadLibrary().then((dynamic _) => @(library).@(localeClass)());''';
const String nestedSwitchTemplate = '''case '@(languageCode)': {
switch (locale.@(code)) {
@(switchClauses)
}
break;
}''';
const String languageCodeSwitchTemplate = '''@(comment)
switch (locale.languageCode) {
@(switchClauses)
}
''';
const String allCodesLookupTemplate = '''// Lookup logic when language+script+country codes are specified.
switch (locale.toString()) {
@(allCodesSwitchClauses)
}
''';

View File

@@ -1,698 +0,0 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'package:intl/locale.dart';
import 'package:path/path.dart' as path;
import 'localizations_utils.dart';
// The set of date formats that can be automatically localized.
//
// The localizations generation tool makes use of the intl library's
// DateFormat class to properly format dates based on the locale, the
// desired format, as well as the passed in [DateTime]. For example, using
// DateFormat.yMMMMd("en_US").format(DateTime.utc(1996, 7, 10)) results
// in the string "July 10, 1996".
//
// Since the tool generates code that uses DateFormat's constructor, it is
// necessary to verify that the constructor exists, or the
// tool will generate code that may cause a compile-time error.
//
// See also:
//
// * <https://pub.dev/packages/intl>
// * <https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html>
// * <https://api.dartlang.org/stable/2.7.0/dart-core/DateTime-class.html>
const Set<String> _validDateFormats = <String>{
'd',
'E',
'EEEE',
'LLL',
'LLLL',
'M',
'Md',
'MEd',
'MMM',
'MMMd',
'MMMEd',
'MMMM',
'MMMMd',
'MMMMEEEEd',
'QQQ',
'QQQQ',
'y',
'yM',
'yMd',
'yMEd',
'yMMM',
'yMMMd',
'yMMMEd',
'yMMMM',
'yMMMMd',
'yMMMMEEEEd',
'yQQQ',
'yQQQQ',
'H',
'Hm',
'Hms',
'j',
'jm',
'jms',
'jmv',
'jmz',
'jv',
'jz',
'm',
'ms',
's',
};
// The set of number formats that can be automatically localized.
//
// The localizations generation tool makes use of the intl library's
// NumberFormat class to properly format numbers based on the locale and
// the desired format. For example, using
// NumberFormat.compactLong("en_US").format(1200000) results
// in the string "1.2 million".
//
// Since the tool generates code that uses NumberFormat's constructor, it is
// necessary to verify that the constructor exists, or the
// tool will generate code that may cause a compile-time error.
//
// See also:
//
// * <https://pub.dev/packages/intl>
// * <https://pub.dev/documentation/intl/latest/intl/NumberFormat-class.html>
const Set<String> _validNumberFormats = <String>{
'compact',
'compactCurrency',
'compactSimpleCurrency',
'compactLong',
'currency',
'decimalPattern',
'decimalPercentPattern',
'percentPattern',
'scientificPattern',
'simpleCurrency',
};
// The names of the NumberFormat factory constructors which have named
// parameters rather than positional parameters.
//
// This helps the tool correctly generate number formmatting code correctly.
//
// Example of code that uses named parameters:
// final NumberFormat format = NumberFormat.compact(
// locale: localeName,
// );
//
// Example of code that uses positional parameters:
// final NumberFormat format = NumberFormat.scientificPattern(localeName);
const Set<String> _numberFormatsWithNamedParameters = <String>{
'compact',
'compactCurrency',
'compactSimpleCurrency',
'compactLong',
'currency',
'decimalPercentPattern',
'simpleCurrency',
};
class L10nException implements Exception {
L10nException(this.message);
final String message;
}
// One optional named parameter to be used by a NumberFormat.
//
// Some of the NumberFormat factory constructors have optional named parameters.
// For example NumberFormat.compactCurrency has a decimalDigits parameter that
// specifies the number of decimal places to use when formatting.
//
// Optional parameters for NumberFormat placeholders are specified as a
// JSON map value for optionalParameters in a resource's "@" ARB file entry:
//
// "@myResourceId": {
// "placeholders": {
// "myNumberPlaceholder": {
// "type": "double",
// "format": "compactCurrency",
// "optionalParameters": {
// "decimalDigits": 2
// }
// }
// }
// }
class OptionalParameter {
const OptionalParameter(this.name, this.value) : assert(name != null), assert(value != null);
final String name;
final Object value;
}
// One message parameter: one placeholder from an @foo entry in the template ARB file.
//
// Placeholders are specified as a JSON map with one entry for each placeholder.
// One placeholder must be specified for each message "{parameter}".
// Each placeholder entry is also a JSON map. If the map is empty, the placeholder
// is assumed to be an Object value whose toString() value will be displayed.
// For example:
//
// "greeting": "{hello} {world}",
// "@greeting": {
// "description": "A message with a two parameters",
// "placeholders": {
// "hello": {},
// "world": {}
// }
// }
//
// Each placeholder can optionally specify a valid Dart type. If the type
// is NumberFormat or DateFormat then a format which matches one of the
// type's factory constructors can also be specified. In this example the
// date placeholder is to be formated with DateFormat.yMMMMd:
//
// "helloWorldOn": "Hello World on {date}",
// "@helloWorldOn": {
// "description": "A message with a date parameter",
// "placeholders": {
// "date": {
// "type": "DateTime",
// "format": "yMMMMd"
// }
// }
// }
//
class Placeholder {
Placeholder(this.resourceId, this.name, Map<String, dynamic> attributes)
: assert(resourceId != null),
assert(name != null),
example = _stringAttribute(resourceId, name, attributes, 'example'),
type = _stringAttribute(resourceId, name, attributes, 'type') ?? 'Object',
format = _stringAttribute(resourceId, name, attributes, 'format'),
optionalParameters = _optionalParameters(resourceId, name, attributes);
final String resourceId;
final String name;
final String example;
final String type;
final String format;
final List<OptionalParameter> optionalParameters;
bool get requiresFormatting => <String>['DateTime', 'double', 'int', 'num'].contains(type);
bool get isNumber => <String>['double', 'int', 'num'].contains(type);
bool get hasValidNumberFormat => _validNumberFormats.contains(format);
bool get hasNumberFormatWithParameters => _numberFormatsWithNamedParameters.contains(format);
bool get isDate => 'DateTime' == type;
bool get hasValidDateFormat => _validDateFormats.contains(format);
static String _stringAttribute(
String resourceId,
String name,
Map<String, dynamic> attributes,
String attributeName,
) {
final dynamic value = attributes[attributeName];
if (value == null)
return null;
if (value is! String || (value as String).isEmpty) {
throw L10nException(
'The "$attributeName" value of the "$name" placeholder in message $resourceId '
'must be a non-empty string.',
);
}
return value as String;
}
static List<OptionalParameter> _optionalParameters(
String resourceId,
String name,
Map<String, dynamic> attributes
) {
final dynamic value = attributes['optionalParameters'];
if (value == null)
return <OptionalParameter>[];
if (value is! Map<String, Object>) {
throw L10nException(
'The "optionalParameters" value of the "$name" placeholder in message '
'$resourceId is not a properly formatted Map. Ensure that it is a map '
'with keys that are strings.'
);
}
final Map<String, dynamic> optionalParameterMap = value as Map<String, dynamic>;
return optionalParameterMap.keys.map<OptionalParameter>((String parameterName) {
return OptionalParameter(parameterName, optionalParameterMap[parameterName]);
}).toList();
}
}
// One translation: one pair of foo,@foo entries from the template ARB file.
//
// The template ARB file must contain an entry called @myResourceId for each
// message named myResourceId. The @ entry describes message parameters
// called "placeholders" and can include an optional description.
// Here's a simple example message with no parameters:
//
// "helloWorld": "Hello World",
// "@helloWorld": {
// "description": "The conventional newborn programmer greeting"
// }
//
// The value of this Message is "Hello World". The Message's value is the
// localized string to be shown for the template ARB file's locale.
// The docs for the Placeholder explain how placeholder entries are defined.
class Message {
Message(Map<String, dynamic> bundle, this.resourceId)
: assert(bundle != null),
assert(resourceId != null && resourceId.isNotEmpty),
value = _value(bundle, resourceId),
description = _description(bundle, resourceId),
placeholders = _placeholders(bundle, resourceId),
_pluralMatch = _pluralRE.firstMatch(_value(bundle, resourceId));
static final RegExp _pluralRE = RegExp(r'\s*\{([\w\s,]*),\s*plural\s*,');
final String resourceId;
final String value;
final String description;
final List<Placeholder> placeholders;
final RegExpMatch _pluralMatch;
bool get isPlural => _pluralMatch != null && _pluralMatch.groupCount == 1;
bool get placeholdersRequireFormatting => placeholders.any((Placeholder p) => p.requiresFormatting);
Placeholder getCountPlaceholder() {
assert(isPlural);
final String countPlaceholderName = _pluralMatch[1];
return placeholders.firstWhere(
(Placeholder p) => p.name == countPlaceholderName,
orElse: () {
throw L10nException('Cannot find the $countPlaceholderName placeholder in plural message "$resourceId".');
}
);
}
static String _value(Map<String, dynamic> bundle, String resourceId) {
final dynamic value = bundle[resourceId];
if (value == null)
throw L10nException('A value for resource "$resourceId" was not found.');
if (value is! String)
throw L10nException('The value of "$resourceId" is not a string.');
return bundle[resourceId] as String;
}
static Map<String, dynamic> _attributes(Map<String, dynamic> bundle, String resourceId) {
final dynamic attributes = bundle['@$resourceId'];
if (attributes == null) {
throw L10nException(
'Resource attribute "@$resourceId" was not found. Please '
'ensure that each resource has a corresponding @resource.'
);
}
if (attributes is! Map<String, dynamic>) {
throw L10nException(
'The resource attribute "@$resourceId" is not a properly formatted Map. '
'Ensure that it is a map with keys that are strings.'
);
}
return attributes as Map<String, dynamic>;
}
static String _description(Map<String, dynamic> bundle, String resourceId) {
final dynamic value = _attributes(bundle, resourceId)['description'];
if (value == null)
return null;
if (value is! String) {
throw L10nException(
'The description for "@$resourceId" is not a properly formatted String.'
);
}
return value as String;
}
static List<Placeholder> _placeholders(Map<String, dynamic> bundle, String resourceId) {
final dynamic value = _attributes(bundle, resourceId)['placeholders'];
if (value == null)
return <Placeholder>[];
if (value is! Map<String, dynamic>) {
throw L10nException(
'The "placeholders" attribute for message $resourceId, is not '
'properly formatted. Ensure that it is a map with string valued keys.'
);
}
final Map<String, dynamic> allPlaceholdersMap = value as Map<String, dynamic>;
return allPlaceholdersMap.keys.map<Placeholder>((String placeholderName) {
final dynamic value = allPlaceholdersMap[placeholderName];
if (value is! Map<String, dynamic>) {
throw L10nException(
'The value of the "$placeholderName" placeholder attribute for message '
'"$resourceId", is not properly formatted. Ensure that it is a map '
'with string valued keys.'
);
}
return Placeholder(resourceId, placeholderName, value as Map<String, dynamic>);
}).toList();
}
}
// Represents the contents of one ARB file.
class AppResourceBundle {
factory AppResourceBundle(File file) {
assert(file != null);
// Assuming that the caller has verified that the file exists and is readable.
Map<String, dynamic> resources;
try {
resources = json.decode(file.readAsStringSync()) as Map<String, dynamic>;
} on FormatException catch (e) {
throw L10nException(
'The arb file ${file.path} has the following formatting issue: \n'
'${e.toString()}',
);
}
String localeString = resources['@@locale'] as String;
// Look for the first instance of an ISO 639-1 language code, matching exactly.
final String fileName = path.basenameWithoutExtension(file.path);
for (int index = 0; index < fileName.length; index += 1) {
// If an underscore was found, check if locale string follows.
if (fileName[index] == '_' && fileName[index + 1] != null) {
// If Locale.tryParse fails, it returns null.
final Locale parserResult = Locale.tryParse(fileName.substring(index + 1));
// If the parserResult is not an actual locale identifier, end the loop.
if (parserResult != null && _iso639Languages.contains(parserResult.languageCode)) {
// The parsed result uses dashes ('-'), but we want underscores ('_').
final String parserLocaleString = parserResult.toString().replaceAll('-', '_');
if (localeString == null) {
// If @@locale was not defined, use the filename locale suffix.
localeString = parserLocaleString;
} else {
// If the localeString was defined in @@locale and in the filename, verify to
// see if the parsed locale matches, throw an error if it does not. This
// prevents developers from confusing issues when both @@locale and
// "_{locale}" is specified in the filename.
if (localeString != parserLocaleString) {
throw L10nException(
'The locale specified in @@locale and the arb filename do not match. \n'
'Please make sure that they match, since this prevents any confusion \n'
'with which locale to use. Otherwise, specify the locale in either the \n'
'filename of the @@locale key only.\n'
'Current @@locale value: $localeString\n'
'Current filename extension: $parserLocaleString'
);
}
}
break;
}
}
}
if (localeString == null) {
throw L10nException(
"The following .arb file's locale could not be determined: \n"
'${file.path} \n'
"Make sure that the locale is specified in the file's '@@locale' "
'property or as part of the filename (e.g. file_en.arb)'
);
}
final Iterable<String> ids = resources.keys.where((String key) => !key.startsWith('@'));
return AppResourceBundle._(file, LocaleInfo.fromString(localeString), resources, ids);
}
const AppResourceBundle._(this.file, this.locale, this.resources, this.resourceIds);
final File file;
final LocaleInfo locale;
final Map<String, dynamic> resources;
final Iterable<String> resourceIds;
String translationFor(Message message) => resources[message.resourceId] as String;
@override
String toString() {
return 'AppResourceBundle($locale, ${file.path})';
}
}
// Represents all of the ARB files in [directory] as [AppResourceBundle]s.
class AppResourceBundleCollection {
factory AppResourceBundleCollection(Directory directory) {
assert(directory != null);
// Assuming that the caller has verified that the directory is readable.
final RegExp filenameRE = RegExp(r'(\w+)\.arb$');
final Map<LocaleInfo, AppResourceBundle> localeToBundle = <LocaleInfo, AppResourceBundle>{};
final Map<String, List<LocaleInfo>> languageToLocales = <String, List<LocaleInfo>>{};
final List<File> files = directory.listSync().whereType<File>().toList()..sort(sortFilesByPath);
for (final File file in files) {
if (filenameRE.hasMatch(file.path)) {
final AppResourceBundle bundle = AppResourceBundle(file);
if (localeToBundle[bundle.locale] != null) {
throw L10nException(
"Multiple arb files with the same '${bundle.locale}' locale detected. \n"
'Ensure that there is exactly one arb file for each locale.'
);
}
localeToBundle[bundle.locale] = bundle;
languageToLocales[bundle.locale.languageCode] ??= <LocaleInfo>[];
languageToLocales[bundle.locale.languageCode].add(bundle.locale);
}
}
languageToLocales.forEach((String language, List<LocaleInfo> listOfCorrespondingLocales) {
final List<String> localeStrings = listOfCorrespondingLocales.map((LocaleInfo locale) {
return locale.toString();
}).toList();
if (!localeStrings.contains(language)) {
throw L10nException(
'Arb file for a fallback, $language, does not exist, even though \n'
'the following locale(s) exist: $listOfCorrespondingLocales. \n'
'When locales specify a script code or country code, a \n'
'base locale (without the script code or country code) should \n'
'exist as the fallback. Please create a {fileName}_$language.arb \n'
'file.'
);
}
});
return AppResourceBundleCollection._(directory, localeToBundle, languageToLocales);
}
const AppResourceBundleCollection._(this._directory, this._localeToBundle, this._languageToLocales);
final Directory _directory;
final Map<LocaleInfo, AppResourceBundle> _localeToBundle;
final Map<String, List<LocaleInfo>> _languageToLocales;
Iterable<LocaleInfo> get locales => _localeToBundle.keys;
Iterable<AppResourceBundle> get bundles => _localeToBundle.values;
AppResourceBundle bundleFor(LocaleInfo locale) => _localeToBundle[locale];
Iterable<String> get languages => _languageToLocales.keys;
Iterable<LocaleInfo> localesForLanguage(String language) => _languageToLocales[language] ?? <LocaleInfo>[];
@override
String toString() {
return 'AppResourceBundleCollection(${_directory.path}, ${locales.length} locales)';
}
}
// A set containing all the ISO630-1 languages. This list was pulled from https://datahub.io/core/language-codes.
final Set<String> _iso639Languages = <String>{
'aa',
'ab',
'ae',
'af',
'ak',
'am',
'an',
'ar',
'as',
'av',
'ay',
'az',
'ba',
'be',
'bg',
'bh',
'bi',
'bm',
'bn',
'bo',
'br',
'bs',
'ca',
'ce',
'ch',
'co',
'cr',
'cs',
'cu',
'cv',
'cy',
'da',
'de',
'dv',
'dz',
'ee',
'el',
'en',
'eo',
'es',
'et',
'eu',
'fa',
'ff',
'fi',
'fil',
'fj',
'fo',
'fr',
'fy',
'ga',
'gd',
'gl',
'gn',
'gsw',
'gu',
'gv',
'ha',
'he',
'hi',
'ho',
'hr',
'ht',
'hu',
'hy',
'hz',
'ia',
'id',
'ie',
'ig',
'ii',
'ik',
'io',
'is',
'it',
'iu',
'ja',
'jv',
'ka',
'kg',
'ki',
'kj',
'kk',
'kl',
'km',
'kn',
'ko',
'kr',
'ks',
'ku',
'kv',
'kw',
'ky',
'la',
'lb',
'lg',
'li',
'ln',
'lo',
'lt',
'lu',
'lv',
'mg',
'mh',
'mi',
'mk',
'ml',
'mn',
'mr',
'ms',
'mt',
'my',
'na',
'nb',
'nd',
'ne',
'ng',
'nl',
'nn',
'no',
'nr',
'nv',
'ny',
'oc',
'oj',
'om',
'or',
'os',
'pa',
'pi',
'pl',
'ps',
'pt',
'qu',
'rm',
'rn',
'ro',
'ru',
'rw',
'sa',
'sc',
'sd',
'se',
'sg',
'si',
'sk',
'sl',
'sm',
'sn',
'so',
'sq',
'sr',
'ss',
'st',
'su',
'sv',
'sw',
'ta',
'te',
'tg',
'th',
'ti',
'tk',
'tl',
'tn',
'to',
'tr',
'ts',
'tt',
'tw',
'ty',
'ug',
'uk',
'ur',
'uz',
've',
'vi',
'vo',
'wa',
'wo',
'xh',
'yi',
'yo',
'za',
'zh',
'zu',
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,71 +0,0 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../../localization/localizations_utils.dart';
import '../common.dart';
void main() {
group('generateString', () {
test('handles simple string', () {
expect(generateString('abc'), "'abc'");
});
test('handles string with quote', () {
expect(generateString("ab'c"), "'ab\\\'c'");
});
test('handles string with double quote', () {
expect(generateString('ab"c'), "'ab\\\"c'");
});
test('handles string with both single and double quote', () {
expect(generateString('''a'b"c'''), '\'a\\\'b\\"c\'');
});
test('handles string with a triple single quote and a double quote', () {
expect(generateString("""a"b'''c"""), '\'a\\"b\\\'\\\'\\\'c\'');
});
test('handles string with a triple double quote and a single quote', () {
expect(generateString('''a'b"""c'''), '\'a\\\'b\\"\\"\\"c\'');
});
test('handles string with both triple single and triple double quote', () {
expect(generateString('''a\'''b"""c'''), '\'a\\\'\\\'\\\'b\\"\\"\\"c\'');
});
test('escapes dollar when escapeDollar is true', () {
expect(generateString(r'ab$c'), "'ab\\\$c'");
});
test('handles backslash', () {
expect(generateString(r'ab\c'), r"'ab\\c'");
});
test('handles backslash followed by "n" character', () {
expect(generateString(r'ab\nc'), r"'ab\\nc'");
});
test('supports newline escaping', () {
expect(generateString('ab\nc'), "'ab\\nc'");
});
test('supports form feed escaping', () {
expect(generateString('ab\fc'), "'ab\\fc'");
});
test('supports tab escaping', () {
expect(generateString('ab\tc'), "'ab\\tc'");
});
test('supports carriage return escaping', () {
expect(generateString('ab\rc'), "'ab\\rc'");
});
test('supports backspace escaping', () {
expect(generateString('ab\bc'), "'ab\\bc'");
});
});
}