Skip to content

Commit

Permalink
Feature/display translations in documentation comments (#52)
Browse files Browse the repository at this point in the history
Adds optional to generate comments with localization details.
  • Loading branch information
lukaskurz committed Apr 24, 2022
1 parent 42d03e5 commit b379243
Show file tree
Hide file tree
Showing 10 changed files with 279 additions and 7 deletions.
4 changes: 4 additions & 0 deletions README.md
Expand Up @@ -49,6 +49,8 @@ flappy_translator:
expose_get_string: false
expose_loca_strings: false
expose_locale_maps: false
generate_comments: false
comment_languages: []
```

| Setting | Default | Description |
Expand All @@ -65,6 +67,8 @@ flappy_translator:
| expose_get_string | false | The default value for whether a getString method should be exposed. |
| expose_loca_strings | false | The default value for whether a locaStrings getter should be exposed. |
| expose_locale_maps | false | The default value for whether a localeMaps getter should be exposed. |
| generate_comments | false | Whether documentation comments should be used to display translations. |
| comment_languages | [] | Languages that are displayed in the comments. Empty -> All languages are used. |

### Run package

Expand Down
6 changes: 6 additions & 0 deletions bin/flappy_translator.dart
Expand Up @@ -29,6 +29,10 @@ void main() {
exposeGetString: settings[_YamlArguments.exposeGetString],
exposeLocaStrings: settings[_YamlArguments.exposeLocaStrings],
exposeLocaleMaps: settings[_YamlArguments.exposeLocaleMaps],
generateComments: settings[_YamlArguments.generateComments],
commentLanguages: (settings[_YamlArguments.commentLanguages] as YamlList?)
?.map<String>((node) => node.toString())
.toList(),
);
}

Expand All @@ -52,6 +56,8 @@ class _YamlArguments {
static const exposeGetString = 'expose_get_string';
static const exposeLocaStrings = 'expose_loca_strings';
static const exposeLocaleMaps = 'expose_locale_maps';
static const generateComments = 'generate_comments';
static const commentLanguages = 'comment_languages';
}

/// Returns configuration settings for flappy_translator from pubspec.yaml
Expand Down
15 changes: 11 additions & 4 deletions example/pubspec.lock
Expand Up @@ -42,7 +42,7 @@ packages:
name: characters
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.0"
version: "1.2.0"
charcode:
dependency: transitive
description:
Expand Down Expand Up @@ -158,13 +158,20 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "0.17.0"
material_color_utilities:
dependency: transitive
description:
name: material_color_utilities
url: "https://pub.dartlang.org"
source: hosted
version: "0.1.3"
meta:
dependency: transitive
description:
name: meta
url: "https://pub.dartlang.org"
source: hosted
version: "1.3.0"
version: "1.7.0"
package_config:
dependency: transitive
description:
Expand Down Expand Up @@ -239,7 +246,7 @@ packages:
name: vector_math
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.0"
version: "2.1.1"
watcher:
dependency: transitive
description:
Expand All @@ -262,5 +269,5 @@ packages:
source: hosted
version: "3.1.0"
sdks:
dart: ">=2.12.0 <3.0.0"
dart: ">=2.14.0 <3.0.0"
flutter: ">=2.0.0"
3 changes: 3 additions & 0 deletions example/pubspec.yaml
Expand Up @@ -31,6 +31,9 @@ flappy_translator:
expose_get_string: false
expose_loca_strings: false
expose_locale_maps: false
generate_comments: false
comment_languages: []


flutter:
uses-material-design: true
6 changes: 6 additions & 0 deletions lib/src/configs/default_settings.dart
Expand Up @@ -34,4 +34,10 @@ class DefaultSettings {

/// The default value for whether a localeMaps getter should be exposed
static const exposeLocaleMaps = false;

/// The default value for whether comments containing the translation should be included in the generated code
static const generateComments = false;

/// The default value for which languages to use in the generated comments. Defaults to all languages.
static const commentLanguages = <String>[];
}
17 changes: 17 additions & 0 deletions lib/src/extensions/list_extensions.dart
@@ -0,0 +1,17 @@
extension ListExtensions<E> on List<E> {
/// Maps a list of elements to a list of elements of another type.
///
/// The [predicate] filters elements that are passed to the [transform] function.
/// This does not change the order or index of the elements.
/// The [transform] function is called for each element in the list with its respective index and maps it to a new element.
List<T> mapIndexedWhere<T>(T Function(int index, E element) transform,
[bool Function(int index, E element)? predicate]) {
final result = <T>[];
for (var i = 0; i < length; i++) {
if (predicate != null ? predicate(i, this[i]) : true) {
result.add(transform(i, this[i]));
}
}
return result;
}
}
21 changes: 18 additions & 3 deletions lib/src/services/code_generation/code_generator.dart
Expand Up @@ -3,6 +3,7 @@ import 'package:dart_style/dart_style.dart';
import '../../configs/constants.dart' as constants;
import '../../configs/default_settings.dart';
import '../../utils/flappy_logger.dart';
import '../../extensions/list_extensions.dart';
import 'template.dart';

/// A service which generates I18n class and delegate using string concatenation
Expand All @@ -11,6 +12,7 @@ class CodeGenerator {
final String _quoteString;
final bool replaceNoBreakSpaces;
final _parametersRegex = RegExp(r'(\%[[0-9a-zA-Z]+]*\$(d|s))');
final List<String> _commentLanguages = [];

late String _template;
late List<Map<String, String>> _maps;
Expand Down Expand Up @@ -44,6 +46,16 @@ class CodeGenerator {
_fields = '';
}

void enableCommentGeneration([List<String> commentLanguages = const []]) {
if (commentLanguages.isEmpty) {
_commentLanguages.addAll(_supportedLanguages);
} else {
// make sure to not use languages that are not supported
_commentLanguages.addAll(_supportedLanguages
.where((supportedLang) => commentLanguages.contains(supportedLang)));
}
}

void setSupportedLanguages(List<String> supportedLanguages) {
_supportedLanguages = supportedLanguages;

Expand Down Expand Up @@ -71,7 +83,10 @@ class CodeGenerator {
}

void addField(String key, String defaultWord, List<String> words) {
var result = '';
var result = _supportedLanguages
.mapIndexedWhere((i, lang) => '/// * $lang: ${words[i]} \n',
(_, lang) => _commentLanguages.contains(lang))
.join('');
final getTextString = '_getText($_quoteString$key$_quoteString)';
final hasParameters = _parametersRegex.hasMatch(defaultWord);
if (hasParameters) {
Expand All @@ -83,7 +98,7 @@ class CodeGenerator {
'required $parameterType ${_getParameterNameFromPlaceholder(match.group(0)!)}, ';
}

result =
result +=
(!dependOnContext ? 'static ' : '') + 'String $key({$parameters}) =>';
result += getTextString;

Expand All @@ -97,7 +112,7 @@ class CodeGenerator {

result += ';\n\n';
} else {
result = (!dependOnContext ? 'static ' : '') +
result += (!dependOnContext ? 'static ' : '') +
'String get $key => $getTextString;\n\n';
}

Expand Down
7 changes: 7 additions & 0 deletions lib/src/services/flappy_translator.dart
Expand Up @@ -23,6 +23,8 @@ class FlappyTranslator {
bool? exposeGetString,
bool? exposeLocaStrings,
bool? exposeLocaleMaps,
bool? generateComments,
List<String>? commentLanguages,
}) {
final file = File(inputFilePath);
Validator.validateFile(file);
Expand All @@ -42,6 +44,8 @@ class FlappyTranslator {
exposeGetString ??= DefaultSettings.exposeGetString;
exposeLocaStrings ??= DefaultSettings.exposeLocaStrings;
exposeLocaleMaps ??= DefaultSettings.exposeLocaleMaps;
generateComments ??= DefaultSettings.generateComments;
commentLanguages ??= DefaultSettings.commentLanguages;

final codeGenerator = CodeGenerator(
className: className,
Expand All @@ -64,6 +68,9 @@ class FlappyTranslator {
final supportedLanguages = parser.supportedLanguages;
Validator.validateSupportedLanguages(supportedLanguages);
codeGenerator.setSupportedLanguages(supportedLanguages);
if (generateComments) {
codeGenerator.enableCommentGeneration(commentLanguages);
}
FlappyLogger.logProgress('Locales $supportedLanguages determined.');

final localizationsTable = parser.localizationsTable;
Expand Down
26 changes: 26 additions & 0 deletions test/extensions/list_extensions_test.dart
@@ -0,0 +1,26 @@
import 'package:flappy_translator/src/extensions/list_extensions.dart';
import 'package:test/test.dart';

void main() {
test('mapIndexedWhere', () {
expect(
['a', 'b', 'c'].mapIndexedWhere((i, e) => e).toList(), ['a', 'b', 'c']);
expect(['a', 'b', 'c'].mapIndexedWhere((i, e) => i).toList(), [0, 1, 2]);
// with filter
expect(
['aasd', 'bas', 'cas', 'a', 'asdas']
.mapIndexedWhere((i, e) => e.length)
.toList(),
[4, 3, 3, 1, 5]);
expect(
['aasd', 'bas', 'cas', 'a', 'asdas']
.mapIndexedWhere((i, e) => e, (i, e) => e.length != 3)
.toList(),
['aasd', 'a', 'asdas']);
expect(
['123456', '123', '123', '12345678', '123456']
.mapIndexedWhere((i, e) => e[i], (i, e) => e.length != 3)
.toList(),
['1', '4', '5']);
});
}

0 comments on commit b379243

Please sign in to comment.