gen_l10n.dart 54.8 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
import 'package:meta/meta.dart';
6

7
import '../base/common.dart';
8 9 10
import '../base/file_system.dart';
import '../base/logger.dart';
import '../convert.dart';
11
import '../flutter_manifest.dart';
12

13 14
import 'gen_l10n_templates.dart';
import 'gen_l10n_types.dart';
15 16
import 'localizations_utils.dart';

17
/// Run the localizations generation script with the configuration [options].
18
LocalizationsGenerator generateLocalizations({
19 20 21 22 23
  required Directory projectDir,
  Directory? dependenciesDir,
  required LocalizationOptions options,
  required Logger logger,
  required FileSystem fileSystem,
24 25 26
}) {
  // If generating a synthetic package, generate a warning if
  // flutter: generate is not set.
27
  final FlutterManifest? flutterManifest = FlutterManifest.createFromPath(
28 29 30 31
    projectDir.childFile('pubspec.yaml').path,
    fileSystem: projectDir.fileSystem,
    logger: logger,
  );
32
  if (options.useSyntheticPackage && (flutterManifest == null || !flutterManifest.generateSyntheticPackage)) {
33
    throwToolExit(
34 35 36 37 38 39 40 41 42 43 44
      'Attempted to generate localizations code without having '
      'the flutter: generate flag turned on.'
      '\n'
      'Check pubspec.yaml and ensure that flutter: generate: true has '
      'been added and rebuild the project. Otherwise, the localizations '
      'source code will not be importable.'
    );
  }

  precacheLanguageAndRegionTags();

45 46 47
  final String inputPathString = options.arbDirectory?.path ?? fileSystem.path.join('lib', 'l10n');
  final String templateArbFileName = options.templateArbFile?.toFilePath() ?? 'app_en.arb';
  final String outputFileString = options.outputLocalizationsFile?.toFilePath() ?? 'app_localizations.dart';
48
  LocalizationsGenerator generator;
49
  try {
50 51 52 53 54 55 56
    generator = LocalizationsGenerator(
      fileSystem: fileSystem,
      inputsAndOutputsListPath: dependenciesDir?.path,
      projectPathString: projectDir.path,
      inputPathString: inputPathString,
      templateArbFileName: templateArbFileName,
      outputFileString: outputFileString,
57
      outputPathString: options.outputDirectory?.path,
58 59 60
      classNameString: options.outputClass ?? 'AppLocalizations',
      preferredSupportedLocales: options.preferredSupportedLocales,
      headerString: options.header,
61
      headerFile: options.headerFile?.toFilePath(),
62
      useDeferredLoading: options.deferredLoading ?? false,
63 64 65 66
      useSyntheticPackage: options.useSyntheticPackage,
      areResourceAttributesRequired: options.areResourceAttributesRequired,
      untranslatedMessagesFile: options.untranslatedMessagesFile?.toFilePath(),
      usesNullableGetter: options.usesNullableGetter,
67
    )
68 69 70
      ..loadResources()
      ..writeOutputFiles(logger, isFromYaml: true);
  } on L10nException catch (e) {
71
    throwToolExit(e.message);
72
  }
73
  return generator;
74 75
}

76
/// The path for the synthetic package.
77
String _defaultSyntheticPackagePath(FileSystem fileSystem) => fileSystem.path.join('.dart_tool', 'flutter_gen');
78 79

/// The default path used when the `_useSyntheticPackage` setting is set to true
80 81 82 83
/// in [LocalizationsGenerator].
///
/// See [LocalizationsGenerator.initialize] for where and how it is used by the
/// localizations tool.
84
String _syntheticL10nPackagePath(FileSystem fileSystem) => fileSystem.path.join(_defaultSyntheticPackagePath(fileSystem), 'gen_l10n');
85

86 87
List<String> generateMethodParameters(Message message) {
  assert(message.placeholders.isNotEmpty);
88
  final Placeholder? countPlaceholder = message.isPlural ? message.getCountPlaceholder() : null;
89
  return message.placeholders.map((Placeholder placeholder) {
90
    final String? type = placeholder == countPlaceholder ? 'num' : placeholder.type;
91
    return '$type ${placeholder.name}';
92 93 94
  }).toList();
}

95
String generateDateFormattingLogic(Message message) {
96
  if (message.placeholders.isEmpty || !message.placeholdersRequireFormatting) {
97
    return '@(none)';
98
  }
99

100 101 102
  final Iterable<String> formatStatements = message.placeholders
    .where((Placeholder placeholder) => placeholder.isDate)
    .map((Placeholder placeholder) {
103 104
      final String? placeholderFormat = placeholder.format;
      if (placeholderFormat == null) {
105 106 107 108 109
        throw L10nException(
          'The placeholder, ${placeholder.name}, has its "type" resource attribute set to '
          'the "${placeholder.type}" type. To properly resolve for the right '
          '${placeholder.type} format, the "format" attribute needs to be set '
          'to determine which DateFormat to use. \n'
110
          "Check the intl library's DateFormat class constructors for allowed "
111 112 113
          'date formats.'
        );
      }
114 115 116
      final bool? isCustomDateFormat = placeholder.isCustomDateFormat;
      if (!placeholder.hasValidDateFormat
          && (isCustomDateFormat == null || !isCustomDateFormat)) {
117
        throw L10nException(
118
          'Date format "$placeholderFormat" for placeholder '
119
          '${placeholder.name} does not have a corresponding DateFormat '
120
          "constructor\n. Check the intl library's DateFormat class "
121 122
          'constructors for allowed date formats, or set "isCustomDateFormat" attribute '
          'to "true".'
123 124
        );
      }
125 126 127 128 129 130
      if (placeholder.hasValidDateFormat) {
        return dateFormatTemplate
          .replaceAll('@(placeholder)', placeholder.name)
          .replaceAll('@(format)', placeholderFormat);
      }
      return dateFormatCustomTemplate
131
        .replaceAll('@(placeholder)', placeholder.name)
132
        .replaceAll('@(format)', generateString(placeholderFormat));
133
    });
134

135
  return formatStatements.isEmpty ? '@(none)' : formatStatements.join();
136 137
}

138 139 140
String generateNumberFormattingLogic(Message message) {
  if (message.placeholders.isEmpty || !message.placeholdersRequireFormatting) {
    return '@(none)';
141
  }
142

143 144 145
  final Iterable<String> formatStatements = message.placeholders
    .where((Placeholder placeholder) => placeholder.isNumber)
    .map((Placeholder placeholder) {
146 147
      final String? placeholderFormat = placeholder.format;
      if (!placeholder.hasValidNumberFormat || placeholderFormat == null) {
148
        throw L10nException(
149
          'Number format $placeholderFormat for the ${placeholder.name} '
150
          'placeholder does not have a corresponding NumberFormat constructor.\n'
151
          "Check the intl library's NumberFormat class constructors for allowed "
152 153 154 155 156
          'number formats.'
        );
      }
      final Iterable<String> parameters =
        placeholder.optionalParameters.map<String>((OptionalParameter parameter) {
157 158 159 160 161
          if (parameter.value is num) {
            return '${parameter.name}: ${parameter.value}';
          } else {
            return '${parameter.name}: ${generateString(parameter.value.toString())}';
          }
162 163
        },
      );
164 165 166 167

      if (placeholder.hasNumberFormatWithParameters) {
        return numberFormatNamedTemplate
            .replaceAll('@(placeholder)', placeholder.name)
168
            .replaceAll('@(format)', placeholderFormat)
169 170 171 172
            .replaceAll('@(parameters)', parameters.join(',\n      '));
      } else {
        return numberFormatPositionalTemplate
            .replaceAll('@(placeholder)', placeholder.name)
173
            .replaceAll('@(format)', placeholderFormat);
174
      }
175
    });
176

177
  return formatStatements.isEmpty ? '@(none)' : formatStatements.join();
178 179
}

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
/// To make it easier to parse plurals or select messages, temporarily replace
/// each "{placeholder}" parameter with "#placeholder#" for example.
String _replacePlaceholdersBraces(
  String translationForMessage,
  Iterable<Placeholder> placeholders,
  String replacementBraces,
) {
  assert(replacementBraces.length == 2);
  String easyMessage = translationForMessage;
  for (final Placeholder placeholder in placeholders) {
    easyMessage = easyMessage.replaceAll(
      '{${placeholder.name}}',
      '${replacementBraces[0]}${placeholder.name}${replacementBraces[1]}',
    );
  }
  return easyMessage;
}

