-
Notifications
You must be signed in to change notification settings - Fork 0
/
reproto.ts
117 lines (94 loc) · 3.14 KB
/
reproto.ts
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
import { spawn, ExecFileOptions } from "child_process";
import { OutputChannel } from "vscode";
export class Reproto {
readonly path: string;
readonly rootPath?: string;
constructor(path: string, rootPath?: string) {
this.path = path;
this.rootPath = rootPath;
}
/**
* Execute the given command, and log output to the given channel.
*/
private executeLogged(
args: string[],
out: OutputChannel
): Promise<void> {
out.show();
return new Promise((resolve, reject) => {
const opts: ExecFileOptions = { cwd: this.rootPath };
const c = spawn(this.path, args, opts);
let buffer = "";
c.stdout.on("data", (data: string) => {
buffer += data;
while (true) {
const index = buffer.indexOf('\n');
if (index < 0) {
break;
}
let json = buffer.substring(0, index);
buffer = buffer.substring(index + 1);
try {
json = JSON.parse(json);
} catch (e) {
c.emit('error', new Error(`illegal json on stdout: ${e}`));
continue;
}
c.emit('json', json);
}
});
c.on('json', (json: any) => {
if (json["type"] === "log") {
out.appendLine(json["level"] + ": " + json["message"]);
}
});
c.on("error", reject);
c.on("close", (code) => {
if (code !== 0) {
reject(new Error(`command exited with non-zero exit status: ${code}`));
} else {
if (out) {
resolve();
} else {
resolve();
}
}
});
});
}
/**
* Execute the given command and capture stdout.
*
* @param command Command to execute.
*/
private execute(args: string[]): Promise<string> {
return new Promise((resolve, reject) => {
const opts: ExecFileOptions = { cwd: this.rootPath };
const c = spawn(this.path, args, opts);
let buffer = "";
c.stdout.on("data", (data: string) => {
buffer += data;
c.emit("buffer");
});
c.on("close", (code: number) => {
if (code !== 0) {
reject(new Error(`command exited with non-zero exit status: ${code}`));
} else {
resolve(buffer);
}
});
});
}
/**
* Run `reproto --version` do determine which version it is.
*/
version(): Promise<string> {
return this.execute(["--version"]).then(out => out.trim());
}
init(out: OutputChannel): Promise<void> {
return this.executeLogged(["--output-format", "json", "init"], out);
}
toString(): string {
return this.path;
}
}