-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathgenerate_lexicon_ids.dart
114 lines (88 loc) · 2.83 KB
/
generate_lexicon_ids.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
// Dart imports:
import 'dart:convert';
import 'dart:io';
// Project imports:
import 'utils.dart';
const packages = {
'atproto': ['com.atproto'],
'bluesky': ['app.bsky', 'chat.bsky'],
};
final _header = getFileHeader('Lexicon IDs Generator');
const _idsFileName = 'ids.g.dart';
const _nsidsFileName = 'nsids.g.dart';
void main() {
final fields = _getFields();
for (final entry in packages.entries) {
final package = entry.key;
final ids = StringBuffer()..writeln(_header);
final nsids = StringBuffer()
..writeln(_header)
..writeln()
..writeln('// Package imports:')
..writeln("import 'package:atproto_core/atproto_core.dart';")
..writeln()
..writeln('// Project imports:')
..writeln("import '$_idsFileName' as ids;");
for (final lexicon in entry.value) {
for (final field in fields) {
if (!field.value.startsWith(lexicon)) continue;
ids
..writeln()
..writeln('/// `${field.value}`')
..writeln("const ${field.name} = '${field.value}';");
if (!field.value.split('#').first.endsWith('defs')) {
nsids
..writeln()
..writeln('/// `${field.value}`')
..writeln("const ${field.name} = NSID(ids.${field.name});");
}
}
}
File('./packages/$package/lib/src/$_idsFileName')
.writeAsStringSync(ids.toString());
File('./packages/$package/lib/src/$_nsidsFileName')
.writeAsStringSync(nsids.toString());
}
}
List<Field> _getFields() {
final fields = <Field>[];
for (final root in lexiconsRoot) {
final directory = Directory('$lexiconsPath/$root');
for (final lexiconPath in directory.listSync()) {
for (final lexicon in Directory(lexiconPath.path).listSync()) {
final lexiconFile = File(lexicon.path);
final json = jsonDecode(lexiconFile.readAsStringSync());
final String id = json['id'];
final fieldName = _toFieldName(id);
fields.add(Field(fieldName, id));
final Map<String, dynamic> defs = json['defs'];
defs.forEach((key, _) {
if (key != 'main') {
fields.add(
Field(
'$fieldName${_toFirstUpperCase(key)}',
'$id#$key',
),
);
}
});
}
}
}
fields.sort((a, b) => a.name.compareTo(b.name));
return fields;
}
String _toFieldName(final String id) =>
id.split('.').map(_toFirstUpperCase).join().replaceFirstMapped(
RegExp(r'^\w'),
(match) => match[0]!.toLowerCase(),
);
String _toFirstUpperCase(final String value) =>
value.substring(0, 1).toUpperCase() + value.substring(1);
class Field {
Field(this.name, this.value);
final String name;
final String value;
@override
String toString() => 'Field(name: $name, value: $value);';
}