/// Replaces message with the interpolated variable name of the given placeholders
/// with the ability to change braces to something other than {...}.
///
/// Examples:
///
/// * Replacing `{userName}`.
/// ```dart
/// final message = 'Hello my name is {userName}';
/// final transformed = _replacePlaceholdersWithVariables(message, placeholders);
/// // transformed == 'Hello my name is $userName'
/// ```
/// * Replacing `#choice#`.
/// ```dart
/// final message = 'I would like to have some #choice#';
/// final transformed = _replacePlaceholdersWithVariables(message, placeholders, '##');
/// transformed == 'I would like to have some $choice'
/// ```
String _replacePlaceholdersWithVariables(String message, Iterable<Placeholder> placeholders, [String braces = '{}']) {
  assert(braces.length == 2);
  String messageWithValues = message;
  for (final Placeholder placeholder in placeholders) {
    String variable = placeholder.name;
    if (placeholder.requiresFormatting) {
      variable += 'String';
    }
    messageWithValues = messageWithValues.replaceAll(
      '${braces[0]}${placeholder.name}${braces[1]}',
      _needsCurlyBracketStringInterpolation(messageWithValues, placeholder.name)
        ? '\${$variable}'
        : '\$$variable'
    );
  }
  return messageWithValues;
}

233
String _generatePluralMethod(Message message, String translationForMessage) {
234
  if (message.placeholders.isEmpty) {
235
    throw L10nException(
236
      'Unable to find placeholders for the plural message: ${message.resourceId}.\n'
237 238 239
      'Check to see if the plural message is in the proper ICU syntax format '
      'and ensure that placeholders are properly specified.'
    );
240
  }
241

242
  final String easyMessage = _replacePlaceholdersBraces(translationForMessage, message.placeholders, '##');
243

244
  final Placeholder countPlaceholder = message.getCountPlaceholder();
245 246 247 248 249 250
  const Map<String, String> pluralIds = <String, String>{
    '=0': 'zero',
    '=1': 'one',
    '=2': 'two',
    'few': 'few',
    'many': 'many',
251
    'other': 'other',
252
  };
253

254
  final List<String> pluralLogicArgs = <String>[];
255
  for (final String pluralKey in pluralIds.keys) {
256
    final RegExp expRE = RegExp('($pluralKey)\\s*{([^}]+)}');
257
    final RegExpMatch? match = expRE.firstMatch(easyMessage);
258
    if (match != null && match.groupCount == 2) {
259
      final String argValue = _replacePlaceholdersWithVariables(generateString(match.group(2)!), message.placeholders, '##');
260
      pluralLogicArgs.add('      ${pluralIds[pluralKey]}: $argValue');
261 262 263 264
    }
  }

  final List<String> parameters = message.placeholders.map((Placeholder placeholder) {
265
    final String? placeholderType = placeholder == countPlaceholder ? 'num' : placeholder.type;
266 267 268 269 270
    return '$placeholderType ${placeholder.name}';
  }).toList();

  final String comment = message.description ?? 'No description provided in @${message.resourceId}';

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
  if (translationForMessage.startsWith('{') && translationForMessage.endsWith('}')) {
    return pluralMethodTemplate
      .replaceAll('@(comment)', comment)
      .replaceAll('@(name)', message.resourceId)
      .replaceAll('@(dateFormatting)', generateDateFormattingLogic(message))
      .replaceAll('@(numberFormatting)', generateNumberFormattingLogic(message))
      .replaceAll('@(parameters)', parameters.join(', '))
      .replaceAll('@(count)', countPlaceholder.name)
      .replaceAll('@(pluralLogicArgs)', pluralLogicArgs.join(',\n'))
      .replaceAll('@(none)\n', '');
  }

  const String variable = 'pluralString';
  final String string = _replaceWithVariable(translationForMessage, variable);
  return pluralMethodTemplateInString
286 287 288 289
    .replaceAll('@(comment)', comment)
    .replaceAll('@(name)', message.resourceId)
    .replaceAll('@(dateFormatting)', generateDateFormattingLogic(message))
    .replaceAll('@(numberFormatting)', generateNumberFormattingLogic(message))
290 291
    .replaceAll('@(parameters)', parameters.join(', '))
    .replaceAll('@(variable)', variable)
292 293
    .replaceAll('@(count)', countPlaceholder.name)
    .replaceAll('@(pluralLogicArgs)', pluralLogicArgs.join(',\n'))
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    .replaceAll('@(none)\n', '')
    .replaceAll('@(string)', string);
}

String _replaceWithVariable(String translation, String variable) {
  String prefix = generateString(translation.substring(0, translation.indexOf('{')));
  prefix = prefix.substring(0, prefix.length - 1);
  String suffix = generateString(translation.substring(translation.lastIndexOf('}') + 1));
  suffix = suffix.substring(1);

  // escape variable when the suffix can be combined with the variable
  if (suffix.isNotEmpty && !suffix.startsWith(' ')) {
    variable = '{$variable}';
  }
  return prefix + r'$' + variable + suffix;
}

