Skip to content

Instantly share code, notes, and snippets.

@Zfinix
Created June 25, 2021 01:58
Show Gist options
  • Select an option

  • Save Zfinix/85b269c34dc9df00691c85beffd2f54e to your computer and use it in GitHub Desktop.

Select an option

Save Zfinix/85b269c34dc9df00691c85beffd2f54e to your computer and use it in GitHub Desktop.
import 'dart:convert';
import 'dart:io';
/// This script finds all i18n Strings and removes multiple instances
void main(List<String> args) async {
Directory? dir;
if (args.isNotEmpty) {
final argPath = args.first;
dir = Directory(argPath);
if (dir.existsSync() == false) {
print('Invalid Directory');
return;
}
}
final allStrings = await findI18n(directory: dir);
final map = <String?, String?>{};
allStrings.forEach((e) {
map.putIfAbsent(e, () => e);
});
final json = prettyJson(map);
await File('en.json').writeAsString(json
.replaceAll(r"\\'", "'")
.replaceAll(r'\\n', r'\n')
.replaceAll(r'\\\', r'\'));
}
/// Find i18n Strings
Future<List<String?>> findI18n({
Directory? directory,
}) async {
var list = <String?>[];
final dir = directory ?? Directory('.');
final raw = dir.list(recursive: true).where(
(e) => e.path.endsWith('.dart'),
);
await for (var f in raw) {
final contents = await File(f.path).readAsString();
final regexString = r'''(?:'|")((?:\w|\\(?:'|")\{).+)(?:'|")\s*\.tr\(''';
final regExp = RegExp(regexString);
var replaceAll = contents;
var matches = regExp.allMatches(replaceAll).toList();
if (matches.isNotEmpty) {
list.addAll(matches.map((e) => e.group(1)).toList());
}
}
return list;
}
/// Prettify JSON
String prettyJson(dynamic json, {int indent = 2}) {
var spaces = ' ' * indent;
var encoder = JsonEncoder.withIndent(spaces);
return encoder.convert(json);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment