generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate_schemas.dart
53 lines (43 loc) · 1.47 KB
/
generate_schemas.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
import 'dart:io';
import 'package:path/path.dart' as p;
void main() {
final schemasPath = p.join('tbdex', 'hosted', 'json-schemas');
final outputDir = Directory('lib/src/protocol/json_schemas')
..createSync(recursive: true);
Directory(schemasPath)
.listSync()
.whereType<File>()
.where((file) => file.path.endsWith('.json'))
.forEach((file) {
final json = file.readAsStringSync();
final dartCode = _generateCode(file.path, json);
File(p.join(outputDir.path, '${_getFileName(file.path)}.dart'))
.writeAsStringSync(dartCode);
});
}
String _generateCode(String filePath, String jsonString) => '''
class ${_getClassName(filePath)} {
static const String json = r\'\'\'
$jsonString\'\'\';
}''';
String _getFileName(String filePath) {
var segments = p.split(filePath);
final index = segments.indexOf('json-schemas');
final baseName = segments[index + 1].split('.').first;
return '${_toSnakeCase(baseName)}_schema';
}
String _getClassName(String filePath) {
var segments = p.split(filePath);
final index = segments.indexOf('json-schemas');
final baseName = segments[index + 1].split('.').first;
return '${_toCamelCase(baseName)}Schema';
}
String _toSnakeCase(String input) => input.replaceAll('-', '_').toLowerCase();
String _toCamelCase(String input) => input
.split(RegExp('[_-]'))
.map(
(str) => str.isEmpty
? ''
: str[0].toUpperCase() + str.substring(1).toLowerCase(),
)
.join();