String _generateSelectMethod(Message message, String translationForMessage) {
  if (message.placeholders.isEmpty) {
    throw L10nException(
      'Unable to find placeholders for the select message: ${message.resourceId}.\n'
      'Check to see if the select message is in the proper ICU syntax format '
      'and ensure that placeholders are properly specified.'
    );
  }

320 321
  final String easyMessage = _replacePlaceholdersBraces(translationForMessage, message.placeholders, '##');

322 323
  final List<String> cases = <String>[];

324
  final RegExpMatch? selectMatch = LocalizationsGenerator._selectRE.firstMatch(easyMessage);
325 326 327 328 329 330 331
  String? choice;
  if (selectMatch != null && selectMatch.groupCount == 2) {
    choice = selectMatch.group(1);
    final String pattern = selectMatch.group(2)!;
    final RegExp patternRE = RegExp(r'\s*([\w\d]+)\s*\{(.*?)\}');
    for (final RegExpMatch patternMatch in patternRE.allMatches(pattern)) {
      if (patternMatch.groupCount == 2) {
332
        String value = patternMatch.group(2)!
333 334
          .replaceAll("'", r"\'")
          .replaceAll('"', r'\"');
335
        value = _replacePlaceholdersWithVariables(value, message.placeholders, '##');
336 337 338 339 340
        cases.add(
          "        '${patternMatch.group(1)}': '$value'",
        );
      }
    }
341 342 343 344 345
  } else {
    throw L10nException(
      'Incorrect select message format for: ${message.resourceId}.\n'
      'Check to see if the select message is in the proper ICU syntax format.'
    );
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
  }

  final List<String> parameters = message.placeholders.map((Placeholder placeholder) {
    final String placeholderType = placeholder.type ?? 'object';
    return '$placeholderType ${placeholder.name}';
  }).toList();

  final String description = message.description ?? 'No description provided in @${message.resourceId}';

  if (translationForMessage.startsWith('{') && translationForMessage.endsWith('}')) {
    return selectMethodTemplate
        .replaceAll('@(name)', message.resourceId)
        .replaceAll('@(parameters)', parameters.join(', '))
        .replaceAll('@(choice)', choice!)
        .replaceAll('@(cases)', cases.join(',\n').trim())
        .replaceAll('@(description)', description);
  }

  const String variable = 'selectString';
  final String string = _replaceWithVariable(translationForMessage, variable);
  return selectMethodTemplateInString
      .replaceAll('@(name)', message.resourceId)
      .replaceAll('@(parameters)', parameters.join(', '))
      .replaceAll('@(variable)', variable)
      .replaceAll('@(choice)', choice!)
      .replaceAll('@(cases)', cases.join(',\n').trim())
      .replaceAll('@(description)', description)
      .replaceAll('@(string)', string);
374 375
}

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
bool _needsCurlyBracketStringInterpolation(String messageString, String placeholder) {
  final int placeholderIndex = messageString.indexOf(placeholder);
  // This means that this message does not contain placeholders/parameters,
  // since one was not found in the message.
  if (placeholderIndex == -1) {
    return false;
  }

  final bool isPlaceholderEndOfSubstring = placeholderIndex + placeholder.length + 2 == messageString.length;

  if (placeholderIndex > 2 && !isPlaceholderEndOfSubstring) {
    // Normal case
    // Examples:
    // "'The number of {hours} elapsed is: 44'" // no curly brackets.
    // "'哈{hours}哈'" // no curly brackets.
    // "'m#hours#m'" // curly brackets.
    // "'I have to work _#hours#_' sometimes." // curly brackets.
    final RegExp commonCaseRE = RegExp('[^a-zA-Z_][#{]$placeholder[#}][^a-zA-Z_]');
    return !commonCaseRE.hasMatch(messageString);
  } else if (placeholderIndex == 2) {
    // Example:
    // "'{hours} elapsed.'" // no curly brackets
    // '#placeholder# ' // no curly brackets
    // '#placeholder#m' // curly brackets
    final RegExp startOfString = RegExp('[#{]$placeholder[#}][^a-zA-Z_]');
    return !startOfString.hasMatch(messageString);
  } else {
    // Example:
    // "'hours elapsed: {hours}'"
    // "'Time elapsed: {hours}'" // no curly brackets
    // ' #placeholder#' // no curly brackets
    // 'm#placeholder#' // curly brackets
    final RegExp endOfString = RegExp('[^a-zA-Z_][#{]$placeholder[#}]');
    return !endOfString.hasMatch(messageString);
  }
}

413
String _generateMethod(Message message, String translationForMessage) {
414
  String generateMessage() {
415
    return _replacePlaceholdersWithVariables(generateString(translationForMessage), message.placeholders);
416 417
  }

418
  if (message.isPlural) {
419
    return _generatePluralMethod(message, translationForMessage);
420 421
  }

422 423 424 425
  if (message.isSelect) {
    return _generateSelectMethod(message, translationForMessage);
  }

426
  if (message.placeholdersRequireFormatting) {
427 428 429
    return formatMethodTemplate
      .replaceAll('@(name)', message.resourceId)
      .replaceAll('@(parameters)', generateMethodParameters(message).join(', '))
430 431
      .replaceAll('@(dateFormatting)', generateDateFormattingLogic(message))
      .replaceAll('@(numberFormatting)', generateNumberFormattingLogic(message))
432 433
      .replaceAll('@(message)', generateMessage())
      .replaceAll('@(none)\n', '');
434
  }
435

436 437 438 439 440 441 442 443 444 445 446 447
  if (message.placeholders.isNotEmpty) {
    return methodTemplate
      .replaceAll('@(name)', message.resourceId)
      .replaceAll('@(parameters)', generateMethodParameters(message).join(', '))
      .replaceAll('@(message)', generateMessage());
  }

  return getterTemplate
    .replaceAll('@(name)', message.resourceId)
    .replaceAll('@(message)', generateMessage());
}

448
String generateBaseClassMethod(Message message, LocaleInfo? templateArbLocale) {
449 450 451 452 453
  final String comment = message.description ?? 'No description provided for @${message.resourceId}.';
  final String templateLocaleTranslationComment = '''
  /// In $templateArbLocale, this message translates to:
  /// **${generateString(message.value)}**''';

454 455 456
  if (message.placeholders.isNotEmpty) {
    return baseClassMethodTemplate
      .replaceAll('@(comment)', comment)
457
      .replaceAll('@(templateLocaleTranslationComment)', templateLocaleTranslationComment)
458 459 460 461 462
      .replaceAll('@(name)', message.resourceId)
      .replaceAll('@(parameters)', generateMethodParameters(message).join(', '));
  }
  return baseClassGetterTemplate
    .replaceAll('@(comment)', comment)
463
    .replaceAll('@(templateLocaleTranslationComment)', templateLocaleTranslationComment)
464 465 466
    .replaceAll('@(name)', message.resourceId);
}

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
// Add spaces to pad the start of each line. Skips the first line
// assuming that the padding is already present.
String _addSpaces(String message, {int spaces = 0}) {
  bool isFirstLine = true;
  return message
    .split('\n')
    .map((String value) {
      if (isFirstLine) {
        isFirstLine = false;
        return value;
      }
      return value.padLeft(spaces);
    })
    .join('\n');
}

483 484 485 486
String _generateLookupByAllCodes(
  AppResourceBundleCollection allBundles,
  String Function(LocaleInfo) generateSwitchClauseTemplate,
) {
487 488 489 490 491 492 493 494 495
  final Iterable<LocaleInfo> localesWithAllCodes = allBundles.locales.where((LocaleInfo locale) {
    return locale.scriptCode != null && locale.countryCode != null;
  });

  if (localesWithAllCodes.isEmpty) {
    return '';
  }

  final Iterable<String> switchClauses = localesWithAllCodes.map<String>((LocaleInfo locale) {
496 497
    return generateSwitchClauseTemplate(locale)
      .replaceAll('@(case)', locale.toString());
498 499 500 501
  });

  return allCodesLookupTemplate.replaceAll(
    '@(allCodesSwitchClauses)',
502
    switchClauses.join('\n        '),
503 504 505
  );
}

506 507 508 509
String _generateLookupByScriptCode(
  AppResourceBundleCollection allBundles,
  String Function(LocaleInfo) generateSwitchClauseTemplate,
) {
510 511
  final Iterable<String> switchClauses = allBundles.languages.map((String language) {
    final Iterable<LocaleInfo> locales = allBundles.localesForLanguage(language);
512 513 514 515
    final Iterable<LocaleInfo> localesWithScriptCodes = locales.where((LocaleInfo locale) {
      return locale.scriptCode != null && locale.countryCode == null;
    });

516
    if (localesWithScriptCodes.isEmpty) {
517
      return null;
518
    }
519

520
    return _addSpaces(nestedSwitchTemplate
521
      .replaceAll('@(languageCode)', language)
522
      .replaceAll('@(code)', 'scriptCode')
523 524 525 526 527 528 529 530 531 532 533
      .replaceAll('@(switchClauses)',
        _addSpaces(
          localesWithScriptCodes.map((LocaleInfo locale) {
            return generateSwitchClauseTemplate(locale)
              .replaceAll('@(case)', locale.scriptCode!);
          }).join('\n'),
          spaces: 8,
        ),
      ),
      spaces: 4,
    );
534
  }).whereType<String>();
535 536 537 538 539 540 541

  if (switchClauses.isEmpty) {
    return '';
  }

  return languageCodeSwitchTemplate
    .replaceAll('@(comment)', '// Lookup logic when language+script codes are specified.')
542
    .replaceAll('@(switchClauses)', switchClauses.join('\n      '),
543 544 545
  );
}

