gen_localizations.dart 25.2 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6 7 8 9
// This program generates a getMaterialTranslation() and a
// getCupertinoTranslation() function that look up the translations provided by
// the arb files. The returned value is a generated instance of a
// GlobalMaterialLocalizations or a GlobalCupertinoLocalizations that
// corresponds to a single locale.
10
//
11
// The *.arb files are in packages/flutter_localizations/lib/src/l10n.
12 13 14 15 16
//
// The arb (JSON) format files must contain a single map indexed by locale.
// Each map value is itself a map with resource identifier keys and localized
// resource string values.
//
17 18 19 20
// The arb filenames are expected to have the form "material_(\w+)\.arb" or
// "cupertino_(\w+)\.arb" where the group following "_" identifies the language
// code and the country code, e.g. "material_en.arb" or "material_en_GB.arb".
// In most cases both codes are just two characters.
21 22 23 24
//
// This app is typically run by hand when a module's .arb files have been
// updated.
//
25 26 27 28 29 30 31
// ## Usage
//
// Run this program from the root of the git repository.
//
// The following outputs the generated Dart code to the console as a dry run:
//
// ```
32
// dart dev/tools/localization/bin/gen_localizations.dart
33 34
// ```
//
35
// If the data looks good, use the `-w` or `--overwrite` option to overwrite the
36 37
// packages/flutter_localizations/lib/src/l10n/generated_material_localizations.dart
// and packages/flutter_localizations/lib/src/l10n/generated_cupertino_localizations.dart file:
38 39
//
// ```
40
// dart dev/tools/localization/bin/gen_localizations.dart --overwrite
41
// ```
42

43
import 'dart:async';
44 45
import 'dart:io';

46 47
import 'package:path/path.dart' as path;
import 'package:meta/meta.dart';
48

49 50 51 52
import '../gen_cupertino_localizations.dart';
import '../gen_material_localizations.dart';
import '../localizations_utils.dart';
import '../localizations_validator.dart';
53

