Skip to content

Commit

Permalink
Format code with 'dartfmt' (to add additional points to package)
Browse files Browse the repository at this point in the history
  • Loading branch information
Pavel-Sulimau committed Mar 2, 2021
1 parent 1c38185 commit 6dbe3fa
Show file tree
Hide file tree
Showing 7 changed files with 125 additions and 70 deletions.
54 changes: 29 additions & 25 deletions lib/builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,27 @@ class I18nBuilder implements Builder {

bool _generated = false;

String get inputFilePattern => options.config['input_file_pattern'] ?? defaultInputFilePattern;
String get outputFilePattern => options.config['output_file_pattern'] ?? defaultOutputFilePattern;
String get inputFilePattern =>
options.config['input_file_pattern'] ?? defaultInputFilePattern;
String get outputFilePattern =>
options.config['output_file_pattern'] ?? defaultOutputFilePattern;

@override
FutureOr<void> build(BuildStep buildStep) async {
final String baseLocale = Utils.normalize(options.config['base_locale'] ?? defaultBaseLocale);
final String baseLocale =
Utils.normalize(options.config['base_locale'] ?? defaultBaseLocale);
final String inputDirectory = options.config['input_directory'];
final String outputDirectory = options.config['output_directory'];
final String translateVar = options.config['output_translate_var'] ?? defaultTranslateVar;
final String translateVar =
options.config['output_translate_var'] ?? defaultTranslateVar;
final String keyCase = options.config['key_case'];
final List<String> maps = options.config['maps']?.cast<String>() ?? [];

if (inputDirectory != null && !buildStep.inputId.path.contains(inputDirectory))
return;
if (inputDirectory != null &&
!buildStep.inputId.path.contains(inputDirectory)) return;

// only generate once
if (_generated)
return;
if (_generated) return;

_generated = true;

Expand All @@ -53,7 +56,8 @@ class I18nBuilder implements Builder {
: Glob('**$inputFilePattern');

await buildStep.findAssets(findAssetsPattern).forEach((assetId) {
final fileNameNoExtension = assetId.pathSegments.last.replaceAll(inputFilePattern, '');
final fileNameNoExtension =
assetId.pathSegments.last.replaceAll(inputFilePattern, '');
final match = Utils.localeRegex.firstMatch(fileNameNoExtension);

if (match != null) {
Expand All @@ -77,12 +81,11 @@ class I18nBuilder implements Builder {

// build config which applies to all locales
final config = I18nConfig(
baseName: baseName ?? defaultBaseName,
baseLocale: baseLocale,
maps: maps,
keyCase: keyCase,
translateVariable: translateVar
);
baseName: baseName ?? defaultBaseName,
baseLocale: baseLocale,
maps: maps,
keyCase: keyCase,
translateVariable: translateVar);

// map each assetId to I18nData
final localesWithData = Map<AssetId, I18nData>();
Expand All @@ -96,23 +99,24 @@ class I18nBuilder implements Builder {

// generate
final String output = generate(
config: config,
translations: localesWithData.values.toList()..sort((a, b) => a.locale.compareTo(b.locale))
);
config: config,
translations: localesWithData.values.toList()
..sort((a, b) => a.locale.compareTo(b.locale)));

// write only to main locale
final AssetId baseId = localesWithData.entries
.firstWhere((element) => element.value.base)
.key;
final AssetId baseId =
localesWithData.entries.firstWhere((element) => element.value.base).key;

final finalOutputDirectory = outputDirectory ?? (baseId.pathSegments..removeLast()).join('/');
final String outFilePath = '$finalOutputDirectory/$baseName$outputFilePattern';
final finalOutputDirectory =
outputDirectory ?? (baseId.pathSegments..removeLast()).join('/');
final String outFilePath =
'$finalOutputDirectory/$baseName$outputFilePattern';

File(outFilePath).writeAsStringSync(output);
}

@override
get buildExtensions => {
inputFilePattern: [outputFilePattern],
};
inputFilePattern: [outputFilePattern],
};
}
28 changes: 18 additions & 10 deletions lib/fast_i18n.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,27 @@ class FastI18n {

/// Returns the candidate (or part of it) if it is supported.
/// Fallbacks to base locale.
static String selectLocale(String candidate, List<String> supported, String baseLocale) {
static String selectLocale(
String candidate, List<String> supported, String baseLocale) {
// normalize
candidate = Utils.normalize(candidate);

// 1st try: match exactly
String selected = supported.firstWhere((element) => element == candidate, orElse: () => null);
String selected = supported.firstWhere((element) => element == candidate,
orElse: () => null);
if (selected != null) return selected;

// 2nd try: match the first part (language)
List<String> deviceLocaleParts = candidate.split(_localePartsDelimiter);
selected =
supported.firstWhere((element) => element == deviceLocaleParts.first, orElse: () => null);
selected = supported.firstWhere(
(element) => element == deviceLocaleParts.first,
orElse: () => null);
if (selected != null) return selected;

// 3rd try: match the second part (region)
selected =
supported.firstWhere((element) => element == deviceLocaleParts.last, orElse: () => null);
selected = supported.firstWhere(
(element) => element == deviceLocaleParts.last,
orElse: () => null);
if (selected != null) return selected;

// fallback: default locale
Expand All @@ -38,18 +42,22 @@ class FastI18n {

/// Converts the passed locales from [String] to [Locale].
/// Puts the [baseLocale] into the the beginning of the list.
static List<Locale> convertToLocales(List<String> locales, String baseLocale) {
static List<Locale> convertToLocales(
List<String> locales, String baseLocale) {
final rawSupportedLocales = [
baseLocale,
...locales.where((locale) => locale != baseLocale),
];

final supportedLocales = rawSupportedLocales.map((rawLocale) {
if (rawLocale.contains(_localePartsDelimiter)) {
final localeParts =
rawLocale.split(_localePartsDelimiter).where((part) => part.isNotEmpty).toList();
final localeParts = rawLocale
.split(_localePartsDelimiter)
.where((part) => part.isNotEmpty)
.toList();
if (localeParts.length == 2) {
return Locale.fromSubtags(languageCode: localeParts[0], countryCode: localeParts[1]);
return Locale.fromSubtags(
languageCode: localeParts[0], countryCode: localeParts[1]);
} else if (localeParts.length == 3) {
return Locale.fromSubtags(
languageCode: localeParts[0],
Expand Down
67 changes: 44 additions & 23 deletions lib/src/generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ String generate({I18nConfig config, List<I18nData> translations}) {

/// generates the header of the .g.dart file
/// contains the t function, LocaleSettings class and some global variables
void _generateHeader(StringBuffer buffer, I18nConfig config, List<I18nData> allLocales) {
void _generateHeader(
StringBuffer buffer, I18nConfig config, List<I18nData> allLocales) {
// identifiers
const String mapVar = '_strings';
const String baseLocaleVar = '_baseLocale';
Expand Down Expand Up @@ -79,7 +80,8 @@ void _generateHeader(StringBuffer buffer, I18nConfig config, List<I18nData> allL
buffer.writeln('///');
buffer.writeln(
'/// Widgets using this method will not be updated when locale changes during runtime.');
buffer.writeln('/// Translation happens during initialization of the widget (call of t).');
buffer.writeln(
'/// Translation happens during initialization of the widget (call of t).');
buffer.writeln('///');
buffer.writeln('/// Usage:');
buffer.writeln('/// String translated = t.someKey.anotherKey;');
Expand All @@ -89,7 +91,8 @@ void _generateHeader(StringBuffer buffer, I18nConfig config, List<I18nData> allL
buffer.writeln();
buffer.writeln('/// Method B: Advanced');
buffer.writeln('///');
buffer.writeln('/// All widgets using this method will trigger a rebuild when locale changes.');
buffer.writeln(
'/// All widgets using this method will trigger a rebuild when locale changes.');
buffer.writeln(
'/// Use this if you have e.g. a settings page where the user can select the locale during runtime.');
buffer.writeln('///');
Expand All @@ -100,8 +103,10 @@ void _generateHeader(StringBuffer buffer, I18nConfig config, List<I18nData> allL
buffer.writeln('/// );');
buffer.writeln('///');
buffer.writeln('/// Step 2:');
buffer.writeln('/// final t = $translationsClass.of(context); // get t variable');
buffer.writeln('/// String translated = t.someKey.anotherKey; // use t variable');
buffer.writeln(
'/// final t = $translationsClass.of(context); // get t variable');
buffer.writeln(
'/// String translated = t.someKey.anotherKey; // use t variable');
buffer.writeln('class $translationsClass {');
buffer.writeln('\t$translationsClass._(); // no constructor');
buffer.writeln();
Expand Down Expand Up @@ -133,7 +138,8 @@ void _generateHeader(StringBuffer buffer, I18nConfig config, List<I18nData> allL
buffer.writeln('\t\t$translateVar = $mapVar[$localeVar];');
buffer.writeln();
buffer.writeln('\t\tif ($translationProviderKey.currentState != null) {');
buffer.writeln('\t\t\t$translationProviderKey.currentState.setLocale($localeVar);');
buffer.writeln(
'\t\t\t$translationProviderKey.currentState.setLocale($localeVar);');
buffer.writeln('\t\t}');
buffer.writeln();
buffer.writeln('\t\treturn $localeVar;');
Expand All @@ -160,7 +166,8 @@ void _generateHeader(StringBuffer buffer, I18nConfig config, List<I18nData> allL
buffer.writeln();
buffer.writeln('\t/// Get supported locales with base locale sorted first.');
buffer.writeln('\tstatic List<Locale> get supportedLocales {');
buffer.writeln('\t\treturn FastI18n.convertToLocales($mapVar.keys.toList(), $baseLocaleVar);');
buffer.writeln(
'\t\treturn FastI18n.convertToLocales($mapVar.keys.toList(), $baseLocaleVar);');
buffer.writeln('\t}');

buffer.writeln('}');
Expand All @@ -182,7 +189,8 @@ void _generateHeader(StringBuffer buffer, I18nConfig config, List<I18nData> allL
buffer.writeln('}');

buffer.writeln();
buffer.writeln('class $translationProviderStateClass extends State<$translationProviderClass> {');
buffer.writeln(
'class $translationProviderStateClass extends State<$translationProviderClass> {');
buffer.writeln('\tString locale = $localeVar;');
buffer.writeln();
buffer.writeln('\tvoid setLocale(String newLocale) {');
Expand All @@ -204,7 +212,8 @@ void _generateHeader(StringBuffer buffer, I18nConfig config, List<I18nData> allL
buffer.writeln();
buffer.writeln('class $inheritedClass extends InheritedWidget {');
buffer.writeln('\tfinal $baseClassName translations;');
buffer.writeln('\t$inheritedClass({this.translations, Widget child}) : super(child: child);');
buffer.writeln(
'\t$inheritedClass({this.translations, Widget child}) : super(child: child);');
buffer.writeln();
buffer.writeln('\t@override');
buffer.writeln('\tbool updateShouldNotify($inheritedClass oldWidget) {');
Expand All @@ -216,7 +225,8 @@ void _generateHeader(StringBuffer buffer, I18nConfig config, List<I18nData> allL
/// generates all classes of one locale
/// all non-default locales has a postfix of their locale code
/// e.g. Strings, StringsDe, StringsFr
void _generateLocale(StringBuffer buffer, I18nConfig config, I18nData localeData) {
void _generateLocale(
StringBuffer buffer, I18nConfig config, I18nData localeData) {
Queue<ClassTask> queue = Queue();

queue.add(ClassTask(
Expand Down Expand Up @@ -250,7 +260,8 @@ void _generateClass(
String className,
Map<String, Value> currMembers,
) {
String finalClassName = base ? className : className + locale.capitalize().replaceAll('-', '');
String finalClassName =
base ? className : className + locale.capitalize().replaceAll('-', '');

buffer.writeln();

Expand All @@ -276,7 +287,8 @@ void _generateClass(
if (value.params.isEmpty) {
buffer.writeln('String $key = \'${value.content}\';');
} else {
buffer.writeln('String $key${_toParameterList(value.params)} => \'${value.content}\';');
buffer.writeln(
'String $key${_toParameterList(value.params)} => \'${value.content}\';');
}
} else if (value is ListNode) {
String type = value.plainStrings ? 'String' : 'dynamic';
Expand All @@ -288,15 +300,18 @@ void _generateClass(
// inline map
String type = value.plainStrings ? 'String' : 'dynamic';
buffer.write('Map<String, $type> get $key => ');
_generateMap(base, locale, buffer, queue, childClassName, value.entries, 0);
_generateMap(
base, locale, buffer, queue, childClassName, value.entries, 0);
} else {
// generate a class later on
queue.add(ClassTask(childClassName, value.entries));

String finalChildClassName =
base ? childClassName : childClassName + locale.capitalize().replaceAll('-', '');
String finalChildClassName = base
? childClassName
: childClassName + locale.capitalize().replaceAll('-', '');

buffer.writeln('$finalChildClassName get $key => $finalChildClassName._instance;');
buffer.writeln(
'$finalChildClassName get $key => $finalChildClassName._instance;');
}
}
});
Expand All @@ -323,23 +338,27 @@ void _generateMap(
if (value.params.isEmpty) {
buffer.writeln('\'$key\': \'${value.content}\',');
} else {
buffer.writeln('\'$key\': ${_toParameterList(value.params)} => \'${value.content}\',');
buffer.writeln(
'\'$key\': ${_toParameterList(value.params)} => \'${value.content}\',');
}
} else if (value is ListNode) {
buffer.write('\'$key\': ');
_generateList(base, locale, buffer, queue, className, value.entries, depth + 1);
_generateList(
base, locale, buffer, queue, className, value.entries, depth + 1);
} else if (value is ObjectNode) {
String childClassName = className + key.capitalize();
if (value.mapMode) {
// inline map
buffer.write('\'$key\': ');
_generateMap(base, locale, buffer, queue, childClassName, value.entries, depth + 1);
_generateMap(base, locale, buffer, queue, childClassName, value.entries,
depth + 1);
} else {
// generate a class later on
queue.add(ClassTask(childClassName, value.entries));

String finalChildClassName =
base ? childClassName : childClassName + locale.capitalize().replaceAll('-', '');
String finalChildClassName = base
? childClassName
: childClassName + locale.capitalize().replaceAll('-', '');

buffer.writeln('\'$key\': $finalChildClassName._instance,');
}
Expand Down Expand Up @@ -376,10 +395,12 @@ void _generateList(
if (value.params.isEmpty) {
buffer.writeln('\'${value.content}\',');
} else {
buffer.writeln('${_toParameterList(value.params)} => \'${value.content}\',');
buffer.writeln(
'${_toParameterList(value.params)} => \'${value.content}\',');
}
} else if (value is ListNode) {
_generateList(base, locale, buffer, queue, className, value.entries, depth + 1);
_generateList(
base, locale, buffer, queue, className, value.entries, depth + 1);
} else if (value is ObjectNode) {
String childClassName = className + depth.toString() + 'i' + i.toString();
queue.add(ClassTask(childClassName, value.entries));
Expand Down
11 changes: 8 additions & 3 deletions lib/src/model.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ class I18nConfig {
final String keyCase;
final String translateVariable;

I18nConfig({this.baseName, this.baseLocale, this.maps, this.keyCase, this.translateVariable});
I18nConfig({
this.baseName,
this.baseLocale,
this.maps,
this.keyCase,
this.translateVariable,
});

@override
String toString() => '$baseLocale, maps: $maps';
Expand Down Expand Up @@ -80,8 +86,7 @@ class TextNode extends Value {
/// 'my name is $name and I am $age years old' => ['name', 'age']
/// 'my name is ${name} and I am ${age} years old' => ['name', 'age']
List<String> _findArguments(String content) {
return Utils
.argumentsRegex
return Utils.argumentsRegex
.allMatches(content)
.map((e) => e.group(2))
.toList();
Expand Down
Loading

0 comments on commit 6dbe3fa

Please sign in to comment.