forked from dart-lang/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yaml2json.dart
70 lines (66 loc) · 2.26 KB
/
yaml2json.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
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert' show JsonEncoder;
import 'dart:io' show File, exit, stderr;
import 'dart:isolate' show RawReceivePort;
import 'package:yaml/yaml.dart' show loadYaml;
main(List<String> rawArguments) {
var port = RawReceivePort();
bool check = false;
String? relative;
List<String> arguments = [];
for (String argument in rawArguments) {
if (argument == '--check') {
check = true;
} else if (argument.startsWith('--relative=')) {
relative = argument.substring('--relative='.length);
} else {
arguments.add(argument);
}
}
if (arguments.length != 2) {
stderr.writeln("Usage: yaml2json.dart input.yaml output.json [--check]");
exit(1);
}
Uri input = File(arguments[0]).absolute.uri;
Uri output = File(arguments[1]).absolute.uri;
String inputString = arguments[0];
String outputString = arguments[1];
if (relative != null) {
String relativeTo = File(relative).absolute.uri.toString();
if (input.toString().startsWith(relativeTo)) {
inputString = input.toString().substring(relativeTo.length);
}
if (output.toString().startsWith(relativeTo)) {
outputString = output.toString().substring(relativeTo.length);
}
}
Map yaml = loadYaml(File.fromUri(input).readAsStringSync());
Map<String, dynamic> result = <String, dynamic>{};
result["comment:0"] = "NOTE: THIS FILE IS GENERATED. DO NOT EDIT.";
result["comment:1"] =
"Instead modify '$inputString' and follow the instructions therein.";
for (String key in yaml.keys) {
result[key] = yaml[key];
}
File file = File.fromUri(output);
String text = const JsonEncoder.withIndent(" ").convert(result);
if (check) {
bool needsUpdate = true;
if (file.existsSync()) {
String existingText = file.readAsStringSync();
needsUpdate = text != existingText;
}
if (needsUpdate) {
stderr.write('''
The file $outputString is not up to date. Regenerate using
dart tools/yaml2json.dart $inputString $outputString
''');
exit(1);
}
} else {
file.writeAsStringSync(text);
}
port.close();
}