54 55 56 57 58 59 60 61
/// This is the core of this script; it generates the code used for translations.
String generateArbBasedLocalizationSubclasses({
  @required Map<LocaleInfo, Map<String, String>> localeToResources,
  @required Map<LocaleInfo, Map<String, dynamic>> localeToResourceAttributes,
  @required String generatedClassPrefix,
  @required String baseClass,
  @required HeaderGenerator generateHeader,
  @required ConstructorGenerator generateConstructor,
62
  @required String factoryName,
63 64
  @required String factoryDeclaration,
  @required String factoryArguments,
65 66
  @required String supportedLanguagesConstant,
  @required String supportedLanguagesDocMacro,
67 68 69 70 71 72 73
}) {
  assert(localeToResources != null);
  assert(localeToResourceAttributes != null);
  assert(generatedClassPrefix.isNotEmpty);
  assert(baseClass.isNotEmpty);
  assert(generateHeader != null);
  assert(generateConstructor != null);
74
  assert(factoryName.isNotEmpty);
75 76
  assert(factoryDeclaration.isNotEmpty);
  assert(factoryArguments.isNotEmpty);
77 78
  assert(supportedLanguagesConstant.isNotEmpty);
  assert(supportedLanguagesDocMacro.isNotEmpty);
79

80
  final StringBuffer output = StringBuffer();
81
  output.writeln(generateHeader('dart dev/tools/localization/bin/gen_localizations.dart --overwrite'));
82

83
  final StringBuffer supportedLocales = StringBuffer();
84

85 86 87 88
  final Map<String, List<LocaleInfo>> languageToLocales = <String, List<LocaleInfo>>{};
  final Map<String, Set<String>> languageToScriptCodes = <String, Set<String>>{};
  // Used to calculate if there are any corresponding countries for a given language and script.
  final Map<LocaleInfo, Set<String>> languageAndScriptToCountryCodes = <LocaleInfo, Set<String>>{};
89
  final Set<String> allResourceIdentifiers = <String>{};
90 91
  for (LocaleInfo locale in localeToResources.keys.toList()..sort()) {
    if (locale.scriptCode != null) {
92
      languageToScriptCodes[locale.languageCode] ??= <String>{};
93 94 95 96
      languageToScriptCodes[locale.languageCode].add(locale.scriptCode);
    }
    if (locale.countryCode != null && locale.scriptCode != null) {
      final LocaleInfo key = LocaleInfo.fromString(locale.languageCode + '_' + locale.scriptCode);
97
      languageAndScriptToCountryCodes[key] ??= <String>{};
98 99 100 101
      languageAndScriptToCountryCodes[key].add(locale.countryCode);
    }
    languageToLocales[locale.languageCode] ??= <LocaleInfo>[];
    languageToLocales[locale.languageCode].add(locale);
102
    allResourceIdentifiers.addAll(localeToResources[locale].keys.toList()..sort());
103 104
  }

105
  // We generate one class per supported language (e.g.
106 107
  // `MaterialLocalizationEn`). These implement everything that is needed by the
  // superclass (e.g. GlobalMaterialLocalizations).
108

109 110 111 112 113
  // We also generate one subclass for each locale with a script code (e.g.
  // `MaterialLocalizationZhHant`). Their superclasses are the aforementioned
  // language classes for the same locale but without a script code (e.g.
  // `MaterialLocalizationZh`).

114 115 116
  // We also generate one subclass for each locale with a country code (e.g.
  // `MaterialLocalizationEnGb`). Their superclasses are the aforementioned
  // language classes for the same locale but without a country code (e.g.
117 118 119 120 121 122 123 124 125 126 127
  // `MaterialLocalizationEn`).

  // If scriptCodes for a language are defined, we expect a scriptCode to be
  // defined for locales that contain a countryCode. The superclass becomes
  // the script sublcass (e.g. `MaterialLocalizationZhHant`) and the generated
  // subclass will also contain the script code (e.g. `MaterialLocalizationZhHantTW`).

  // When scriptCodes are not defined for languages that use scriptCodes to distinguish
  // between significantly differing scripts, we assume the scriptCodes in the
  // [LocaleInfo.fromString] factory and add it to the [LocaleInfo]. We then generate
  // the script classes based on the first locale that we assume to use the script.
128 129 130

  final List<String> allKeys = allResourceIdentifiers.toList()..sort();
  final List<String> languageCodes = languageToLocales.keys.toList()..sort();
131
  final LocaleInfo canonicalLocale = LocaleInfo.fromString('en');
132
  for (String languageName in languageCodes) {
133
    final LocaleInfo languageLocale = LocaleInfo.fromString(languageName);
134 135 136
    output.writeln(generateClassDeclaration(languageLocale, generatedClassPrefix, baseClass));
    output.writeln(generateConstructor(languageLocale));

137
    final Map<String, String> languageResources = localeToResources[languageLocale];
138
    for (String key in allKeys) {
139
      final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>;
140
      output.writeln(generateGetter(key, languageResources[key], attributes, languageLocale));
141
    }
142 143
    output.writeln('}');
    int countryCodeCount = 0;
144 145 146 147 148 149 150
    int scriptCodeCount = 0;
    if (languageToScriptCodes.containsKey(languageName)) {
      scriptCodeCount = languageToScriptCodes[languageName].length;
      // Language has scriptCodes, so we need to properly fallback countries to corresponding
      // script default values before language default values.
      for (String scriptCode in languageToScriptCodes[languageName]) {
        final LocaleInfo scriptBaseLocale = LocaleInfo.fromString(languageName + '_' + scriptCode);
151 152 153 154 155 156
        output.writeln(generateClassDeclaration(
          scriptBaseLocale,
          generatedClassPrefix,
          '$generatedClassPrefix${camelCase(languageLocale)}',
        ));
        output.writeln(generateConstructor(scriptBaseLocale));
157
        final Map<String, String> scriptResources = localeToResources[scriptBaseLocale];
158
        for (String key in scriptResources.keys.toList()..sort()) {
159 160
          if (languageResources[key] == scriptResources[key])
            continue;
161
          final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>;
162
          output.writeln(generateGetter(key, scriptResources[key], attributes, languageLocale));
163 164 165 166 167 168 169 170 171 172 173 174
        }
        output.writeln('}');

        final List<LocaleInfo> localeCodes = languageToLocales[languageName]..sort();
        for (LocaleInfo locale in localeCodes) {
          if (locale.originalString == languageName)
            continue;
          if (locale.originalString == languageName + '_' + scriptCode)
            continue;
          if (locale.scriptCode != scriptCode)
            continue;
          countryCodeCount += 1;
175 176 177 178 179 180
          output.writeln(generateClassDeclaration(
            locale,
            generatedClassPrefix,
            '$generatedClassPrefix${camelCase(scriptBaseLocale)}',
          ));
          output.writeln(generateConstructor(locale));
181 182 183 184 185
          final Map<String, String> localeResources = localeToResources[locale];
          for (String key in localeResources.keys) {
            // When script fallback contains the key, we compare to it instead of language fallback.
            if (scriptResources.containsKey(key) ? scriptResources[key] == localeResources[key] : languageResources[key] == localeResources[key])
              continue;
186
            final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>;
187
            output.writeln(generateGetter(key, localeResources[key], attributes, languageLocale));
188 189 190 191 192 193 194 195 196 197
          }
         output.writeln('}');
        }
      }
    } else {
      // No scriptCode. Here, we do not compare against script default (because it
      // doesn't exist).
      final List<LocaleInfo> localeCodes = languageToLocales[languageName]..sort();
      for (LocaleInfo locale in localeCodes) {
        if (locale.originalString == languageName)
198
          continue;
199 200
        countryCodeCount += 1;
        final Map<String, String> localeResources = localeToResources[locale];
201 202 203 204 205 206
        output.writeln(generateClassDeclaration(
          locale,
          generatedClassPrefix,
          '$generatedClassPrefix${camelCase(languageLocale)}',
        ));
        output.writeln(generateConstructor(locale));
207 208 209
        for (String key in localeResources.keys) {
          if (languageResources[key] == localeResources[key])
            continue;
210
          final Map<String, dynamic> attributes = localeToResourceAttributes[canonicalLocale][key] as Map<String, dynamic>;
211
          output.writeln(generateGetter(key, localeResources[key], attributes, languageLocale));
212 213
        }
       output.writeln('}');
214
      }
215
    }
216
    final String scriptCodeMessage = scriptCodeCount == 0 ? '' : ' and $scriptCodeCount script' + (scriptCodeCount == 1 ? '' : 's');
217
    if (countryCodeCount == 0) {
218 219 220 221 222
      if (scriptCodeCount == 0)
        supportedLocales.writeln('///  * `$languageName` - ${describeLocale(languageName)}');
      else
        supportedLocales.writeln('///  * `$languageName` - ${describeLocale(languageName)} (plus $scriptCodeCount script' + (scriptCodeCount == 1 ? '' : 's') + ')');

223
    } else if (countryCodeCount == 1) {
224
      supportedLocales.writeln('///  * `$languageName` - ${describeLocale(languageName)} (plus one country variation$scriptCodeMessage)');
225
    } else {
226
      supportedLocales.writeln('///  * `$languageName` - ${describeLocale(languageName)} (plus $countryCodeCount country variations$scriptCodeMessage)');
227 228 229
    }
  }

230 231
  // Generate the factory function. Given a Locale it returns the corresponding
  // base class implementation.
232 233
  output.writeln('''

234 235
/// The set of supported languages, as language code strings.
///
236
/// The [$baseClass.delegate] can generate localizations for
237 238 239 240 241 242 243
/// any [Locale] with a language code from this set, regardless of the region.
/// Some regions have specific support (e.g. `de` covers all forms of German,
/// but there is support for `de-CH` specifically to override some of the
/// translations for Switzerland).
///
/// See also:
///
244 245 246
///  * [$factoryName], whose documentation describes these values.
final Set<String> $supportedLanguagesConstant = HashSet<String>.from(const <String>[
${languageCodes.map<String>((String value) => "  '$value', // ${describeLocale(value)}").toList().join('\n')}
247 248
]);

249
/// Creates a [$baseClass] instance for the given `locale`.
250
///
251 252
/// All of the function's arguments except `locale` will be passed to the [
/// $baseClass] constructor. (The `localeName` argument of that
253 254 255 256 257
/// constructor is specified by the actual subclass constructor by this
/// function.)
///
/// The following locales are supported by this package:
///
258
/// {@template $supportedLanguagesDocMacro}
259 260 261
$supportedLocales/// {@endtemplate}
///
/// Generally speaking, this method is only intended to be used by
262 263
/// [$baseClass.delegate].
$factoryDeclaration
264 265
  switch (locale.languageCode) {''');
  for (String language in languageToLocales.keys) {
266
    // Only one instance of the language.
267 268
    if (languageToLocales[language].length == 1) {
      output.writeln('''
269
    case '$language':
270
      return $generatedClassPrefix${camelCase(languageToLocales[language][0])}($factoryArguments);''');
271
    } else if (!languageToScriptCodes.containsKey(language)) { // Does not distinguish between scripts. Switch on countryCode directly.
272
      output.writeln('''
273 274
    case '$language': {
      switch (locale.countryCode) {''');
275 276
      for (LocaleInfo locale in languageToLocales[language]) {
        if (locale.originalString == language)
277
          continue;
278 279
        assert(locale.length > 1);
        final String countryCode = locale.countryCode;
280
        output.writeln('''
281
        case '$countryCode':
282
          return $generatedClassPrefix${camelCase(locale)}($factoryArguments);''');
283 284 285
      }
      output.writeln('''
      }
286
      return $generatedClassPrefix${camelCase(LocaleInfo.fromString(language))}($factoryArguments);
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
    }''');
    } else { // Language has scriptCode, add additional switch logic.
      bool hasCountryCode = false;
      output.writeln('''
    case '$language': {
      switch (locale.scriptCode) {''');
      for (String scriptCode in languageToScriptCodes[language]) {
        final LocaleInfo scriptLocale = LocaleInfo.fromString(language + '_' + scriptCode);
        output.writeln('''
        case '$scriptCode': {''');
        if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) {
          output.writeln('''
          switch (locale.countryCode) {''');
          for (LocaleInfo locale in languageToLocales[language]) {
            if (locale.countryCode == null)
              continue;
            else
              hasCountryCode = true;
            if (locale.originalString == language)
              continue;
            if (locale.scriptCode != scriptCode && locale.scriptCode != null)
              continue;
            final String countryCode = locale.countryCode;
            output.writeln('''
            case '$countryCode':
312
              return $generatedClassPrefix${camelCase(locale)}($factoryArguments);''');
313 314 315 316 317 318 319 320 321 322 323
          }
        }
        // Return a fallback locale that matches scriptCode, but not countryCode.
        //
        // Explicitly defined scriptCode fallback:
        if (languageToLocales[language].contains(scriptLocale)) {
          if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) {
            output.writeln('''
          }''');
          }
          output.writeln('''
324
          return $generatedClassPrefix${camelCase(scriptLocale)}($factoryArguments);
325 326 327 328 329 330 331 332 333 334 335 336
        }''');
        } else {
          // Not Explicitly defined, fallback to first locale with the same language and
          // script:
          for (LocaleInfo locale in languageToLocales[language]) {
            if (locale.scriptCode != scriptCode)
              continue;
            if (languageAndScriptToCountryCodes.containsKey(scriptLocale)) {
              output.writeln('''
          }''');
            }
            output.writeln('''
337
          return $generatedClassPrefix${camelCase(scriptLocale)}($factoryArguments);
338 339 340 341
        }''');
            break;
          }
        }
342 343
      }
      output.writeln('''
344 345 346 347 348 349 350 351 352 353 354 355 356
      }''');
      if (hasCountryCode) {
      output.writeln('''
      switch (locale.countryCode) {''');
        for (LocaleInfo locale in languageToLocales[language]) {
          if (locale.originalString == language)
            continue;
          assert(locale.length > 1);
          if (locale.countryCode == null)
            continue;
          final String countryCode = locale.countryCode;
          output.writeln('''
        case '$countryCode':
357
          return $generatedClassPrefix${camelCase(locale)}($factoryArguments);''');
358 359 360
        }
        output.writeln('''
      }''');
361
      }
362
      output.writeln('''
363
      return $generatedClassPrefix${camelCase(LocaleInfo.fromString(language))}($factoryArguments);
364 365 366 367
    }''');
    }
  }
  output.writeln('''
368
  }
369
  assert(false, '$factoryName() called for unsupported locale "\$locale"');
370
  return null;
371
}''');
372 373 374 375

  return output.toString();
}

