This repository was archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 402
/
Copy pathgit-prompt-server.js
75 lines (64 loc) · 1.86 KB
/
git-prompt-server.js
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
import net from 'net';
import {Emitter} from 'event-kit';
import {normalizeGitHelperPath} from './helpers';
export default class GitPromptServer {
constructor(gitTempDir) {
this.emitter = new Emitter();
this.gitTempDir = gitTempDir;
this.address = null;
}
async start(promptForInput) {
this.promptForInput = promptForInput;
await this.gitTempDir.ensure();
this.server = await this.startListening(this.gitTempDir.getSocketOptions());
}
getAddress() {
/* istanbul ignore if */
if (!this.address) {
throw new Error('Server is not listening');
} else if (this.address.port) {
// TCP socket
return `tcp:${this.address.port}`;
} else {
// Unix domain socket
return `unix:${normalizeGitHelperPath(this.address)}`;
}
}
startListening(socketOptions) {
return new Promise(resolve => {
const server = net.createServer({allowHalfOpen: true}, connection => {
connection.setEncoding('utf8');
let payload = '';
connection.on('data', data => {
payload += data;
});
connection.on('end', () => {
this.handleData(connection, payload);
});
});
server.listen(socketOptions, () => {
this.address = server.address();
resolve(server);
});
});
}
async handleData(connection, data) {
let query;
try {
query = JSON.parse(data);
const answer = await this.promptForInput(query);
await new Promise(resolve => {
connection.end(JSON.stringify(answer), 'utf8', resolve);
});
} catch (e) {
this.emitter.emit('did-cancel', query.pid ? {handlerPid: query.pid} : undefined);
}
}
onDidCancel(cb) {
return this.emitter.on('did-cancel', cb);
}
async terminate() {
await new Promise(resolve => this.server.close(resolve));
this.emitter.dispose();
}
}