-
-
Notifications
You must be signed in to change notification settings - Fork 223
/
Copy pathjack-in.ts
434 lines (402 loc) · 13.6 KB
/
jack-in.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import * as vscode from 'vscode';
import * as path from 'path';
import * as utilities from '../utilities';
import * as _ from 'lodash';
import * as state from '../state';
import * as connector from '../connector';
import { nClient } from '../connector';
import statusbar from '../statusbar';
import {
askForConnectSequence,
ReplConnectSequence,
CljsTypes,
getConnectSequences,
} from './connectSequence';
import * as projectTypes from './project-types';
import * as outputWindow from '../repl-window/repl-doc';
import {
JackInPTY as JackInPTY,
JackInPTYOptions as JackInPTYOptions,
createCommandLine,
} from './jack-in-terminal';
import * as liveShareSupport from '../live-share';
import { getConfig } from '../config';
import * as joyride from '../joyride';
import { ConnectType } from './connect-types';
import * as output from '../results-output/output';
import * as inspector from '../providers/inspector';
function resolveEnvVariables(entry: any): any {
if (typeof entry === 'string') {
const s = entry.replace(/\$\{env:(\w+)\}/g, (_, v) => (process.env[v] ? process.env[v] : ''));
return s;
} else {
return entry;
}
}
function processEnvObject(env: any) {
return _.mapValues(env, resolveEnvVariables);
}
function getGlobalJackInEnv() {
return {
...process.env,
...processEnvObject(getConfig().jackInEnv as object),
};
}
let jackInPTY: JackInPTY = undefined;
let jackInTerminal: vscode.Terminal = undefined;
async function executeJackInTask(
terminalOptions: JackInPTYOptions,
connectSequence: ReplConnectSequence,
cb?: () => unknown
) {
utilities.setLaunchingState(connectSequence.name);
statusbar.update();
if (!jackInPTY) {
jackInPTY = new JackInPTY();
jackInTerminal = (<any>vscode.window).createTerminal({
name: `Calva Jack-in: ${connectSequence.name}`,
pty: jackInPTY,
});
jackInPTY.onDidClose((e) => {
calvaJackout();
});
} else {
jackInPTY.clearTerminal();
}
if (getConfig().autoOpenJackInTerminal) {
jackInTerminal.show();
}
return vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: `Jacking in: ${connectSequence.name}...`,
cancellable: true,
},
(progress, token) => {
return new Promise<void>((resolve, reject) => {
try {
token.onCancellationRequested(() => {
calvaJackout();
reject(new Error('Jack-in was cancelled by the user.'));
});
void jackInPTY.startClojureProgram(
terminalOptions,
(_p, hostname: string, port: string) => {
utilities.setLaunchingState(null);
resolve();
void connector.connect(connectSequence, true, hostname, port).then(() => {
utilities.setJackedInState(true);
statusbar.update();
output.appendLineOtherOut('Jack-in done.');
output.replWindowAppendPrompt();
if (cb) {
cb();
}
});
},
(status: number) => {
setJackedOutStatus();
void vscode.window
.showErrorMessage(
`Jack-in was interrupted. Exit code: ${status}`,
'Show Jack-in Terminal'
)
.then((item) => {
if (item) {
void vscode.commands.executeCommand('calva.revealJackInTerminal');
}
});
resolve();
}
);
} catch (exception) {
console.error('Failed executing task: ', exception.message);
reject(exception);
}
});
}
);
}
function setJackedOutStatus() {
utilities.setLaunchingState(null);
utilities.setJackedInState(false);
statusbar.update();
}
export function calvaJackout() {
if (jackInPTY !== undefined) {
if (projectTypes.isWin) {
// this is a hack under Windows to terminate the
// repl process from the repl client because the
// ShellExecution under Windows will not terminate
// all child processes.
//
// the clojure code to terminate the repl process
// was taken from this comment on github:
//
// https://github.com/clojure-emacs/cider/issues/390#issuecomment-317791387
//
if (nClient && nClient.session) {
nClient.session.eval(
'(do (.start (Thread. (fn [] (Thread/sleep 5000) (shutdown-agents) (System/exit 0)))) nil)',
'user'
);
}
}
connector.default.disconnect();
jackInPTY.killProcess();
setJackedOutStatus();
}
liveShareSupport.didJackOut();
}
export function revealJackInTerminal() {
if (jackInTerminal) {
jackInTerminal.show();
}
}
export async function copyJackInCommandToClipboard(): Promise<void> {
try {
await state.initProjectDir(ConnectType.JackIn, undefined);
} catch (e) {
console.error('An error occurred while initializing project directory.', e);
return;
}
let projectConnectSequence: ReplConnectSequence;
try {
projectConnectSequence = await getProjectConnectSequence(false);
} catch (e) {
return;
}
if (projectConnectSequence) {
try {
const options = await getJackInTerminalOptions(projectConnectSequence);
if (options) {
void vscode.env.clipboard.writeText(createCommandLine(options));
const message = `Jack-in command line copied to the clipboard.${
projectTypes.isWin ? ' It is tailored for cmd.exe and may not work in other shells.' : ''
}`;
if (projectTypes.isWin) {
void vscode.window.showInformationMessage(message, 'OK');
} else {
void vscode.window.showInformationMessage(message);
}
}
} catch (e) {
void vscode.window.showErrorMessage(`Error creating Jack-in command line: ${e}`, 'OK');
}
} else {
void vscode.window.showInformationMessage('No supported project types detected.');
}
}
type Substitutions = {
[key: string]: string | string[];
};
function substituteCustomCommandLinePlaceholders(
commandLineTemplate: string,
substitutions: Substitutions
) {
return Object.keys(substitutions).reduce((acc: string, k: string) => {
const placeholder = `JACK-IN-${k}`;
const value: string = Array.isArray(substitutions[k])
? (substitutions[k] as string[]).join(',')
: (substitutions[k] as string);
return acc.replace(new RegExp(placeholder, 'g'), value);
}, commandLineTemplate);
}
async function getJackInTerminalOptions(
projectConnectSequence: ReplConnectSequence
): Promise<JackInPTYOptions> {
const projectTypeName: string = projectConnectSequence.projectType;
let selectedCljsType: CljsTypes;
if (
typeof projectConnectSequence.cljsType == 'string' &&
projectConnectSequence.cljsType != CljsTypes.none
) {
selectedCljsType = projectConnectSequence.cljsType;
} else if (
projectConnectSequence.cljsType &&
typeof projectConnectSequence.cljsType == 'object'
) {
selectedCljsType = projectConnectSequence.cljsType.dependsOn;
}
const projectType = projectTypes.getProjectTypeForName(projectTypeName);
if (!projectType?.commandLine) {
throw new Error(`Project type ${projectTypeName} does not support Jack-in.`);
}
const commandLineInfo = await projectType.commandLine(projectConnectSequence, selectedCljsType);
let args: string[] = commandLineInfo.args;
let cmd: string[];
if (projectTypes.isWin) {
cmd = typeof projectType.winCmd === 'function' ? projectType.winCmd() : projectType.winCmd;
} else {
cmd = typeof projectType.cmd === 'function' ? projectType.cmd() : projectType.cmd;
}
const nReplPortFile = projectConnectSequence.nReplPortFile ?? projectType.nReplPortFile;
const substitutions = {
'PROJECT-ROOT-PATH': state.getProjectRootLocal(),
...(nReplPortFile
? { 'NREPL-PORT-FILE': nReplPortFile.join(projectTypes.isWin ? '\\' : '/') }
: {}),
...commandLineInfo.substitutions,
};
const executable: string = projectConnectSequence.customJackInCommandLine
? substituteCustomCommandLinePlaceholders(
projectConnectSequence.customJackInCommandLine,
substitutions
)
: cmd[0];
args = projectConnectSequence.customJackInCommandLine ? [] : [...cmd.slice(1), ...args];
const terminalOptions: JackInPTYOptions = {
name: `Calva Jack-in: ${projectConnectSequence.name}`,
executable,
args,
env: {
...getGlobalJackInEnv(),
...processEnvObject(projectConnectSequence.jackInEnv),
...Object.entries(substitutions).reduce((acc, [key, value]) => {
return { ...acc, [`JACK_IN_${key.replace(/-/g, '_')}`]: value };
}, {}),
},
isWin: projectTypes.isWin,
cwd: state.getProjectRootLocal(),
useShell: projectTypes.isWin ? projectType.processShellWin : projectType.processShellUnix,
};
return terminalOptions;
}
async function getProjectConnectSequence(disableAutoSelect: boolean): Promise<ReplConnectSequence> {
const cljTypes: string[] = await projectTypes.detectProjectTypes();
const excludes = ['generic', 'cljs-only'];
if (joyride.isJoyrideExtensionActive() && joyride.isJoyrideNReplServerRunning()) {
excludes.push('joyride');
}
if (cljTypes.length > 1) {
return askForConnectSequence(
cljTypes.filter((t) => !excludes.includes(t)),
ConnectType.JackIn,
disableAutoSelect
);
}
}
async function executeJackIn(
connectSequence: ReplConnectSequence,
disableAutoSelect: boolean,
cb?: () => unknown
) {
void state.analytics().logGA4Pageview('/connect-initiated');
void state.analytics().logGA4Pageview('/connect-initiated/jack-in');
try {
await liveShareSupport.setupLiveShareListener();
} catch (e) {
console.error('An error occurred while setting up Live Share listener.', e);
}
if (state.getProjectRootUri().scheme === 'vsls') {
output.appendLineOtherErr("Aborting Jack-in, since you're the guest of a live share session.");
output.appendLineOtherOut(
'Please use this command instead: Connect to a running REPL server in the project.'
);
return;
}
inspector.revealOnConnect();
await outputWindow.initResultsDoc();
output.appendLineOtherOut('Jacking in...');
await outputWindow.openResultsDoc();
let projectConnectSequence: ReplConnectSequence = connectSequence;
if (!projectConnectSequence) {
try {
projectConnectSequence = await getProjectConnectSequence(disableAutoSelect);
} catch (e) {
output.appendLineOtherErr(`${e}\nAborting jack-in.`);
// TODO: Figure out why this is not shown to the user.
void vscode.window.showErrorMessage(e, 'OK');
return;
}
if (!projectConnectSequence) {
output.appendLineOtherErr('Aborting jack-in. No project type selected.');
return;
}
}
if (projectConnectSequence) {
const projectType = projectTypes.getProjectTypeForName(projectConnectSequence.projectType);
if (projectType.startFunction) {
void projectType.startFunction();
} else {
try {
const terminalJackInOptions = await getJackInTerminalOptions(projectConnectSequence);
if (terminalJackInOptions) {
void executeJackInTask(terminalJackInOptions, projectConnectSequence, cb);
}
} catch (e) {
void vscode.window.showErrorMessage(`Error creating jack-in command line: ${e}`, 'OK');
}
}
} else {
void vscode.window.showInformationMessage(
'No supported project types detected. Maybe try starting your project manually and use the Connect command?'
);
return;
}
void liveShareSupport.didJackIn();
}
export async function jackIn(
connectSequence: ReplConnectSequence,
disableAutoSelect: boolean,
cb?: () => unknown
): Promise<unknown> {
return new Promise((resolve, reject) => {
if (jackInPTY && !jackInPTY.isProcessAlive()) {
resolve(executeJackIn(connectSequence, disableAutoSelect, cb));
} else {
calvaJackout();
setTimeout(() => {
resolve(executeJackIn(connectSequence, disableAutoSelect, cb));
}, 1000);
}
});
}
export function jackOutCommand() {
calvaJackout();
}
export async function jackInCommand(options: {
connectSequence?: ReplConnectSequence | string;
disableAutoSelect?: boolean;
}) {
let connectSequence: ReplConnectSequence;
if (options && typeof options.connectSequence === 'string') {
connectSequence = getConnectSequences(projectTypes.getAllProjectTypes()).find(
(s) => s.name === options.connectSequence
);
} else if (options && options.connectSequence) {
connectSequence = options.connectSequence as ReplConnectSequence;
}
try {
await state.initProjectDir(ConnectType.JackIn, connectSequence, options?.disableAutoSelect);
} catch (e) {
console.error('An error occurred while initializing project directory.', e);
return;
}
await jackIn(connectSequence, options?.disableAutoSelect);
}
export function calvaDisconnect() {
if (utilities.getConnectedState()) {
connector.default.disconnect();
return;
} else if (utilities.getConnectingState() || utilities.getLaunchingState()) {
void vscode.window
.showInformationMessage(
'Do you want to interrupt the connection process?',
{ modal: true },
...['Ok']
)
.then((value) => {
if (value == 'Ok') {
calvaJackout();
connector.default.disconnect();
utilities.setLaunchingState(null);
utilities.setConnectingState(false);
statusbar.update();
output.appendLineOtherOut('Interrupting Jack-in process.');
}
});
return;
}
void vscode.window.showInformationMessage('Not connected to a REPL server');
}