546 547 548 549
String _generateLookupByCountryCode(
  AppResourceBundleCollection allBundles,
  String Function(LocaleInfo) generateSwitchClauseTemplate,
) {
550 551 552 553 554 555
  final Iterable<String> switchClauses = allBundles.languages.map((String language) {
    final Iterable<LocaleInfo> locales = allBundles.localesForLanguage(language);
    final Iterable<LocaleInfo> localesWithCountryCodes = locales.where((LocaleInfo locale) {
      return locale.countryCode != null && locale.scriptCode == null;
    });

556
    if (localesWithCountryCodes.isEmpty) {
557
      return null;
558
    }
559

560 561 562 563 564 565 566 567 568 569 570 571
    return _addSpaces(
      nestedSwitchTemplate
        .replaceAll('@(languageCode)', language)
        .replaceAll('@(code)', 'countryCode')
        .replaceAll('@(switchClauses)', _addSpaces(
          localesWithCountryCodes.map((LocaleInfo locale) {
            return generateSwitchClauseTemplate(locale).replaceAll('@(case)', locale.countryCode!);
          }).join('\n'),
          spaces: 4,
        )),
      spaces: 4,
    );
572
  }).whereType<String>();
573 574 575 576 577 578 579 580 581 582

  if (switchClauses.isEmpty) {
    return '';
  }

  return languageCodeSwitchTemplate
    .replaceAll('@(comment)', '// Lookup logic when language+country codes are specified.')
    .replaceAll('@(switchClauses)', switchClauses.join('\n    '));
}

583 584 585 586
String _generateLookupByLanguageCode(
  AppResourceBundleCollection allBundles,
  String Function(LocaleInfo) generateSwitchClauseTemplate,
) {
587 588 589 590 591 592
  final Iterable<String> switchClauses = allBundles.languages.map((String language) {
    final Iterable<LocaleInfo> locales = allBundles.localesForLanguage(language);
    final Iterable<LocaleInfo> localesWithLanguageCode = locales.where((LocaleInfo locale) {
      return locale.countryCode == null && locale.scriptCode == null;
    });

593
    if (localesWithLanguageCode.isEmpty) {
594
      return null;
595
    }
596 597

    return localesWithLanguageCode.map((LocaleInfo locale) {
598 599
      return generateSwitchClauseTemplate(locale)
        .replaceAll('@(case)', locale.languageCode);
600
    }).join('\n      ');
601
  }).whereType<String>();
602 603 604 605 606 607 608 609 610 611

  if (switchClauses.isEmpty) {
    return '';
  }

  return languageCodeSwitchTemplate
    .replaceAll('@(comment)', '// Lookup logic when only language code is specified.')
    .replaceAll('@(switchClauses)', switchClauses.join('\n    '));
}

612 613 614 615 616 617
String _generateLookupBody(
  AppResourceBundleCollection allBundles,
  String className,
  bool useDeferredLoading,
  String fileName,
) {
618
  String generateSwitchClauseTemplate(LocaleInfo locale) {
619 620 621 622 623
    return (useDeferredLoading ?
      switchClauseDeferredLoadingTemplate : switchClauseTemplate)
      .replaceAll('@(localeClass)', '$className${locale.camelCase()}')
      .replaceAll('@(appClass)', className)
      .replaceAll('@(library)', '${fileName}_${locale.languageCode}');
624
  }
625
  return lookupBodyTemplate
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
    .replaceAll('@(lookupAllCodesSpecified)', _generateLookupByAllCodes(
      allBundles,
      generateSwitchClauseTemplate,
    ))
    .replaceAll('@(lookupScriptCodeSpecified)', _generateLookupByScriptCode(
      allBundles,
      generateSwitchClauseTemplate,
    ))
    .replaceAll('@(lookupCountryCodeSpecified)', _generateLookupByCountryCode(
      allBundles,
      generateSwitchClauseTemplate,
    ))
    .replaceAll('@(lookupLanguageCodeSpecified)', _generateLookupByLanguageCode(
      allBundles,
      generateSwitchClauseTemplate,
    ));
}

String _generateDelegateClass({
645 646 647 648 649
  required AppResourceBundleCollection allBundles,
  required String className,
  required Set<String> supportedLanguageCodes,
  required bool useDeferredLoading,
  required String fileName,
650 651 652 653 654 655 656 657 658 659 660 661
}) {

  final String lookupBody = _generateLookupBody(
    allBundles,
    className,
    useDeferredLoading,
    fileName,
  );
  final String loadBody = (
    useDeferredLoading ? loadBodyDeferredLoadingTemplate : loadBodyTemplate
  )
    .replaceAll('@(class)', className)
662
    .replaceAll('@(lookupName)', 'lookup$className');
663 664 665
  final String lookupFunction = (useDeferredLoading ?
  lookupFunctionDeferredLoadingTemplate : lookupFunctionTemplate)
    .replaceAll('@(class)', className)
666
    .replaceAll('@(lookupName)', 'lookup$className')
667 668 669 670 671 672
    .replaceAll('@(lookupBody)', lookupBody);
  return delegateClassTemplate
    .replaceAll('@(class)', className)
    .replaceAll('@(loadBody)', loadBody)
    .replaceAll('@(supportedLanguageCodes)', supportedLanguageCodes.join(', '))
    .replaceAll('@(lookupFunction)', lookupFunction);
673 674
}

675
class LocalizationsGenerator {
676 677 678 679 680 681 682 683 684
  /// Initializes [inputDirectory], [outputDirectory], [templateArbFile],
  /// [outputFile] and [className].
  ///
  /// Throws an [L10nException] when a provided configuration is not allowed
  /// by [LocalizationsGenerator].
  ///
  /// Throws a [FileSystemException] when a file operation necessary for setting
  /// up the [LocalizationsGenerator] cannot be completed.
  factory LocalizationsGenerator({
685 686 687 688 689 690 691 692 693
    required FileSystem fileSystem,
    required String inputPathString,
    String? outputPathString,
    required String templateArbFileName,
    required String outputFileString,
    required String classNameString,
    List<String>? preferredSupportedLocales,
    String? headerString,
    String? headerFile,
694
    bool useDeferredLoading = false,
695
    String? inputsAndOutputsListPath,
696
    bool useSyntheticPackage = true,
697
    String? projectPathString,
698
    bool areResourceAttributesRequired = false,
699
    String? untranslatedMessagesFile,
700 701
    bool usesNullableGetter = true,
  }) {
702
    final Directory? projectDirectory = projectDirFromPath(fileSystem, projectPathString);
703 704 705 706 707 708 709 710 711 712 713 714 715 716
    final Directory inputDirectory = inputDirectoryFromPath(fileSystem, inputPathString, projectDirectory);
    final Directory outputDirectory = outputDirectoryFromPath(fileSystem, outputPathString ?? inputPathString, useSyntheticPackage, projectDirectory);
    return LocalizationsGenerator._(
      fileSystem,
      useSyntheticPackage: useSyntheticPackage,
      usesNullableGetter: usesNullableGetter,
      className: classNameFromString(classNameString),
      projectDirectory: projectDirectory,
      inputDirectory: inputDirectory,
      outputDirectory: outputDirectory,
      templateArbFile: templateArbFileFromFileName(templateArbFileName, inputDirectory),
      baseOutputFile: outputDirectory.childFile(outputFileString),
      preferredSupportedLocales: preferredSupportedLocalesFromLocales(preferredSupportedLocales),
      header: headerFromFile(headerString, headerFile, inputDirectory),
717
      useDeferredLoading: useDeferredLoading,
718 719 720 721 722 723
      untranslatedMessagesFile: _untranslatedMessagesFileFromPath(fileSystem, untranslatedMessagesFile),
      inputsAndOutputsListFile: _inputsAndOutputsListFileFromPath(fileSystem, inputsAndOutputsListPath),
      areResourceAttributesRequired: areResourceAttributesRequired,
    );
  }

724 725 726
  /// Creates an instance of the localizations generator class.
  ///
  /// It takes in a [FileSystem] representation that the class will act upon.
727 728 729 730 731 732
  LocalizationsGenerator._(this._fs, {
    required this.inputDirectory,
    required this.outputDirectory,
    required this.templateArbFile,
    required this.baseOutputFile,
    required this.className,
733 734 735
    this.preferredSupportedLocales = const <LocaleInfo>[],
    this.header = '',
    this.useDeferredLoading = false,
736
    required this.inputsAndOutputsListFile,
737 738 739 740 741 742
    this.useSyntheticPackage = true,
    this.projectDirectory,
    this.areResourceAttributesRequired = false,
    this.untranslatedMessagesFile,
    this.usesNullableGetter = true,
  });
743

744
  final FileSystem _fs;
745 746 747 748 749
  Iterable<Message> _allMessages = <Message>[];
  late final AppResourceBundleCollection _allBundles = AppResourceBundleCollection(inputDirectory);