376 377 378 379 380 381 382
/// Returns the appropriate type for getters with the given attributes.
///
/// Typically "String", but some (e.g. "timeOfDayFormat") return enums.
///
/// Used by [generateGetter] below.
String generateType(Map<String, dynamic> attributes) {
  if (attributes != null) {
383
    switch (attributes['x-flutter-type'] as String) {
384 385
      case 'icuShortTimePattern':
        return 'TimeOfDayFormat';
386 387
      case 'scriptCategory':
        return 'ScriptCategory';
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    }
  }
  return 'String';
}

/// Returns the appropriate name for getters with the given attributes.
///
/// Typically this is the key unmodified, but some have parameters, and
/// the GlobalMaterialLocalizations class does the substitution, and for
/// those we have to therefore provide an alternate name.
///
/// Used by [generateGetter] below.
String generateKey(String key, Map<String, dynamic> attributes) {
  if (attributes != null) {
    if (attributes.containsKey('parameters'))
      return '${key}Raw';
404
    switch (attributes['x-flutter-type'] as String) {
405 406 407 408
      case 'icuShortTimePattern':
        return '${key}Raw';
    }
  }
409 410 411 412
  if (key == 'datePickerDateOrder')
    return 'datePickerDateOrderString';
  if (key == 'datePickerDateTimeOrder')
    return 'datePickerDateTimeOrderString';
413 414 415 416 417 418 419 420 421 422 423 424 425 426
  return key;
}

