gen_date_localizations.dart 6.73 KB
Newer Older
1 2 3 4 5 6 7 8
// 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 program extracts localized date symbols and patterns from the intl
/// package for the subset of locales supported by the flutter_localizations
/// package.
///
9
/// The extracted data is written into:
10
///   packages/flutter_localizations/lib/src/l10n/generated_date_localizations.dart
11
///
12 13 14
/// ## Usage
///
/// Run this program from the root of the git repository.
15 16 17 18
///
/// The following outputs the generated Dart code to the console as a dry run:
///
/// ```
19
/// dart dev/tools/localization/gen_date_localizations.dart
20 21
/// ```
///
22
/// If the data looks good, use the `--overwrite` option to overwrite the
23 24 25
/// lib/src/l10n/date_localizations.dart file:
///
/// ```
26
/// dart dev/tools/localization/gen_date_localizations.dart --overwrite
27 28 29 30 31 32 33 34
/// ```

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:path/path.dart' as path;

35 36
import 'localizations_utils.dart';

37 38
const String _kCommandName = 'gen_date_localizations.dart';

39 40 41 42 43 44
// Used to let _jsonToMap know what locale it's date symbols converting for.
// Date symbols for the Kannada locale ('kn') are handled specially because
// some of the strings contain characters that can crash Emacs on Linux.
// See packages/flutter_localizations/lib/src/l10n/README for more information.
String currentLocale;

45
Future<void> main(List<String> rawArgs) async {
46
  checkCwdIsRepoRoot(_kCommandName);
47

48
  final bool writeToFile = parseArgs(rawArgs).writeToFile;
49

50
  final File dotPackagesFile = File(path.join('packages', 'flutter_localizations', '.packages'));
51 52 53
  final bool dotPackagesExists = dotPackagesFile.existsSync();

  if (!dotPackagesExists) {
54
    exitWithError(
55 56 57 58 59 60 61 62 63 64 65
      'File not found: ${dotPackagesFile.path}. $_kCommandName must be run '
      'after a successful "flutter update-packages".'
    );
  }

  final String pathToIntl = dotPackagesFile
    .readAsStringSync()
    .split('\n')
    .firstWhere(
      (String line) => line.startsWith('intl:'),
      orElse: () {
66
        exitWithError('intl dependency not found in ${dotPackagesFile.path}');
67
        return null; // unreachable
68 69 70 71 72
      },
    )
    .split(':')
    .last;

73
  final Directory dateSymbolsDirectory = Directory(path.join(pathToIntl, 'src', 'data', 'dates', 'symbols'));
74
  final Map<String, File> symbolFiles = _listIntlData(dateSymbolsDirectory);
75
  final Directory datePatternsDirectory = Directory(path.join(pathToIntl, 'src', 'data', 'dates', 'patterns'));
76
  final Map<String, File> patternFiles = _listIntlData(datePatternsDirectory);
77
  final StringBuffer buffer = StringBuffer();
78 79 80 81 82 83 84

  buffer.writeln(
'''
// 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.

85
// This file has been automatically generated. Please do not edit it manually.
86
// To regenerate run (omit --overwrite to print to console instead of the file):
87
// dart --enable-asserts dev/tools/localization/gen_date_localizations.dart --overwrite
88 89 90

'''
);
91 92 93
  buffer.writeln('''
/// The subset of date symbols supported by the intl package which are also
/// supported by flutter_localizations.''');
94
  buffer.writeln('const Map<String, dynamic> dateSymbols = <String, dynamic> {');
95
  symbolFiles.forEach((String locale, File data) {
96
    currentLocale = locale;
97
    if (_supportedLocales().contains(locale))
98
      buffer.writeln(_jsonToMapEntry(locale, json.decode(data.readAsStringSync())));
99
  });
100
  currentLocale = null;
101 102
  buffer.writeln('};');

103
  // Code that uses datePatterns expects it to contain values of type
104
  // Map<String, String> not Map<String, dynamic>.
105 106 107
  buffer.writeln('''
/// The subset of date patterns supported by the intl package which are also
/// supported by flutter_localizations.''');
108
  buffer.writeln('const Map<String, Map<String, String>> datePatterns = <String, Map<String, String>> {');
109
  patternFiles.forEach((String locale, File data) {
110
    if (_supportedLocales().contains(locale)) {
111
      final Map<String, dynamic> patterns = json.decode(data.readAsStringSync());
112
      buffer.writeln("'$locale': <String, String>{");
113 114 115 116 117 118
      patterns.forEach((String key, dynamic value) {
        assert(value is String);
        buffer.writeln(_jsonToMapEntry(key, value));
      });
      buffer.writeln('},');
    }
119 120 121 122
  });
  buffer.writeln('};');

  if (writeToFile) {
123
    final File dateLocalizationsFile = File(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n', 'generated_date_localizations.dart'));
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    dateLocalizationsFile.writeAsStringSync(buffer.toString());
    Process.runSync(path.join('bin', 'cache', 'dart-sdk', 'bin', 'dartfmt'), <String>[
      '-w',
      dateLocalizationsFile.path,
    ]);
  } else {
    print(buffer);
  }
}

String _jsonToMapEntry(String key, dynamic value) {
  return "'$key': ${_jsonToMap(value)},";
}

String _jsonToMap(dynamic json) {
  if (json == null || json is num || json is bool)
    return '$json';

  if (json is String) {
143 144 145
    if (currentLocale == 'kn')
      return generateEncodedString(json);
    else if (json.contains("'"))
146 147 148 149 150 151
      return 'r"""$json"""';
    else
      return "r'''$json'''";
  }

  if (json is Iterable)
152
    return '<dynamic>[${json.map<String>(_jsonToMap).join(',')}]';
153

154
  if (json is Map<String, dynamic>) {
155
    final StringBuffer buffer = StringBuffer('<String, dynamic>{');
156 157 158 159 160 161 162 163 164 165
    json.forEach((String key, dynamic value) {
      buffer.writeln(_jsonToMapEntry(key, value));
    });
    buffer.write('}');
    return buffer.toString();
  }

  throw 'Unsupported JSON type ${json.runtimeType} of value $json.';
}

166 167 168 169 170
Set<String> _supportedLocales() {
  final Set<String> supportedLocales = <String>{};
  final RegExp filenameRE = RegExp(r'(?:material|cupertino)_(\w+)\.arb$');
  final Directory supportedLocalesDirectory = Directory(path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n'));
  for (FileSystemEntity entity in supportedLocalesDirectory.listSync()) {
171 172
    final String filePath = entity.path;
    if (FileSystemEntity.isFileSync(filePath) && filenameRE.hasMatch(filePath))
173
      supportedLocales.add(filenameRE.firstMatch(filePath)[1]);
174
  }
175
  return supportedLocales;
176 177 178
}

Map<String, File> _listIntlData(Directory directory) {
179
  final Map<String, File> localeFiles = <String, File>{};
180 181 182 183
  for (FileSystemEntity entity in directory.listSync()) {
    final String filePath = entity.path;
    if (FileSystemEntity.isFileSync(filePath) && filePath.endsWith('.json')) {
      final String locale = path.basenameWithoutExtension(filePath);
184
      localeFiles[locale] = entity;
185 186
    }
  }
187 188 189

  final List<String> locales = localeFiles.keys.toList(growable: false);
  locales.sort();
190
  return Map<String, File>.fromIterable(locales, value: (dynamic locale) => localeFiles[locale]);
191
}