-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgen_dart.dart
77 lines (65 loc) · 2.38 KB
/
gen_dart.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
// ignore_for_file: avoid_print
import "dart:io";
Future<void> checkProtoc() async {
const command = "protoc";
const args = ["--help"];
try {
await Process.run(command, args);
} on ProcessException {
print("\nError: Could not find protoc. Please download it from the URL below and add it to your PATH");
print("https://github.com/protocolbuffers/protobuf/releases/latest");
exit(1); // could not find protoc
}
}
Future<bool> hasProtocPlugin() async {
const command = "dart";
const args = ["pub", "global", "list"];
final result = await Process.run(command, args);
return result.stdout.contains("protoc_plugin");
}
Future<void> installDartPlugin() async {
const command = "dart";
const args = ["pub", "global", "activate", "protoc_plugin"];
final result = await Process.run(command, args);
if (result.exitCode != 0) {
print("\nError: Could not install protoc_plugin from Pub");
print("Tried running: $command ${args.join(' ')}");
exit(2); // could not install protoc_plugin
}
}
extension on FileSystemEntity {
String get filename => path.replaceAll(r"\", "/").split("/").last;
}
Future<void> generateProtobuf(String inputDir, String output) async {
const command = "protoc";
final files = await Directory(inputDir).list().toList();
// For some reason, Linux does not like `./*.proto`, so we must list all files
final filenames = [
for (final file in files)
if (file.path.endsWith(".proto"))
"$inputDir/${file.filename}",
];
final args = ["--dart_out=$output", "-I", inputDir, ...filenames, "google/protobuf/timestamp.proto"];
final result = await Process.run(command, args);
if (result.exitCode != 0) {
print("\nError: Could not generate Protobuf");
print(result.stderr);
exit(3); // could not generate Protobuf
}
}
void main(List<String> args) async {
final isTest = args.contains("--test") || args.contains("-t");
print("Checking for protoc...");
await checkProtoc();
if (!await hasProtocPlugin()) {
print("Installing Dart plugin...");
await installDartPlugin();
}
print("Generating Protobuf...");
final inputDir = isTest ? "." : "Protobuf";
final outputDir = Directory(isTest ? "test_output" : "lib/src/generated");
await outputDir.create(recursive: true);
await generateProtobuf(inputDir, outputDir.path);
if (isTest) await outputDir.delete(recursive: true);
print("Done!");
}