const Map<String, String> _icuTimeOfDayToEnum = <String, String>{
  'HH:mm': 'TimeOfDayFormat.HH_colon_mm',
  'HH.mm': 'TimeOfDayFormat.HH_dot_mm',
  "HH 'h' mm": 'TimeOfDayFormat.frenchCanadian',
  'HH:mm .': 'TimeOfDayFormat.HH_colon_mm',
  'H:mm': 'TimeOfDayFormat.H_colon_mm',
  'h:mm a': 'TimeOfDayFormat.h_colon_mm_space_a',
  'a h:mm': 'TimeOfDayFormat.a_space_h_colon_mm',
  'ah:mm': 'TimeOfDayFormat.a_space_h_colon_mm',
};

427 428 429 430 431 432
const Map<String, String> _scriptCategoryToEnum = <String, String>{
  'English-like': 'ScriptCategory.englishLike',
  'dense': 'ScriptCategory.dense',
  'tall': 'ScriptCategory.tall',
};

433 434 435 436 437 438 439 440
/// Returns the literal that describes the value returned by getters
/// with the given attributes.
///
/// This handles cases like the value being a literal `null`, an enum, and so
/// on. The default is to treat the value as a string and escape it and quote
/// it.
///
/// Used by [generateGetter] below.
441
String generateValue(String value, Map<String, dynamic> attributes, LocaleInfo locale) {
442 443
  if (value == null)
    return null;
444
  // cupertino_en.arb doesn't use x-flutter-type.
445
  if (attributes != null) {
446
    switch (attributes['x-flutter-type'] as String) {
447 448
      case 'icuShortTimePattern':
        if (!_icuTimeOfDayToEnum.containsKey(value)) {
449
          throw Exception(
450 451 452 453 454 455
            '"$value" is not one of the ICU short time patterns supported '
            'by the material library. Here is the list of supported '
            'patterns:\n  ' + _icuTimeOfDayToEnum.keys.join('\n  ')
          );
        }
        return _icuTimeOfDayToEnum[value];
456 457 458 459 460 461 462 463 464
      case 'scriptCategory':
        if (!_scriptCategoryToEnum.containsKey(value)) {
          throw Exception(
            '"$value" is not one of the scriptCategory values supported '
            'by the material library. Here is the list of supported '
            'values:\n  ' + _scriptCategoryToEnum.keys.join('\n  ')
          );
        }
        return _scriptCategoryToEnum[value];
465 466
    }
  }
467 468 469 470
  // Localization strings for the Kannada locale ('kn') are encoded because
  // some of the localized strings contain characters that can crash Emacs on Linux.
  // See packages/flutter_localizations/lib/src/l10n/README for more information.
  return locale.languageCode == 'kn' ? generateEncodedString(value) : generateString(value);
471 472 473 474
}

