gen_localizations.dart 5.86 KB
Newer Older
1 2 3 4
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
// This program generates a Dart "localizations" Map definition that combines
6
// the contents of the arb files. The map can be used to lookup a localized
7
// string: `localizations[localeString][resourceId]`.
8
//
9
// The *.arb files are in packages/flutter_localizations/lib/src/l10n.
10 11 12 13 14
//
// 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.
//
15 16 17 18
// The arb filenames are expected to have the form "material_(\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.
19 20 21 22
//
// This app is typically run by hand when a module's .arb files have been
// updated.
//
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
// ## 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:
//
// ```
// dart dev/tools/gen_localizations.dart
// ```
//
// If the data looks good, use the `-w` option to overwrite the
// packages/flutter_localizations/lib/src/l10n/localizations.dart file:
//
// ```
// dart dev/tools/gen_localizations.dart --overwrite
// ```
39 40 41 42

import 'dart:convert' show JSON;
import 'dart:io';

43 44 45
import 'package:path/path.dart' as pathlib;

import 'localizations_utils.dart';
46 47
import 'localizations_validator.dart';

48 49 50 51 52 53 54 55 56 57
const String outputHeader = '''
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file has been automatically generated.  Please do not edit it manually.
// To regenerate the file, use:
// @(regenerate)
''';

58
/// Maps locales to resource key/value pairs.
59 60
final Map<String, Map<String, String>> localeToResources = <String, Map<String, String>>{};

61
/// Maps locales to resource attributes.
62
///
63 64 65
/// See also https://github.com/googlei18n/app-resource-bundle/wiki/ApplicationResourceBundleSpecification#resource-attributes
final Map<String, Map<String, dynamic>> localeToResourceAttributes = <String, Map<String, dynamic>>{};

66 67 68 69
// Return s as a Dart-parseable raw string in single or double quotes. Expand double quotes:
// foo => r'foo'
// foo "bar" => r'foo "bar"'
// foo 'bar' => r'foo ' "'" r'bar' "'"
70
String generateString(String s) {
71 72
  if (!s.contains("'"))
    return "r'$s'";
73 74 75 76

  final StringBuffer output = new StringBuffer();
  bool started = false; // Have we started writing a raw string.
  for (int i = 0; i < s.length; i++) {
77
    if (s[i] == "'") {
78
      if (started)
79 80
        output.write("'");
      output.write(' "\'" ');
81 82
      started = false;
    } else if (!started) {
83
      output.write("r'${s[i]}");
84 85 86 87 88 89
      started = true;
    } else {
      output.write(s[i]);
    }
  }
  if (started)
90
    output.write("'");
91 92 93 94 95 96
  return output.toString();
}

String generateLocalizationsMap() {
  final StringBuffer output = new StringBuffer();

97 98 99 100 101 102
  output.writeln('''
/// Maps from [Locale.languageCode] to a map that contains the localized strings
/// for that locale.
///
/// This variable is used by [MaterialLocalizations].
const Map<String, Map<String, String>> localizations = const <String, Map<String, String>> {''');
103

Yegor's avatar
Yegor committed
104
  for (String locale in localeToResources.keys.toList()..sort()) {
105
    output.writeln("  '$locale': const <String, String>{");
106 107 108 109

    final Map<String, String> resources = localeToResources[locale];
    for (String name in resources.keys) {
      final String value = generateString(resources[name]);
110
      output.writeln("    '$name': $value,");
111
    }
112
    output.writeln('  },');
113 114 115 116 117 118 119 120
  }

  output.writeln('};');
  return output.toString();
}

void processBundle(File file, String locale) {
  localeToResources[locale] ??= <String, String>{};
121
  localeToResourceAttributes[locale] ??= <String, dynamic>{};
122
  final Map<String, String> resources = localeToResources[locale];
123
  final Map<String, dynamic> attributes = localeToResourceAttributes[locale];
124 125 126 127
  final Map<String, dynamic> bundle = JSON.decode(file.readAsStringSync());
  for (String key in bundle.keys) {
    // The ARB file resource "attributes" for foo are called @foo.
    if (key.startsWith('@'))
128 129 130
      attributes[key.substring(1)] = bundle[key];
    else
      resources[key] = bundle[key];
131 132 133
  }
}

134 135 136
void main(List<String> rawArgs) {
  checkCwdIsRepoRoot('gen_localizations');
  final GeneratorOptions options = parseArgs(rawArgs);
137 138 139 140 141

  // 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.

142 143
  final Directory directory = new Directory(pathlib.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'));
  final RegExp filenameRE = new RegExp(r'material_(\w+)\.arb$');
144

145 146 147 148
  exitWithError(
    validateEnglishLocalizations(new File(pathlib.join(directory.path, 'material_en.arb')))
  );

149 150 151 152 153 154 155
  for (FileSystemEntity entity in directory.listSync()) {
    final String path = entity.path;
    if (FileSystemEntity.isFileSync(path) && filenameRE.hasMatch(path)) {
      final String locale = filenameRE.firstMatch(path)[1];
      processBundle(new File(path), locale);
    }
  }
156 157 158 159

  exitWithError(
    validateLocalizations(localeToResources, localeToResourceAttributes)
  );
160

161 162 163 164 165 166 167 168 169 170 171
  final String regenerate = 'dart dev/tools/gen_localizations.dart --overwrite';
  final StringBuffer buffer = new StringBuffer();
  buffer.writeln(outputHeader.replaceFirst('@(regenerate)', regenerate));
  buffer.writeln(generateLocalizationsMap());

  if (options.writeToFile) {
    final File localizationsFile = new File(pathlib.join(directory.path, 'localizations.dart'));
    localizationsFile.writeAsStringSync('$buffer');
  } else {
    print(buffer);
  }
172
}