-
Notifications
You must be signed in to change notification settings - Fork 31
/
configReader.ts
778 lines (632 loc) · 25 KB
/
configReader.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
import * as path from 'path';
import module from 'module';
import { readFile, fileExists, normalizePath } from './util';
import * as vscode from 'vscode';
import { glob } from 'glob';
import minimatch from 'minimatch';
import chokidar from 'chokidar';
import assert from 'assert';
import { parse as dotenvParse } from 'dotenv';
import { detectNodePath, Log } from 'vscode-test-adapter-util';
import { IDisposable, IConfigReader } from './core';
import { MochaOpts } from 'vscode-test-adapter-remoting-util/out/mocha';
import { MochaOptsReader, MochaOptsAndFiles } from './optsReader';
import { configKeys, OnChange, configSection } from './configKeys';
import { FileChangeDebouncer } from './debouncer';
export type EnvVars = { [envVar: string]: string | null };
export interface AdapterConfig {
nodePath: string | undefined;
nodeArgv: string[];
mochaPath: string;
cwd: string;
env: EnvVars;
monkeyPatch: boolean;
multiFileSuites: boolean;
pruneFiles: boolean;
debuggerPort: number;
debuggerConfig: string | undefined;
mochaOpts: MochaOpts;
testFiles: string[];
extraFiles: string[];
mochaConfigFile: string | undefined;
packageFile: string | undefined;
mochaOptsFile: string | undefined;
envFile: string | undefined;
globs: string[];
ignores: string[];
esmLoader: boolean;
launcherScript: string | undefined;
ipcRole: 'client' | 'server' | undefined;
ipcPort: number;
ipcHost: string | undefined;
ipcTimeout: number;
autoload: boolean | 'onStart';
}
interface DetailedWatcherConfig {
files: string | string[];
ignore?: string | string[];
debounce?: number;
}
interface NormalizedWatcherConfig {
files: string[];
ignore: string[];
debounce: number;
}
export class ConfigReader implements IConfigReader, IDisposable {
private disposables: IDisposable[] = [];
private enabledStateKey: string;
private watcher?: chokidar.FSWatcher;
private debouncer?: FileChangeDebouncer;
private _currentConfig: Promise<AdapterConfig | undefined> | undefined;
get currentConfig(): Promise<AdapterConfig | undefined> {
if (this._currentConfig === undefined) {
this._currentConfig = this.readConfig();
}
return this._currentConfig;
}
constructor(
private readonly workspaceFolder: vscode.WorkspaceFolder,
private readonly workspaceState: vscode.Memento,
private load: (changedFiles?: string[], reloadConfig?: boolean) => Promise<void>,
private retire: (tests?: string[]) => void,
private readonly log: Log
) {
this.enabledStateKey = `enable ${this.workspaceFolder.uri.fsPath}`;
this.disposables.push(vscode.workspace.onDidChangeConfiguration(async configChange => {
this.log.info('Configuration changed');
let configKey: string | undefined;
if (configKey = this.configChangeRequires(configChange, 'reloadTests')) {
const config = await this.currentConfig;
if (config?.autoload === true) {
if (this.log.enabled) this.log.info(`Reloading tests because ${configKey} changed`);
load();
} else {
if (this.log.enabled) this.log.info(`Reloading tests cancelled because the adapter or autoloading is disabled`);
this.reloadConfig();
retire();
}
return;
}
if (configKey = this.configChangeRequires(configChange, 'retire')) {
if (this.log.enabled) this.log.info(`Sending retire event because ${configKey} changed`);
this.reloadConfig();
retire();
return;
}
if (configKey = this.configChangeRequires(configChange, 'reloadConfig')) {
if (this.log.enabled) this.log.info(`Reloading configuration because ${configKey} changed`);
this.reloadConfig();
return;
}
}));
this.disposables.push(vscode.workspace.onDidSaveTextDocument(async document => {
this.onFileChanged(document.uri.fsPath, false);
}));
}
reloadConfig(): void {
this._currentConfig = this.readConfig();
}
async enableAdapter(): Promise<void> {
await this.workspaceState.update(this.enabledStateKey, true);
}
async disableAdapter(): Promise<void> {
await this.workspaceState.update(this.enabledStateKey, false);
}
getAutoload(config: vscode.WorkspaceConfiguration): boolean | 'onStart' {
const autoload = config.get<boolean | 'onStart'>(configKeys.autoload.key);
return (autoload !== undefined) ? autoload : true;
}
private async onFileChanged(filename: string, fromWatcher: boolean) {
const config = await this.currentConfig;
if (config?.autoload !== true) {
if (this.log.enabled) this.log.info(`Reloading cancelled because the adapter or autoloading is disabled`);
return;
}
if (this.log.enabled) this.log.info(`${filename} was saved - checking if this affects ${this.workspaceFolder.uri.fsPath}`);
const isTestFile = await this.isTestFile(filename);
if (!isTestFile && !filename.startsWith(this.workspaceFolder.uri.fsPath)) {
return;
}
if (isTestFile === 'config') {
if (!fromWatcher) {
if (this.log.enabled) this.log.info(`Reloading because ${filename} is a config file`);
this.debouncer?.reset();
this.load();
}
return;
}
if (fromWatcher) {
assert(this.debouncer);
this.debouncer.fileChanged(isTestFile ? filename : undefined);
} else if (!this.watcher) {
this.filesChangedCallback(isTestFile, isTestFile ? [ filename ] : undefined);
}
}
private filesChangedCallback(reload?: boolean, testFiles?: string[]) {
if (reload) {
if (testFiles) {
if (this.log.enabled) this.log.info(`Reloading because ${JSON.stringify(testFiles)} are test files`);
this.load(testFiles.map(normalizePath), false);
} else {
if (this.log.enabled) this.log.info('Reloading because of changed files');
this.load(undefined, false);
}
} else {
this.log.info('Sending retire event');
this.retire();
}
}
private async readConfig(): Promise<AdapterConfig | undefined> {
if (this.watcher) {
this.watcher.close();
this.watcher = undefined;
}
if (this.debouncer) {
this.debouncer.dispose();
this.debouncer = undefined;
}
const config = vscode.workspace.getConfiguration(configSection, this.workspaceFolder.uri);
if (!await this.checkEnabled(config)) {
return undefined;
}
const cwd = this.getCwd(config);
const nodePath = await this.getNodePath(config);
const nodeArgv = this.getNodeArgv(config);
let optsFromFiles: MochaOptsAndFiles;
const optsReader = new MochaOptsReader(this.log);
const defaultMochaOptsFile = 'test/mocha.opts';
let mochaOptsFile = this.getMochaOptsFile(config);
let mochaConfigFile: string | undefined;
let packageFile: string | undefined = 'package.json';
if (!mochaOptsFile) {
if (await fileExists(path.resolve(this.workspaceFolder.uri.fsPath, defaultMochaOptsFile))) {
mochaOptsFile = defaultMochaOptsFile;
}
}
if (mochaOptsFile) {
const resolvedFile = path.resolve(this.workspaceFolder.uri.fsPath, mochaOptsFile);
optsFromFiles = await optsReader.readMochaOptsFile(resolvedFile);
} else {
const argv: string[] = [];
const configFile = this.getMochaConfigFile(config);
if (configFile !== 'default') {
if (configFile === null) {
argv.push('--no-config');
} else {
mochaConfigFile = path.resolve(this.workspaceFolder.uri.fsPath, configFile);
argv.push('--config', mochaConfigFile);
}
}
const pkgFile = this.getPkgFile(config);
if (pkgFile !== 'default') {
if (pkgFile === null) {
packageFile = undefined;
argv.push('--no-package');
} else {
packageFile = path.resolve(this.workspaceFolder.uri.fsPath, pkgFile);
argv.push('--package', packageFile);
}
}
optsFromFiles = await optsReader.readOptsUsingMocha(cwd, nodePath, nodeArgv, argv);
}
const mochaOpts = await this.getMochaOpts(config, optsFromFiles.mochaOpts);
const envFile = this.getEnvFile(config);
const testFiles = await this.lookupFiles(config, optsFromFiles.globs, optsFromFiles.ignores);
const extraFiles = optsFromFiles.files
.map(file => path.resolve(this.workspaceFolder.uri.fsPath, file));
if (this.log.enabled && (extraFiles.length > 0)) {
this.log.debug(`Adding files ${JSON.stringify(extraFiles)}`);
}
const watcherConfig = this.getWatcherConfig(config);
if (watcherConfig) {
this.watcher = chokidar.watch(watcherConfig.files, {
ignored: watcherConfig.ignore,
ignoreInitial: true
});
this.debouncer = new FileChangeDebouncer(
watcherConfig.debounce,
(reload, changedFiles) => this.filesChangedCallback(reload, changedFiles)
);
this.watcher.on('add', filename => this.onFileChanged(filename, true));
this.watcher.on('change', filename => this.onFileChanged(filename, true));
this.watcher.on('unlink', filename => this.onFileChanged(filename, true));
}
return {
nodePath,
nodeArgv,
mochaPath: await this.getMochaPath(config, cwd),
cwd,
env: await this.getEnv(config, mochaOpts),
monkeyPatch: this.getMonkeyPatch(config),
multiFileSuites: this.getMultiFileSuites(config),
pruneFiles: this.getPruneFiles(config),
debuggerPort: this.getDebuggerPort(config),
debuggerConfig: this.getDebuggerConfig(config),
mochaOpts,
testFiles,
extraFiles,
mochaConfigFile,
packageFile,
mochaOptsFile,
envFile,
globs: this.getTestFilesGlobs(config, optsFromFiles.globs),
ignores: this.getIgnores(config, optsFromFiles.ignores),
esmLoader: this.getEsmLoader(config),
launcherScript: this.getLauncherScript(config),
ipcRole: this.getIpcRole(config),
ipcPort: this.getIpcPort(config),
ipcHost: this.getIpcHost(config),
ipcTimeout: this.getIpcTimeout(config),
autoload: this.getAutoload(config)
}
}
private async checkEnabled(config: vscode.WorkspaceConfiguration): Promise<boolean> {
if (this.workspaceFolder.uri.scheme !== 'file') {
return false;
}
const enabledState = this.workspaceState.get<boolean>(this.enabledStateKey);
if (enabledState !== undefined) {
return enabledState;
}
for (const configKey in configKeys) {
const configValues = config.inspect(configKey);
if (configValues && (configValues.workspaceFolderValue !== undefined)) {
await this.enableAdapter();
return true;
}
}
for (const configFile of [ '.mocharc.js', '.mocharc.json', '.mocharc.yaml', '.mocharc.yml', 'test/mocha.opts' ]) {
const resolvedConfigFile = path.resolve(this.workspaceFolder.uri.fsPath, configFile);
if (await fileExists(resolvedConfigFile)) {
await this.enableAdapter();
return true;
}
}
try {
const packageJson = JSON.parse(await readFile(path.resolve(this.workspaceFolder.uri.fsPath, 'package.json')));
if (packageJson.mocha ||
(packageJson.dependencies && packageJson.dependencies.mocha) ||
(packageJson.devDependencies && packageJson.devDependencies.mocha)) {
await this.enableAdapter();
return true;
}
} catch (err) {
}
const filePaths = await this.globFiles(config, 'test/**/*.js');
if (filePaths.length > 0) {
let msg = `The workspace folder ${this.workspaceFolder.name} contains test files, but I'm not sure if they should be run using Mocha. `;
msg += 'Do you want to enable Mocha Test Explorer for this workspace folder?';
const userChoice = await vscode.window.showInformationMessage(msg, 'Enable', 'Disable');
if (userChoice === 'Enable') {
await this.enableAdapter();
return true;
} else if (userChoice === 'Disable') {
await this.disableAdapter();
return false;
}
}
return false;
}
private getMochaConfigFile(config: vscode.WorkspaceConfiguration): string | null {
return config.get<string | null>(configKeys.configFile.key) || null;
}
private getPkgFile(config: vscode.WorkspaceConfiguration): string | null {
return config.get<string | null>(configKeys.pkgFile.key) || null;
}
private getMochaOptsFile(config: vscode.WorkspaceConfiguration): string | undefined {
const configValues = config.inspect<string>(configKeys.optsFile.key)!;
if (configValues.workspaceFolderValue !== undefined) {
return configValues.workspaceFolderValue;
} else if (configValues.workspaceValue !== undefined) {
return configValues.workspaceValue;
} else if (configValues.globalValue !== undefined) {
return configValues.globalValue;
} else {
return undefined;
}
}
private getTestFilesGlobs(config: vscode.WorkspaceConfiguration, globsFromOptsFile: string[]): string[] {
const globConfigValues = config.inspect<string | string[]>(configKeys.files.key)!;
let globFromConfig =
globConfigValues.workspaceFolderValue ||
globConfigValues.workspaceValue ||
globConfigValues.globalValue; // ?
if (globFromConfig) {
if (typeof globFromConfig === 'string') {
globFromConfig = [ globFromConfig ];
}
return [ ...globFromConfig, ...globsFromOptsFile ];
} else if (globsFromOptsFile.length > 0) {
return globsFromOptsFile;
} else {
return [ globConfigValues.defaultValue as string ]; // globalValue?
}
}
private getIgnores(config: vscode.WorkspaceConfiguration, ignoresFromOptsFile: string[]): string[] {
let ignoresFromConfig = config.get<string | string[]>(configKeys.ignore.key) || [];
if (typeof ignoresFromConfig === 'string') {
ignoresFromConfig = [ ignoresFromConfig ];
}
return [ ...ignoresFromConfig, ...ignoresFromOptsFile ];
}
private getWatcherConfig(config: vscode.WorkspaceConfiguration): NormalizedWatcherConfig | undefined {
const rawConfig = config.get<string | string[] | DetailedWatcherConfig>(configKeys.watch.key);
if (!rawConfig) {
return undefined;
}
const normalizeArray = (files: string[]) => files.map(
file => path.resolve(this.workspaceFolder.uri.fsPath, file)
);
const defaultIgnore = normalizeArray([ '**/node_modules/**' ]);
const defaultDebounce = 200;
if (typeof rawConfig === 'string') {
return {
files: normalizeArray([ rawConfig ]),
ignore: defaultIgnore,
debounce: defaultDebounce
};
} else if (Array.isArray(rawConfig)) {
return {
files: normalizeArray(rawConfig),
ignore: defaultIgnore,
debounce: defaultDebounce
};
} else {
return {
files: normalizeArray((typeof rawConfig.files === 'string') ? [ rawConfig.files ] : rawConfig.files),
ignore: normalizeArray(rawConfig.ignore ? (Array.isArray(rawConfig.ignore) ? rawConfig.ignore : [ rawConfig.ignore ]) : []),
debounce: (rawConfig.debounce === undefined) ? defaultDebounce : rawConfig.debounce
};
}
}
private async lookupFiles(
config: vscode.WorkspaceConfiguration,
globsFromOptsFile: string[],
ignoresFromOptsFile: string[]
): Promise<string[]> {
const globs = this.getTestFilesGlobs(config, globsFromOptsFile);
const ignores = this.getIgnores(config, ignoresFromOptsFile);
if (this.log.enabled) this.log.debug(`Looking for test files ${JSON.stringify(globs)} in ${this.workspaceFolder.uri.fsPath}`);
const testFiles: string[] = [];
for (let testFilesGlob of globs) {
for (const path of await this.globFiles(config, testFilesGlob)) {
if (ignores.every(ignore => !this.absolutePathMatchesRelativeGlob(path, ignore))) {
testFiles.push(path);
}
}
}
if (this.log.enabled) {
this.log.debug(`Found test files ${JSON.stringify(testFiles)}`);
}
return testFiles;
}
private async globFiles(config: vscode.WorkspaceConfiguration, relativeGlob: string) {
if (this.getGlobImplementation(config) === 'glob') {
const cwdRelativeGlob = config.cwd ? path.join(config.cwd, relativeGlob) : relativeGlob;
const absoluteGlob = normalizePath(path.resolve(this.workspaceFolder.uri.fsPath, cwdRelativeGlob));
return await new Promise<string[]>(
(resolve, reject) => glob(
absoluteGlob,
{ nodir: true },
(err, matches) => {
if (err) {
reject(err);
} else {
resolve(matches.map(normalizePath));
}
}
));
} else {
if (relativeGlob.startsWith('./')) {
relativeGlob = relativeGlob.substring(2);
}
const relativePattern = new vscode.RelativePattern(this.workspaceFolder, relativeGlob);
const fileUris = await vscode.workspace.findFiles(relativePattern, null);
return fileUris.map(uri => normalizePath(uri.fsPath));
}
}
private absolutePathMatchesRelativeGlob(absolutePath: string, relativeGlob: string): boolean {
absolutePath = normalizePath(absolutePath);
const absoluteGlob = normalizePath(path.resolve(this.workspaceFolder.uri.fsPath, relativeGlob));
return minimatch(absolutePath, absoluteGlob);
}
private async isTestFile(absolutePath: string): Promise<boolean | 'config'> {
absolutePath = normalizePath(absolutePath);
if (!absolutePath.startsWith(normalizePath(this.workspaceFolder.uri.fsPath))) {
return false;
}
const settingsPath = normalizePath(path.resolve(this.workspaceFolder.uri.fsPath, '.vscode/settings.json'));
if (absolutePath === settingsPath) {
return false;
}
const config = await this.currentConfig;
if (!config?.mochaConfigFile) {
for (const configFile of [ '.mocharc.js', '.mocharc.json', '.mocharc.yaml', '.mocharc.yml' ]) {
const resolvedConfigFile = path.resolve(this.workspaceFolder.uri.fsPath, configFile);
if (absolutePath === resolvedConfigFile) {
return 'config';
}
}
}
if (!config) {
const testFolderPath = normalizePath(path.resolve(this.workspaceFolder.uri.fsPath, 'test'));
return absolutePath.startsWith(testFolderPath);
}
for (const configFile of [ config.mochaConfigFile, config.packageFile, config.mochaOptsFile, config.envFile, config.launcherScript ]) {
if (configFile) {
const resolvedConfigFile = normalizePath(path.resolve(this.workspaceFolder.uri.fsPath, configFile));
if (absolutePath === resolvedConfigFile) {
return 'config';
}
}
}
const globs = config.globs;
for (const relativeGlob of globs) {
const absoluteGlob = normalizePath(path.resolve(this.workspaceFolder.uri.fsPath, relativeGlob));
if (minimatch(absolutePath, absoluteGlob) &&
config.ignores.every(ignore => !this.absolutePathMatchesRelativeGlob(absolutePath, ignore))) {
return true;
}
}
for (const file of config.extraFiles) {
if (absolutePath === file) {
return true;
}
}
return false;
}
private async getEnv(config: vscode.WorkspaceConfiguration, mochaOpts: MochaOpts): Promise<EnvVars> {
let resultEnv: EnvVars = config.get(configKeys.env.key) || {};
if (this.log.enabled) this.log.debug(`Using environment variables from config: ${JSON.stringify(resultEnv)}`);
let envPath: string | undefined = config.get<string>(configKeys.envPath.key);
if (envPath) {
envPath = path.resolve(this.workspaceFolder.uri.fsPath, envPath);
if (this.log.enabled) this.log.debug(`Reading environment variables from ${envPath}`);
try {
const dotenvFile = await readFile(envPath);
resultEnv = { ...dotenvParse(dotenvFile), ...resultEnv };
} catch (e) {
const envPathSettings = config.inspect<string>(configKeys.envPath.key);
if (envPathSettings?.workspaceFolderValue || envPathSettings?.workspaceValue) {
throw e;
} else {
if (this.log.enabled) this.log.info(`Ignoring globally configured envPath because ${envPath} can't be read`);
}
}
}
// workaround for esm not working when mocha is loaded programmatically (see #12)
if ((mochaOpts.requires.indexOf('esm') >= 0) && !resultEnv.hasOwnProperty('NYC_ROOT_ID')) {
resultEnv['NYC_ROOT_ID'] = '';
}
return resultEnv;
}
private getCwd(config: vscode.WorkspaceConfiguration): string {
const dirname = normalizePath(this.workspaceFolder.uri.fsPath);
const configCwd = config.get<string>(configKeys.cwd.key);
const cwd = configCwd ? path.resolve(dirname, configCwd) : dirname;
if (this.log.enabled) this.log.debug(`Using working directory: ${cwd}`);
return cwd;
}
private async getMochaOpts(config: vscode.WorkspaceConfiguration, mochaOptsFromFile: Partial<MochaOpts>): Promise<MochaOpts> {
let requires = this.mergeOpts<string | string[]>(configKeys.require.key, mochaOptsFromFile.requires, config);
if (typeof requires === 'string') {
if (requires.length > 0) {
requires = [ requires ];
} else {
requires = [];
}
} else if (typeof requires === 'undefined') {
requires = [];
}
const mochaOpts = {
ui: this.mergeOpts<string>(configKeys.ui.key, mochaOptsFromFile.ui, config),
timeout: this.mergeOpts<number>(configKeys.timeout.key, mochaOptsFromFile.timeout, config),
retries: this.mergeOpts<number>(configKeys.retries.key, mochaOptsFromFile.retries, config),
requires,
delay: this.mergeOpts<boolean>(configKeys.delay.key, mochaOptsFromFile.delay, config),
fullTrace: this.mergeOpts<boolean>(configKeys.fullTrace.key, mochaOptsFromFile.fullTrace, config),
exit: this.mergeOpts<boolean>(configKeys.exit.key, mochaOptsFromFile.exit, config),
asyncOnly: this.mergeOpts<boolean>(configKeys.asyncOnly.key, mochaOptsFromFile.asyncOnly, config),
parallel: this.mergeOpts<boolean>(configKeys.parallel.key, mochaOptsFromFile.parallel, config),
jobs: this.mergeOpts<number | null>(configKeys.jobs.key, mochaOptsFromFile.jobs, config) || undefined
}
if (this.log.enabled) this.log.debug(`Using Mocha options: ${JSON.stringify(mochaOpts)}`);
return mochaOpts;
}
private mergeOpts<T>(configKey: string, fileConfigValue: T | undefined, config: vscode.WorkspaceConfiguration): T {
const vsCodeConfigValues = config.inspect<T>(configKey)!;
if (vsCodeConfigValues.workspaceFolderValue !== undefined) {
return vsCodeConfigValues.workspaceFolderValue;
} else if (vsCodeConfigValues.workspaceValue !== undefined) {
return vsCodeConfigValues.workspaceValue;
} else if (vsCodeConfigValues.globalValue !== undefined) {
return vsCodeConfigValues.globalValue;
} else if (fileConfigValue !== undefined) {
return fileConfigValue;
} else {
return vsCodeConfigValues.defaultValue!;
}
}
private async getMochaPath(config: vscode.WorkspaceConfiguration, cwd: string): Promise<string> {
const configuredMochaPath = config.get<string | null>(configKeys.mochaPath.key);
if (configuredMochaPath === 'default') {
const cwdRequire = module.createRequire(path.join(cwd, "index.js"));
try {
return path.dirname(cwdRequire.resolve('mocha'));
} catch {}
} else if (configuredMochaPath) {
return path.resolve(this.workspaceFolder.uri.fsPath, configuredMochaPath);
}
return path.dirname(require.resolve('mocha'));
}
private async getNodePath(config: vscode.WorkspaceConfiguration): Promise<string | undefined> {
let nodePath = config.get<string | null>(configKeys.nodePath.key) || undefined;
if (nodePath === 'default') {
nodePath = await detectNodePath();
}
if (this.log.enabled) this.log.debug(`Using nodePath: ${nodePath}`);
return nodePath;
}
private getNodeArgv(config: vscode.WorkspaceConfiguration): string[] {
return config.get<string[]>(configKeys.nodeArgv.key) || [];
}
private getMonkeyPatch(config: vscode.WorkspaceConfiguration): boolean {
let monkeyPatch = config.get<boolean>(configKeys.monkeyPatch.key);
return (monkeyPatch !== undefined) ? monkeyPatch : true;
}
private getMultiFileSuites(config: vscode.WorkspaceConfiguration): boolean {
return config.get<boolean>(configKeys.multiFileSuites.key) || false;
}
private getDebuggerPort(config: vscode.WorkspaceConfiguration): number {
return config.get<number>(configKeys.debuggerPort.key) || 9229;
}
private getDebuggerConfig(config: vscode.WorkspaceConfiguration): string | undefined {
return config.get<string>(configKeys.debuggerConfig.key) || undefined;
}
private getPruneFiles(config: vscode.WorkspaceConfiguration): boolean {
return config.get<boolean>(configKeys.pruneFiles.key) || false;
}
private getEsmLoader(config: vscode.WorkspaceConfiguration): boolean {
const esmLoader = config.get<boolean>(configKeys.esmLoader.key);
return (esmLoader !== undefined) ? esmLoader : true;
}
private getEnvFile(config: vscode.WorkspaceConfiguration): string | undefined {
return config.get<string>(configKeys.envPath.key) || undefined;
}
private getGlobImplementation(config: vscode.WorkspaceConfiguration): 'glob' | 'vscode' {
return config.get<'glob' | 'vscode'>(configKeys.globImplementation.key) || 'glob';
}
private getLauncherScript(config: vscode.WorkspaceConfiguration): string | undefined {
return config.get<string>(configKeys.launcherScript.key) || undefined;
}
private getIpcRole(config: vscode.WorkspaceConfiguration): 'client' | 'server' | undefined {
return config.get<'client' | 'server' | null>('ipcRole') || undefined;
}
private getIpcPort(config: vscode.WorkspaceConfiguration): number {
return config.get<number>('ipcPort') || 9449;
}
private getIpcHost(config: vscode.WorkspaceConfiguration): string | undefined {
return config.get<string | null>('ipcHost') || undefined;
}
private getIpcTimeout(config: vscode.WorkspaceConfiguration): number {
return config.get<number>('ipcTimeout') || 5000;
}
private configChangeRequires(configChange: vscode.ConfigurationChangeEvent, action: OnChange): string | undefined {
for (const configKeyInfo of Object.values(configKeys)) {
if ((configKeyInfo.onChange === action) && configChange.affectsConfiguration(configKeyInfo.fullKey, this.workspaceFolder.uri)) {
return configKeyInfo.fullKey;
}
}
return undefined;
}
dispose(): void {
if (this.watcher) {
this.watcher.close();
this.watcher = undefined;
}
for (const disposable of this.disposables) {
disposable.dispose();
}
this.disposables = [];
}
}