-
-
Notifications
You must be signed in to change notification settings - Fork 141
/
tr.dart
193 lines (175 loc) · 6.99 KB
/
tr.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// ignore_for_file: avoid_print
import 'dart:convert';
import 'dart:io';
/// * Use Cases:
/// - `KEY VALUE` => Adds [KEY] and [VALUE]
/// - `KEY` => Adds [KEY] with a value identical to the key, ex: `MY_NAME` : `My name`.
/// - Appending `-r` anywhere removes the key
/// * Notes:
/// - Key is not case sensitive, ex: `my_key`, `MY_KEY` & `My_key` are all valid.
/// - Key words should be separated with underscore.
/// * NEW:
/// - now supports multiple insertions, deletions.
/// - only: `KEY` format is approved, ex: `KEY1,KEY2,KEY3`.
/// - separated by commas (,)
/// - if `KEY1,KEY2 VALUE` was used, only first key will be inserted
void main(List<String> argumentsPre) async {
final args = List<String>.from(argumentsPre);
final shouldRemove = args.remove('-r');
final argKeyhh = args[0].toUpperCase();
final argKeys = argKeyhh.split(',');
// should remove
if (shouldRemove) {
await _removeKeys(argKeys);
return;
}
// `KEY VALUE`
if (args.length == 2) {
// should add `KEY: value` normally
final value = args[1];
await _addKey({argKeys.first: value});
} else
// want to add `KEY` with identical value
// ex: `MY_NAME` : `My name`
if (args.length == 1) {
final map = <String, String>{};
for (final argKey in argKeys) {
final valuePre = argKey.replaceAll('_', ' ').toLowerCase();
final value = "${valuePre[0].toUpperCase()}${valuePre.substring(1)}";
map[argKey] = value;
}
await _addKey(map);
} else {
print('Error(Missing Arguments): Supported arguments: `KEY VALUE` | `KEY` | `KEY1,KEY2` |`-r KEY`');
}
}
Future<bool> _addKey(Map<String, String> argKeysVals) async {
try {
// -- Keys File
final file = File(_keysFilePath);
final keys = <String>[];
final stream = file.openRead();
final lines = stream.transform(utf8.decoder).transform(const LineSplitter());
await for (final line in lines) {
final regexRes = RegExp(r'(?<=String get )(.*)(?= =>)');
final match = regexRes.firstMatch(line)?[0];
if (match != null) keys.add(match);
// final pieces = line.split('String get ');
// if (pieces.length == 2) {
// final withoutSC = pieces.last.split('');
// withoutSC.removeLast();
// keys.add(withoutSC.join());
// }
}
for (final argKey in argKeysVals.keys) {
keys.insertWithOrder(argKey);
}
await file.writeAsString("""
// ignore_for_file: non_constant_identifier_names
// AUTO GENERATED FILE
abstract class LanguageKeys {
Map<String, String> get languageMap;
Map<String, String> get languageMapDefault;
String _getKey(String key) => languageMap[key] ?? languageMapDefault[key] ?? '';
${keys.map((e) => " String get $e => _getKey('$e');").join('\n')}
}
""");
// -- Controller file
// final langFile = File(_controllerFilePath);
// final langController = await langFile.readAsString();
// const splitterOne = '// -- Keys Start ---------------------------------------------------------';
// const splitterTwo = '// -- Keys End ---------------------------------------------------------';
// final firstPiece = langController.split(splitterOne).first;
// final lastPiece = langController.split(splitterTwo).last;
// final mapText = keys.map((e) => '\t\t\t$e = getKey("$e");').join('\n');
// await langFile.writeAsString("""$firstPiece$splitterOne
// $mapText
// \t\t\t$splitterTwo$lastPiece""");
// -- All Langauges files
// const encoder = JsonEncoder.withIndent(' ');
// await for (final fileSystem in Directory(_languagesDirectoryPath).list()) {
// if (fileSystem is File) {
// if (fileSystem.path.endsWith('.json')) {
// final str = await fileSystem.readAsString();
// final map = jsonDecode(str) as Map<String, dynamic>;
// map.addAll(argKeysVals);
// final sorted = Map<String, dynamic>.fromEntries(map.entries.toList()..sort((a, b) => a.key.compareTo(b.key)));
// await fileSystem.writeAsString(encoder.convert(sorted));
// }
// }
// }
print('Added ${argKeysVals.length} ${argKeysVals.length > 1 ? 'keys' : 'key'} Successfully');
return true;
} on Exception catch (e) {
print('Error Adding: $e\nRemoving Keys...');
_removeKeys(argKeysVals.keys);
return false;
}
}
Future<bool> _removeKeys(Iterable<String> keysToRemove) async {
try {
// -- Keys File
final file = File(_keysFilePath);
final lines = await file.readAsLines();
// -- reverse looping for index-related issues
for (int i = lines.length - 1; i >= 0; i--) {
final line = lines[i];
if (keysToRemove.any((keyToRemove) => line.contains("String get $keyToRemove => _getKey('$keyToRemove');"))) {
lines.removeAt(i);
}
}
await file.writeAsString('${lines.join('\n')}\n');
// -- Controller file
// final langFile = File(_controllerFilePath);
// final langController = await langFile.readAsString();
// const splitterOne = '// -- Keys Start ---------------------------------------------------------';
// const splitterTwo = '// -- Keys End ---------------------------------------------------------';
// final firstPiece = langController.split(splitterOne).first;
// final lastPiece = langController.split(splitterTwo).last;
// final oldMapText = langController.split(splitterOne).last.split(splitterTwo).first;
// final mapLines = const LineSplitter().convert(oldMapText);
// mapLines.removeWhere((element) => element.contains("$keyToRemove = "));
// await langFile.writeAsString("$firstPiece$splitterOne${mapLines.join('\n')}$splitterTwo$lastPiece");
// -- All Langauges files
// const encoder = JsonEncoder.withIndent(' ');
// await for (final fileSystem in Directory(_languagesDirectoryPath).list()) {
// if (fileSystem is File) {
// if (fileSystem.path.endsWith('.json')) {
// final str = await fileSystem.readAsString();
// final map = jsonDecode(str) as Map<String, dynamic>;
// for (final keyToRemove in keysToRemove) {
// map.remove(keyToRemove);
// }
// await fileSystem.writeAsString(encoder.convert(map));
// }
// }
// }
print('Removed Successfully');
return true;
} catch (e) {
print('Error Removing: $e');
return false;
}
}
extension OrderedInsert<T extends Comparable> on List<T> {
void insertWithOrder(T item) {
int left = 0;
int right = length - 1;
while (left <= right) {
int mid = (left + right) ~/ 2;
if (this[mid] == item) {
// -- If the string is already in the list, dont do anything
return;
} else if (this[mid].compareTo(item) < 0) {
left = mid + 1;
} else {
right = mid - 1;
}
}
// If the string is not in the list, insert it at the appropriate position
insert(left, item);
}
}
const _keysFilePath = 'lib/core/translations/keys.dart';
// const _controllerFilePath = 'lib/core/translations/language.dart';
// const _languagesDirectoryPath = 'assets/language/translations';