  late final AppResourceBundle _templateBundle = AppResourceBundle(templateArbFile);
  late final LocaleInfo _templateArbLocale = _templateBundle.locale;
750 751 752 753

  @visibleForTesting
  final bool useSyntheticPackage;

754 755 756
  // Used to decide if the generated code is nullable or not
  // (whether AppLocalizations? or AppLocalizations is returned from
  // `static {name}Localizations{?} of (BuildContext context))`
757 758
  @visibleForTesting
  final bool usesNullableGetter;
759

760 761
  /// The directory that contains the project's arb files, as well as the
  /// header file, if specified.
762 763
  ///
  /// It is assumed that all input files (e.g. [templateArbFile], arb files
764
  /// for translated messages, header file templates) will reside here.
765
  final Directory inputDirectory;
766

767
  /// The Flutter project's root directory.
768
  final Directory? projectDirectory;
769

770 771 772
  /// The directory to generate the project's localizations files in.
  ///
  /// It is assumed that all output files (e.g. The localizations
773 774
  /// [outputFile], `messages_<locale>.dart` and `messages_all.dart`)
  /// will reside here.
775
  final Directory outputDirectory;
776

777 778
  /// The input arb file which defines all of the messages that will be
  /// exported by the generated class that's written to [outputFile].
779
  final File templateArbFile;
780

781 782 783 784
  /// The file to write the generated abstract localizations and
  /// localizations delegate classes to. Separate localizations
  /// files will also be generated for each language using this
  /// filename as a prefix and the locale as the suffix.
785
  final File baseOutputFile;
786 787 788 789 790

  /// The class name to be used for the localizations class in [outputFile].
  ///
  /// For example, if 'AppLocalizations' is passed in, a class named
  /// AppLocalizations will be used for localized message lookups.
791
  final String className;
792 793 794 795 796 797 798 799 800 801 802

  /// The list of preferred supported locales.
  ///
  /// By default, the list of supported locales in the localizations class
  /// will be sorted in alphabetical order. However, this option
  /// allows for a set of preferred locales to appear at the top of the
  /// list.
  ///
  /// The order of locales in this list will also be the order of locale
  /// priority. For example, if a device supports 'en' and 'es' and
  /// ['es', 'en'] is passed in, the 'es' locale will take priority over 'en'.
803
  final List<LocaleInfo> preferredSupportedLocales;
804

805
  /// The list of all arb path strings in [inputDirectory].
806 807 808
  List<String> get arbPathStrings {
    return _allBundles.bundles.map((AppResourceBundle bundle) => bundle.file.path).toList();
  }
809 810

  /// The supported language codes as found in the arb files located in
811
  /// [inputDirectory].
812
  final Set<String> supportedLanguageCodes = <String>{};
813 814

  /// The supported locales as found in the arb files located in
815
  /// [inputDirectory].
816 817
  final Set<LocaleInfo> supportedLocales = <LocaleInfo>{};

818
  /// The header to be prepended to the generated Dart localization file.
819
  final String header;
820

821 822
  final Map<LocaleInfo, List<String>> _unimplementedMessages = <LocaleInfo, List<String>>{};

823 824 825 826 827 828 829 830 831 832 833 834 835 836
  /// Whether to generate the Dart localization file with locales imported as
  /// deferred, allowing for lazy loading of each locale in Flutter web.
  ///
  /// This can reduce a web app’s initial startup time by decreasing the size of
  /// the JavaScript bundle. When [_useDeferredLoading] 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.
  ///
  /// Note that this flag does not affect other platforms such as mobile or
  /// desktop.
837
  final bool useDeferredLoading;
838

839 840 841 842
  /// Contains a map of each output language file to its corresponding content in
  /// string format.
  final Map<File, String> _languageFileMap = <File, String>{};

843 844
  /// A generated file that will contain the list of messages for each locale
  /// that do not have a translation yet.
845
  @visibleForTesting
846
  final File? untranslatedMessagesFile;
847

848 849
  /// The file that contains the list of inputs and outputs for generating
  /// localizations.
850
  @visibleForTesting
851
  final File? inputsAndOutputsListFile;
852 853
  final List<String> _inputFileList = <String>[];
  final List<String> _outputFileList = <String>[];
854

855 856 857 858
  /// Whether or not resource attributes are required for each corresponding
  /// resource id.
  ///
  /// Resource attributes provide metadata about the message.
859 860
  @visibleForTesting
  final bool areResourceAttributesRequired;
861

862 863
  static final RegExp _selectRE = RegExp(r'\{([\w\s,]*),\s*select\s*,\s*([\w\d]+\s*\{.*\})+\s*\}');

864 865 866 867 868 869 870 871 872 873 874 875 876 877
  static bool _isNotReadable(FileStat fileStat) {
    final String rawStatString = fileStat.modeString();
    // Removes potential prepended permission bits, such as '(suid)' and '(guid)'.
    final String statString = rawStatString.substring(rawStatString.length - 9);
    return !(statString[0] == 'r' || statString[3] == 'r' || statString[6] == 'r');
  }

  static bool _isNotWritable(FileStat fileStat) {
    final String rawStatString = fileStat.modeString();
    // Removes potential prepended permission bits, such as '(suid)' and '(guid)'.
    final String statString = rawStatString.substring(rawStatString.length - 9);
    return !(statString[1] == 'w' || statString[4] == 'w' || statString[7] == 'w');
  }

878
  @visibleForTesting
879
  static Directory? projectDirFromPath(FileSystem fileSystem, String? projectPathString) {
880
    if (projectPathString == null) {
881
      return null;
882 883
    }

884
    final Directory directory = fileSystem.directory(projectPathString);
885 886 887
    if (!directory.existsSync()) {
      throw L10nException(
        'Directory does not exist: $directory.\n'
888
        "Please select a directory that contains the project's localizations "
889 890 891
        'resource files.'
      );
    }
892
    return directory;
893 894
  }

895
  /// Sets the reference [Directory] for [inputDirectory].
896
  @visibleForTesting
897
  static Directory inputDirectoryFromPath(FileSystem fileSystem, String inputPathString, Directory? projectDirectory) {
898
    final Directory inputDirectory = fileSystem.directory(
899
      projectDirectory != null
900
        ? _getAbsoluteProjectPath(inputPathString, projectDirectory)
901 902 903
        : inputPathString
    );

904 905
    if (!inputDirectory.existsSync()) {
      throw L10nException(
906
        "The 'arb-dir' directory, '$inputDirectory', does not exist.\n"
907 908
        'Make sure that the correct path was provided.'
      );
909
    }
910

911
    final FileStat fileStat = inputDirectory.statSync();
912 913
    if (_isNotReadable(fileStat) || _isNotWritable(fileStat)) {
      throw L10nException(
914
        "The 'arb-dir' directory, '$inputDirectory', doesn't allow reading and writing.\n"
915 916
        'Please ensure that the user has read and write permissions.'
      );
917
    }
918
    return inputDirectory;
919 920
  }

921 922
  /// Sets the reference [Directory] for [outputDirectory].
  @visibleForTesting
923
  static Directory outputDirectoryFromPath(FileSystem fileSystem, String outputPathString, bool useSyntheticPackage, Directory? projectDirectory) {
924 925 926
    Directory outputDirectory;
    if (useSyntheticPackage) {
      outputDirectory = fileSystem.directory(
927
        projectDirectory != null
928 929
          ? _getAbsoluteProjectPath(_syntheticL10nPackagePath(fileSystem), projectDirectory)
          : _syntheticL10nPackagePath(fileSystem)
930 931
      );
    } else {
932
      outputDirectory = fileSystem.directory(
933
        projectDirectory != null
934
          ? _getAbsoluteProjectPath(outputPathString, projectDirectory)
935 936 937
          : outputPathString
      );
    }
938
    return outputDirectory;
939 940
  }

941 942
  /// Sets the reference [File] for [templateArbFile].
  @visibleForTesting
943 944
  static File templateArbFileFromFileName(String templateArbFileName, Directory inputDirectory) {
    final File templateArbFile = inputDirectory.childFile(templateArbFileName);
945
    final String templateArbFileStatModeString = templateArbFile.statSync().modeString();
946 947
    if (templateArbFileStatModeString[0] == '-' && templateArbFileStatModeString[3] == '-') {
      throw L10nException(
948 949 950
        "The 'template-arb-file', $templateArbFile, is not readable.\n"
        'Please ensure that the user has read permissions.'
      );
951
    }
952
    return templateArbFile;
953 954
  }

955 956
  static bool _isValidClassName(String className) {
    // Public Dart class name cannot begin with an underscore
957
    if (className[0] == '_') {
958
      return false;
959
    }
960
    // Dart class name cannot contain non-alphanumeric symbols
961
    if (className.contains(RegExp(r'[^a-zA-Z_\d]'))) {
962
      return false;
963
    }
964
    // Dart class name must start with upper case character
965
    if (className[0].contains(RegExp(r'[a-z]'))) {
966
      return false;
967
    }
968
    // Dart class name cannot start with a number
969
    if (className[0].contains(RegExp(r'\d'))) {
970
      return false;
971
    }
972 973 974
    return true;
  }

975 976
  /// Sets the [className] for the localizations and localizations delegate
  /// classes.
977
  @visibleForTesting
978
  static String classNameFromString(String classNameString) {
979 980
    if (classNameString.isEmpty) {
      throw L10nException('classNameString argument cannot be empty');
981 982
    }
    if (!_isValidClassName(classNameString)) {
983
      throw L10nException(
984
        "The 'output-class', $classNameString, is not a valid public Dart class name.\n"
985
      );
986
    }
987
    return classNameString;
988 989
  }

990 991 992
  /// Sets [preferredSupportedLocales] so that this particular list of locales
  /// will take priority over the other locales.
  @visibleForTesting
993
  static List<LocaleInfo> preferredSupportedLocalesFromLocales(List<String>? inputLocales) {
994
    if (inputLocales == null || inputLocales.isEmpty) {
995
      return const <LocaleInfo>[];
996
    }
997 998 999
    return inputLocales.map((String localeString) {
      return LocaleInfo.fromString(localeString);
    }).toList();
1000 1001
  }

1002
  static String headerFromFile(String? headerString, String? headerFile, Directory inputDirectory) {
1003 1004 1005 1006 1007 1008 1009 1010
    if (headerString != null && headerFile != null) {
      throw L10nException(
        'Cannot accept both header and header file arguments. \n'
        'Please make sure to define only one or the other. '
      );
    }

    if (headerString != null) {
1011
      return headerString;
1012 1013
    } else if (headerFile != null) {
      try {
1014
        return inputDirectory.childFile(headerFile).readAsStringSync();
1015 1016 1017 1018 1019 1020 1021
      } on FileSystemException catch (error) {
        throw L10nException (
          'Failed to read header file: "$headerFile". \n'
          'FileSystemException: ${error.message}'
        );
      }
    }
1022
    return '';
1023 1024
  }

1025 1026
  static String _getAbsoluteProjectPath(String relativePath, Directory projectDirectory) =>
      projectDirectory.fileSystem.path.join(projectDirectory.path, relativePath);
1027

1028
  static File? _untranslatedMessagesFileFromPath(FileSystem fileSystem, String? untranslatedMessagesFileString) {
1029
    if (untranslatedMessagesFileString == null || untranslatedMessagesFileString.isEmpty) {
1030
      return null;
1031 1032
    }

1033
    return fileSystem.file(untranslatedMessagesFileString);
1034 1035
  }

1036
  static File? _inputsAndOutputsListFileFromPath(FileSystem fileSystem, String? inputsAndOutputsListPath) {
1037
    if (inputsAndOutputsListPath == null) {
1038
      return null;
1039
    }
1040

1041 1042
    return fileSystem.file(
      fileSystem.path.join(inputsAndOutputsListPath, 'gen_l10n_inputs_and_outputs.json'),
1043 1044 1045
    );
  }

1046 1047
  static bool _isValidGetterAndMethodName(String name) {
    // Public Dart method name must not start with an underscore
1048
    if (name[0] == '_') {
1049
      return false;
1050
    }
1051
    // Dart getter and method name cannot contain non-alphanumeric symbols
1052
    if (name.contains(RegExp(r'[^a-zA-Z_\d]'))) {
1053
      return false;
1054
    }
1055
    // Dart method name must start with lower case character
1056
    if (name[0].contains(RegExp(r'[A-Z]'))) {
1057
      return false;
1058
    }
1059
    // Dart class name cannot start with a number
1060
    if (name[0].contains(RegExp(r'\d'))) {
1061
      return false;
1062
    }
1063 1064 1065
    return true;
  }

1066
  // Load _allMessages from templateArbFile and _allBundles from all of the ARB
1067
  // files in inputDirectory. Also initialized: supportedLocales.
1068
  void loadResources() {
1069 1070
    _allMessages = _templateBundle.resourceIds.map((String id) => Message(
      _templateBundle.resources, id, areResourceAttributesRequired,
1071
    ));
1072
    for (final String resourceId in _templateBundle.resourceIds) {
1073 1074 1075 1076 1077 1078 1079 1080
      if (!_isValidGetterAndMethodName(resourceId)) {
        throw L10nException(
          'Invalid ARB resource name "$resourceId" in $templateArbFile.\n'
          'Resources names must be valid Dart method names: they have to be '
          'camel case, cannot start with a number or underscore, and cannot '
          'contain non-alphanumeric characters.'
        );
      }
1081
    }
1082

1083
    if (inputsAndOutputsListFile != null) {
1084 1085 1086 1087
      _inputFileList.addAll(_allBundles.bundles.map((AppResourceBundle bundle) {
        return bundle.file.absolute.path;
      }));
    }
1088

1089 1090 1091 1092
    final List<LocaleInfo> allLocales = List<LocaleInfo>.from(_allBundles.locales);
    for (final LocaleInfo preferredLocale in preferredSupportedLocales) {
      final int index = allLocales.indexOf(preferredLocale);
      if (index == -1) {
1093
        throw L10nException(
1094 1095 1096 1097
          "The preferred supported locale, '$preferredLocale', cannot be "
          'added. Please make sure that there is a corresponding ARB file '
          'with translations for the locale, or remove the locale from the '
          'preferred supported locale list.'
1098
        );
1099
      }
1100 1101
      allLocales.removeAt(index);
      allLocales.insertAll(0, preferredSupportedLocales);
1102
    }
1103
    supportedLocales.addAll(allLocales);
1104 1105
  }

1106 1107
  void _addUnimplementedMessage(LocaleInfo locale, String message) {
    if (_unimplementedMessages.containsKey(locale)) {
1108
      _unimplementedMessages[locale]!.add(message);
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
    } else {
      _unimplementedMessages.putIfAbsent(locale, () => <String>[message]);
    }
  }