/// Combines [generateType], [generateKey], and [generateValue] to return
/// the source of getters for the GlobalMaterialLocalizations subclass.
475 476
/// The locale is the locale for which the getter is being generated.
String generateGetter(String key, String value, Map<String, dynamic> attributes, LocaleInfo locale) {
477 478
  final String type = generateType(attributes);
  key = generateKey(key, attributes);
479
  value = generateValue(value, attributes, locale);
480 481 482 483 484 485 486
      return '''

  @override
  $type get $key => $value;''';
}

Future<void> main(List<String> rawArgs) async {
487 488
  checkCwdIsRepoRoot('gen_localizations');
  final GeneratorOptions options = parseArgs(rawArgs);
489 490 491 492 493

  // filenames are assumed to end in "prefix_lc.arb" or "prefix_lc_cc.arb", where prefix
  // is the 2nd command line argument, lc is a language code and cc is the country
  // code. In most cases both codes are just two characters.

494
  final Directory directory = Directory(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'));
495
  final RegExp materialFilenameRE = RegExp(r'material_(\w+)\.arb$');
496
  final RegExp cupertinoFilenameRE = RegExp(r'cupertino_(\w+)\.arb$');
497

498
  try {
499
    validateEnglishLocalizations(File(path.join(directory.path, 'material_en.arb')));
500
    validateEnglishLocalizations(File(path.join(directory.path, 'cupertino_en.arb')));
501 502 503 504 505
  } on ValidationError catch (exception) {
    exitWithError('$exception');
  }

  await precacheLanguageAndRegionTags();
506

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
  // Maps of locales to resource key/value pairs for Material ARBs.
  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>>{};
  // Maps of locales to resource key/value pairs for Cupertino ARBs.
  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>>{};

  loadMatchingArbsIntoBundleMaps(
    directory: directory,
    filenamePattern: materialFilenameRE,
    localeToResources: materialLocaleToResources,
    localeToResourceAttributes: materialLocaleToResourceAttributes,
  );
  loadMatchingArbsIntoBundleMaps(
    directory: directory,
    filenamePattern: cupertinoFilenameRE,
    localeToResources: cupertinoLocaleToResources,
    localeToResourceAttributes: cupertinoLocaleToResourceAttributes,
  );
530

531
  try {
532 533
    validateLocalizations(materialLocaleToResources, materialLocaleToResourceAttributes);
    validateLocalizations(cupertinoLocaleToResources, cupertinoLocaleToResourceAttributes);
534 535 536
  } on ValidationError catch (exception) {
    exitWithError('$exception');
  }
537

538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
  final String materialLocalizations = options.writeToFile || !options.cupertinoOnly
      ? generateArbBasedLocalizationSubclasses(
        localeToResources: materialLocaleToResources,
        localeToResourceAttributes: materialLocaleToResourceAttributes,
        generatedClassPrefix: 'MaterialLocalization',
        baseClass: 'GlobalMaterialLocalizations',
        generateHeader: generateMaterialHeader,
        generateConstructor: generateMaterialConstructor,
        factoryName: materialFactoryName,
        factoryDeclaration: materialFactoryDeclaration,
        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,
        factoryArguments: cupertinoFactoryArguments,
        supportedLanguagesConstant: cupertinoSupportedLanguagesConstant,
        supportedLanguagesDocMacro: cupertinoSupportedLanguagesDocMacro,
      )
      : null;
568 569

  if (options.writeToFile) {
570 571 572 573
    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'));
    cupertinoLocalizationsFile.writeAsStringSync(cupertinoLocalizations, flush: true);
574
  } else {
575 576 577 578 579 580
    if (!options.cupertinoOnly) {
      stdout.write(materialLocalizations);
    }
    if (!options.materialOnly) {
      stdout.write(cupertinoLocalizations);
    }
581
  }
582
}