forked from atom/github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-prompt-server.js
More file actions
60 lines (49 loc) · 1.48 KB
/
git-prompt-server.js
File metadata and controls
60 lines (49 loc) · 1.48 KB
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
import net from 'net';
import {Emitter} from 'event-kit';
export default class GitPromptServer {
constructor(gitTempDir) {
this.emitter = new Emitter();
this.gitTempDir = gitTempDir;
}
async start(promptForInput) {
this.promptForInput = promptForInput;
await this.gitTempDir.ensure();
this.server = await this.startListening(this.gitTempDir.getSocketPath());
}
startListening(socketPath) {
return new Promise(resolve => {
const server = net.createServer(connection => {
connection.setEncoding('utf8');
const parts = [];
connection.on('data', data => {
const nullIndex = data.indexOf('\u0000');
if (nullIndex === -1) {
parts.push(data);
} else {
parts.push(data.substring(0, nullIndex));
this.handleData(connection, parts.join(''));
}
});
});
server.listen(socketPath, () => resolve(server));
});
}
handleData(connection, data) {
let query;
try {
query = JSON.parse(data);
} catch (e) {
this.emitter.emit('did-cancel');
}
Promise.resolve(this.promptForInput(query))
.then(answer => connection.end(JSON.stringify(answer), 'utf-8'))
.catch(() => this.emitter.emit('did-cancel', {handlerPid: query.pid}));
}
onDidCancel(cb) {
return this.emitter.on('did-cancel', cb);
}
async terminate() {
await new Promise(resolve => this.server.close(resolve));
this.emitter.dispose();
}
}