  String _generateBaseClassFile(
    String className,
    String fileName,
    String header,
    AppResourceBundle bundle,
    AppResourceBundle templateBundle,
    Iterable<Message> messages,
  ) {
    final LocaleInfo locale = bundle.locale;

    final Iterable<String> methods = messages.map((Message message) {
      if (bundle.translationFor(message) == null) {
        _addUnimplementedMessage(locale, message.resourceId);
      }

1129
      return _generateMethod(
1130
        message,
1131
        bundle.translationFor(message) ?? templateBundle.translationFor(message)!,
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
      );
    });

    return classFileTemplate
      .replaceAll('@(header)', header)
      .replaceAll('@(language)', describeLocale(locale.toString()))
      .replaceAll('@(baseClass)', className)
      .replaceAll('@(fileName)', fileName)
      .replaceAll('@(class)', '$className${locale.camelCase()}')
      .replaceAll('@(localeName)', locale.toString())
1142
      .replaceAll('@(methods)', methods.join('\n\n'))
1143
      .replaceAll('@(requiresIntlImport)', _requiresIntlImport() ? "import 'package:intl/intl.dart' as intl;" : '');
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
  }

  String _generateSubclass(
    String className,
    AppResourceBundle bundle,
    Iterable<Message> messages,
  ) {
    final LocaleInfo locale = bundle.locale;
    final String baseClassName = '$className${LocaleInfo.fromString(locale.languageCode).camelCase()}';

    messages
      .where((Message message) => bundle.translationFor(message) == null)
      .forEach((Message message) {
        _addUnimplementedMessage(locale, message.resourceId);
      });

    final Iterable<String> methods = messages
      .where((Message message) => bundle.translationFor(message) != null)
1162
      .map((Message message) => _generateMethod(message, bundle.translationFor(message)!));
1163 1164 1165 1166 1167 1168 1169 1170 1171

    return subclassTemplate
      .replaceAll('@(language)', describeLocale(locale.toString()))
      .replaceAll('@(baseLanguageClassName)', baseClassName)
      .replaceAll('@(class)', '$className${locale.camelCase()}')
      .replaceAll('@(localeName)', locale.toString())
      .replaceAll('@(methods)', methods.join('\n\n'));
  }

1172
  // Generate the AppLocalizations class, its LocalizationsDelegate subclass,
1173 1174
  // and all AppLocalizations subclasses for every locale. This method by
  // itself does not generate the output files.
1175
  String _generateCode() {
1176 1177
    bool isBaseClassLocale(LocaleInfo locale, String language) {
      return locale.languageCode == language
1178
          && locale.countryCode == null
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
          && locale.scriptCode == null;
    }

    List<LocaleInfo> getLocalesForLanguage(String language) {
      return _allBundles.bundles
        // Return locales for the language specified, except for the base locale itself
        .where((AppResourceBundle bundle) {
          final LocaleInfo locale = bundle.locale;
          return !isBaseClassLocale(locale, language) && locale.languageCode == language;
        })
        .map((AppResourceBundle bundle) => bundle.locale).toList();
    }

1192 1193
    final String directory = _fs.path.basename(outputDirectory.path);
    final String outputFileName = _fs.path.basename(baseOutputFile.path);
1194 1195 1196 1197 1198 1199
    if (!outputFileName.endsWith('.dart')) {
      throw L10nException(
        "The 'output-localization-file', $outputFileName, is invalid.\n"
        'The file name must have a .dart extension.'
      );
    }
1200 1201

    final Iterable<String> supportedLocalesCode = supportedLocales.map((LocaleInfo locale) {
1202
      final String languageCode = locale.languageCode;
1203 1204
      final String? countryCode = locale.countryCode;
      final String? scriptCode = locale.scriptCode;
1205 1206

      if (countryCode == null && scriptCode == null) {
1207
        return "Locale('$languageCode')";
1208
      } else if (countryCode != null && scriptCode == null) {
1209
        return "Locale('$languageCode', '$countryCode')";
1210
      } else if (countryCode != null && scriptCode != null) {
1211
        return "Locale.fromSubtags(languageCode: '$languageCode', countryCode: '$countryCode', scriptCode: '$scriptCode')";
1212
      } else {
1213
        return "Locale.fromSubtags(languageCode: '$languageCode', scriptCode: '$scriptCode')";
1214
      }
1215 1216 1217
    });

    final Set<String> supportedLanguageCodes = Set<String>.from(
1218
      _allBundles.locales.map<String>((LocaleInfo locale) => "'${locale.languageCode}'")
1219
    );
1220 1221

    final List<LocaleInfo> allLocales = _allBundles.locales.toList()..sort();
1222 1223 1224 1225 1226 1227 1228 1229 1230
    final int extensionIndex = outputFileName.indexOf('.');
    if (extensionIndex <= 0) {
      throw L10nException(
        "The 'output-localization-file', $outputFileName, is invalid.\n"
        'The base name cannot be empty.'
      );
    }
    final String fileName = outputFileName.substring(0, extensionIndex);
    final String fileExtension = outputFileName.substring(extensionIndex + 1);
1231
    for (final LocaleInfo locale in allLocales) {
1232
      if (isBaseClassLocale(locale, locale.languageCode)) {
1233
        final File languageMessageFile = outputDirectory.childFile('${fileName}_$locale.$fileExtension');
1234 1235 1236 1237

        // Generate the template for the base class file. Further string
        // interpolation will be done to determine if there are
        // subclasses that extend the base class.
1238
        final String languageBaseClassFile = _generateBaseClassFile(
1239 1240 1241
          className,
          outputFileName,
          header,
1242 1243
          _allBundles.bundleFor(locale)!,
          _allBundles.bundleFor(_templateArbLocale)!,
1244 1245 1246 1247 1248 1249 1250 1251
          _allMessages,
        );

        // Every locale for the language except the base class.
        final List<LocaleInfo> localesForLanguage = getLocalesForLanguage(locale.languageCode);

        // Generate every subclass that is needed for the particular language
        final Iterable<String> subclasses = localesForLanguage.map<String>((LocaleInfo locale) {
1252 1253
          return _generateSubclass(
            className,
1254
            _allBundles.bundleFor(locale)!,
1255
            _allMessages,
1256 1257 1258
          );
        });

1259 1260 1261
        _languageFileMap.putIfAbsent(languageMessageFile, () {
          return languageBaseClassFile.replaceAll('@(subclasses)', subclasses.join());
        });
1262
      }
1263 1264
    }

1265
    final List<String> sortedClassImports = supportedLocales
1266 1267
      .where((LocaleInfo locale) => isBaseClassLocale(locale, locale.languageCode))
      .map((LocaleInfo locale) {
1268 1269
        final String library = '${fileName}_${locale.toString()}';
        if (useDeferredLoading) {
1270
          return "import '$library.$fileExtension' deferred as $library;";
1271
        } else {
1272
          return "import '$library.$fileExtension';";
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
        }
      })
      .toList()
      ..sort();

    final String delegateClass = _generateDelegateClass(
      allBundles: _allBundles,
      className: className,
      supportedLanguageCodes: supportedLanguageCodes,
      useDeferredLoading: useDeferredLoading,
      fileName: fileName,
    );
1285

1286
    return fileTemplate
1287
      .replaceAll('@(header)', header)
1288
      .replaceAll('@(class)', className)
1289
      .replaceAll('@(methods)', _allMessages.map((Message message) => generateBaseClassMethod(message, _templateArbLocale)).join('\n'))
1290 1291 1292
      .replaceAll('@(importFile)', '$directory/$outputFileName')
      .replaceAll('@(supportedLocales)', supportedLocalesCode.join(',\n    '))
      .replaceAll('@(supportedLanguageCodes)', supportedLanguageCodes.join(', '))
1293
      .replaceAll('@(messageClassImports)', sortedClassImports.join('\n'))
1294
      .replaceAll('@(delegateClass)', delegateClass)
1295
      .replaceAll('@(requiresFoundationImport)', useDeferredLoading ? '' : "import 'package:flutter/foundation.dart';")
1296
      .replaceAll('@(requiresIntlImport)', _requiresIntlImport() ? "import 'package:intl/intl.dart' as intl;" : '')
1297
      .replaceAll('@(canBeNullable)', usesNullableGetter ? '?' : '')
1298 1299 1300 1301 1302
      .replaceAll('@(needsNullCheck)', usesNullableGetter ? '' : '!')
      // Removes all trailing whitespace from the generated file.
      .split('\n').map((String line) => line.trimRight()).join('\n')
      // Cleans out unnecessary newlines.
      .replaceAll('\n\n\n', '\n\n');
1303 1304
  }

1305 1306 1307 1308 1309
  bool _requiresIntlImport() => _allMessages.any((Message message) {
    return message.isPlural
        || message.isSelect
        || message.placeholdersRequireFormatting;
  });
1310

1311
  void writeOutputFiles(Logger logger, { bool isFromYaml = false }) {
1312
    // First, generate the string contents of all necessary files.
1313
    final String generatedLocalizationsFile = _generateCode();
1314

1315 1316
    // A pubspec.yaml file is required when using a synthetic package. If it does not
    // exist, create a blank one.
1317
    if (useSyntheticPackage) {
1318 1319 1320
      final Directory syntheticPackageDirectory = projectDirectory != null
          ? projectDirectory!.childDirectory(_defaultSyntheticPackagePath(_fs))
          : _fs.directory(_defaultSyntheticPackagePath(_fs));
1321 1322 1323 1324 1325 1326 1327
      syntheticPackageDirectory.createSync(recursive: true);
      final File flutterGenPubspec = syntheticPackageDirectory.childFile('pubspec.yaml');
      if (!flutterGenPubspec.existsSync()) {
        flutterGenPubspec.writeAsStringSync(emptyPubspecTemplate);
      }
    }

1328 1329
    // Since all validity checks have passed up to this point,
    // write the contents into the directory.
1330
    outputDirectory.createSync(recursive: true);
1331 1332 1333

    // Ensure that the created directory has read/write permissions.
    final FileStat fileStat = outputDirectory.statSync();
1334 1335
    if (_isNotReadable(fileStat) || _isNotWritable(fileStat)) {
      throw L10nException(
1336 1337 1338
        "The 'output-dir' directory, $outputDirectory, doesn't allow reading and writing.\n"
        'Please ensure that the user has read and write permissions.'
      );
1339
    }
1340 1341 1342 1343

    // Generate the required files for localizations.
    _languageFileMap.forEach((File file, String contents) {
      file.writeAsStringSync(contents);
1344
      if (inputsAndOutputsListFile != null) {
1345 1346
        _outputFileList.add(file.absolute.path);
      }
1347
    });
1348

1349 1350 1351 1352
    baseOutputFile.writeAsStringSync(generatedLocalizationsFile);
    final File? messagesFile = untranslatedMessagesFile;
    if (messagesFile != null) {
      _generateUntranslatedMessagesFile(logger, messagesFile);
1353 1354 1355 1356
    } else if (_unimplementedMessages.isNotEmpty) {
      _unimplementedMessages.forEach((LocaleInfo locale, List<String> messages) {
        logger.printStatus('"$locale": ${messages.length} untranslated message(s).');
      });
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
      if (isFromYaml) {
        logger.printStatus(
          'To see a detailed report, use the untranslated-messages-file \n'
          'option in the l10n.yaml file:\n'
          'untranslated-messages-file: desiredFileName.txt\n'
          '<other option>: <other selection> \n\n'
        );
      } else {
        logger.printStatus(
          'To see a detailed report, use the --untranslated-messages-file \n'
          'option in the flutter gen-l10n tool:\n'
          'flutter gen-l10n --untranslated-messages-file=desiredFileName.txt\n'
          '<other options> \n\n'
        );
      }

1373
      logger.printStatus(
1374 1375
        'This will generate a JSON format file containing all messages that \n'
        'need to be translated.'
1376 1377
      );
    }
1378 1379
    final File? inputsAndOutputsListFileLocal = inputsAndOutputsListFile;
    if (inputsAndOutputsListFileLocal != null) {
1380 1381 1382
      _outputFileList.add(baseOutputFile.absolute.path);

      // Generate a JSON file containing the inputs and outputs of the gen_l10n script.
1383 1384
      if (!inputsAndOutputsListFileLocal.existsSync()) {
        inputsAndOutputsListFileLocal.createSync(recursive: true);
1385 1386
      }

1387
      inputsAndOutputsListFileLocal.writeAsStringSync(
1388 1389 1390 1391 1392 1393
        json.encode(<String, Object> {
          'inputs': _inputFileList,
          'outputs': _outputFileList,
        }),
      );
    }
1394
  }
1395

1396
  void _generateUntranslatedMessagesFile(Logger logger, File untranslatedMessagesFile) {
1397
    if (_unimplementedMessages.isEmpty) {
1398 1399 1400
      untranslatedMessagesFile.writeAsStringSync('{}');
      if (inputsAndOutputsListFile != null) {
        _outputFileList.add(untranslatedMessagesFile.absolute.path);
1401
      }
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
      return;
    }

    String resultingFile = '{\n';
    int count = 0;
    final int numberOfLocales = _unimplementedMessages.length;
    _unimplementedMessages.forEach((LocaleInfo locale, List<String> messages) {
      resultingFile += '  "$locale": [\n';

      for (int i = 0; i < messages.length; i += 1) {
        resultingFile += '    "${messages[i]}"';
        if (i != messages.length - 1) {
          resultingFile += ',';
        }
        resultingFile += '\n';
      }

      resultingFile += '  ]';
      count += 1;
      if (count < numberOfLocales) {
        resultingFile += ',\n';
      }
      resultingFile += '\n';
    });

    resultingFile += '}\n';
1428 1429 1430
    untranslatedMessagesFile.writeAsStringSync(resultingFile);
    if (inputsAndOutputsListFile != null) {
      _outputFileList.add(untranslatedMessagesFile.absolute.path);
1431
    }
1432
  }
1433
}