-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli-resolver.test.ts
More file actions
554 lines (447 loc) · 18.3 KB
/
cli-resolver.test.ts
File metadata and controls
554 lines (447 loc) · 18.3 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
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
import { join } from 'path';
import { afterEach, describe, it, expect, vi, beforeEach } from 'vitest';
import { CliResolver } from '../../src/codeql/cli-resolver';
// Mock child_process
vi.mock('child_process', () => ({
execFile: vi.fn(),
}));
// Mock fs/promises
vi.mock('fs/promises', () => ({
access: vi.fn(),
readdir: vi.fn(),
readFile: vi.fn(),
}));
import { execFile } from 'child_process';
import { access, readdir, readFile } from 'fs/promises';
function createMockLogger() {
return {
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
show: vi.fn(),
dispose: vi.fn(),
channel: {},
} as any;
}
describe('CliResolver', () => {
let resolver: CliResolver;
let logger: any;
beforeEach(() => {
vi.resetAllMocks();
logger = createMockLogger();
resolver = new CliResolver(logger);
});
it('should be instantiable', () => {
expect(resolver).toBeDefined();
});
it('should resolve from CODEQL_PATH env var when set', async () => {
const originalEnv = process.env.CODEQL_PATH;
process.env.CODEQL_PATH = '/usr/local/bin/codeql';
// Mock access to succeed (file exists)
vi.mocked(access).mockResolvedValueOnce(undefined);
// Mock execFile to return a version
vi.mocked(execFile).mockImplementationOnce(
(_cmd: any, _args: any, callback: any) => {
callback(null, 'CodeQL command-line toolchain release 2.19.0.\n', '');
return {} as any;
},
);
const result = await resolver.resolve();
expect(result).toBe('/usr/local/bin/codeql');
process.env.CODEQL_PATH = originalEnv;
});
it('should cache CLI version after resolve', async () => {
const originalEnv = process.env.CODEQL_PATH;
process.env.CODEQL_PATH = '/usr/local/bin/codeql';
vi.mocked(access).mockResolvedValueOnce(undefined);
vi.mocked(execFile).mockImplementationOnce(
(_cmd: any, _args: any, callback: any) => {
callback(null, 'CodeQL command-line toolchain release 2.25.1.\n', '');
return {} as any;
},
);
await resolver.resolve();
expect(resolver.getCliVersion()).toBe('2.25.1');
process.env.CODEQL_PATH = originalEnv;
});
it('should return undefined for getCliVersion before resolve', () => {
expect(resolver.getCliVersion()).toBeUndefined();
});
it('should clear cached version on invalidateCache', async () => {
const originalEnv = process.env.CODEQL_PATH;
process.env.CODEQL_PATH = '/usr/local/bin/codeql';
vi.mocked(access).mockResolvedValue(undefined);
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callback(null, 'CodeQL CLI 2.24.3\n', '');
return {} as any;
},
);
await resolver.resolve();
expect(resolver.getCliVersion()).toBe('2.24.3');
resolver.invalidateCache();
expect(resolver.getCliVersion()).toBeUndefined();
process.env.CODEQL_PATH = originalEnv;
});
it('should cache resolved path', async () => {
const originalEnv = process.env.CODEQL_PATH;
process.env.CODEQL_PATH = '/cached/codeql';
vi.mocked(access).mockResolvedValue(undefined);
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callback(null, 'CodeQL command-line toolchain release 2.19.0.\n', '');
return {} as any;
},
);
const result1 = await resolver.resolve();
const result2 = await resolver.resolve();
expect(result1).toBe('/cached/codeql');
expect(result2).toBe('/cached/codeql');
// access should only be called once due to caching
expect(access).toHaveBeenCalledTimes(1);
process.env.CODEQL_PATH = originalEnv;
});
it('should invalidate cache when instructed', async () => {
const originalEnv = process.env.CODEQL_PATH;
process.env.CODEQL_PATH = '/cached/codeql';
vi.mocked(access).mockResolvedValue(undefined);
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callback(null, 'CodeQL command-line toolchain release 2.19.0.\n', '');
return {} as any;
},
);
await resolver.resolve();
resolver.invalidateCache();
await resolver.resolve();
// access should be called twice (once before invalidation, once after)
expect(access).toHaveBeenCalledTimes(2);
process.env.CODEQL_PATH = originalEnv;
});
it('should return undefined when no CLI is found', async () => {
const originalEnv = process.env.CODEQL_PATH;
delete process.env.CODEQL_PATH;
// All access checks fail
vi.mocked(access).mockRejectedValue(new Error('ENOENT'));
// execFile (which/command -v) also fails
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callback(new Error('not found'), '', '');
return {} as any;
},
);
const result = await resolver.resolve();
expect(result).toBeUndefined();
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('not found'));
process.env.CODEQL_PATH = originalEnv;
});
it('should fall back to PATH when CODEQL_PATH is invalid', async () => {
const originalEnv = process.env.CODEQL_PATH;
process.env.CODEQL_PATH = '/nonexistent/codeql';
// CODEQL_PATH access fails
vi.mocked(access).mockImplementation((path: any) => {
if (String(path) === '/nonexistent/codeql') return Promise.reject(new Error('ENOENT'));
return Promise.resolve(undefined as any);
});
// which/command -v succeeds
let callCount = 0;
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callCount++;
if (callCount === 1) {
// which codeql
callback(null, '/usr/local/bin/codeql\n', '');
} else {
// codeql --version
callback(null, 'CodeQL CLI 2.19.0\n', '');
}
return {} as any;
},
);
const result = await resolver.resolve();
expect(result).toBe('/usr/local/bin/codeql');
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('not a valid'));
process.env.CODEQL_PATH = originalEnv;
});
it('should be disposable', () => {
expect(() => resolver.dispose()).not.toThrow();
});
describe('parseVersionString', () => {
it('should parse legacy format', () => {
expect(CliResolver.parseVersionString(
'CodeQL command-line toolchain release 2.19.0.\n',
)).toBe('2.19.0');
});
it('should parse current format', () => {
expect(CliResolver.parseVersionString('CodeQL CLI 2.25.1\n')).toBe('2.25.1');
});
it('should parse bare version string', () => {
expect(CliResolver.parseVersionString('2.24.3')).toBe('2.24.3');
});
it('should return undefined for non-version output', () => {
expect(CliResolver.parseVersionString('no version here')).toBeUndefined();
});
});
describe('vscode-codeql distribution discovery', () => {
const storagePath = '/mock/globalStorage/github.vscode-codeql';
const binaryName = process.platform === 'win32' ? 'codeql.exe' : 'codeql';
let originalEnv: string | undefined;
beforeEach(() => {
originalEnv = process.env.CODEQL_PATH;
delete process.env.CODEQL_PATH;
// Make `which codeql` fail
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
if (String(_cmd) === 'which' || String(_cmd) === 'where') {
callback(new Error('not found'), '', '');
} else {
// codeql --version for validateBinary
callback(null, 'CodeQL CLI 2.24.2\n', '');
}
return {} as any;
},
);
// All known filesystem locations fail
vi.mocked(access).mockRejectedValue(new Error('ENOENT'));
});
afterEach(() => {
if (originalEnv === undefined) {
delete process.env.CODEQL_PATH;
} else {
process.env.CODEQL_PATH = originalEnv;
}
});
it('should resolve from distribution.json hint', async () => {
resolver = new CliResolver(logger, storagePath);
// distribution.json exists with folderIndex=3
vi.mocked(readFile).mockResolvedValueOnce(
JSON.stringify({ folderIndex: 3, release: { name: 'v2.24.2' } }),
);
// The binary at distribution3/codeql/codeql is valid
const expectedPath = join(storagePath, 'distribution3', 'codeql', binaryName);
vi.mocked(access).mockImplementation((path: any) => {
if (String(path) === expectedPath) return Promise.resolve(undefined as any);
return Promise.reject(new Error('ENOENT'));
});
const result = await resolver.resolve();
expect(result).toBe(expectedPath);
expect(logger.info).toHaveBeenCalledWith(
expect.stringContaining('vscode-codeql distribution'),
);
});
it('should fall back to directory scan when distribution.json is missing', async () => {
resolver = new CliResolver(logger, storagePath);
// distribution.json read fails
vi.mocked(readFile).mockRejectedValueOnce(new Error('ENOENT'));
// Directory listing returns distribution directories
vi.mocked(readdir).mockResolvedValueOnce([
{ name: 'distribution1', isDirectory: () => true },
{ name: 'distribution3', isDirectory: () => true },
{ name: 'distribution2', isDirectory: () => true },
{ name: 'queries', isDirectory: () => true },
{ name: 'distribution.json', isDirectory: () => false },
] as any);
// Only distribution3 has a valid binary
const expectedPath = join(storagePath, 'distribution3', 'codeql', binaryName);
vi.mocked(access).mockImplementation((path: any) => {
if (String(path) === expectedPath) return Promise.resolve(undefined as any);
return Promise.reject(new Error('ENOENT'));
});
const result = await resolver.resolve();
expect(result).toBe(expectedPath);
});
it('should scan directories sorted by descending number', async () => {
resolver = new CliResolver(logger, storagePath);
vi.mocked(readFile).mockRejectedValueOnce(new Error('ENOENT'));
vi.mocked(readdir).mockResolvedValueOnce([
{ name: 'distribution1', isDirectory: () => true },
{ name: 'distribution10', isDirectory: () => true },
{ name: 'distribution2', isDirectory: () => true },
] as any);
// All binaries are valid — should pick distribution10 (highest number)
vi.mocked(access).mockResolvedValue(undefined as any);
const result = await resolver.resolve();
expect(result).toBe(join(storagePath, 'distribution10', 'codeql', binaryName));
});
it('should return undefined when no storage path is provided', async () => {
resolver = new CliResolver(logger); // no storage path
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callback(new Error('not found'), '', '');
return {} as any;
},
);
const result = await resolver.resolve();
expect(result).toBeUndefined();
});
it('should skip distribution directories without a valid binary', async () => {
resolver = new CliResolver(logger, storagePath);
vi.mocked(readFile).mockRejectedValueOnce(new Error('ENOENT'));
vi.mocked(readdir).mockResolvedValueOnce([
{ name: 'distribution3', isDirectory: () => true },
{ name: 'distribution2', isDirectory: () => true },
{ name: 'distribution1', isDirectory: () => true },
] as any);
const expectedPath = join(storagePath, 'distribution1', 'codeql', binaryName);
vi.mocked(access).mockImplementation((path: any) => {
// Only distribution1 has the binary
if (String(path) === expectedPath) return Promise.resolve(undefined as any);
return Promise.reject(new Error('ENOENT'));
});
const result = await resolver.resolve();
expect(result).toBe(expectedPath);
});
it('should handle distribution.json with invalid JSON gracefully', async () => {
resolver = new CliResolver(logger, storagePath);
// Return non-JSON content
vi.mocked(readFile).mockResolvedValueOnce('not-valid-json');
vi.mocked(readdir).mockResolvedValueOnce([
{ name: 'distribution1', isDirectory: () => true },
] as any);
const expectedPath = join(storagePath, 'distribution1', 'codeql', binaryName);
vi.mocked(access).mockImplementation((path: any) => {
if (String(path) === expectedPath) return Promise.resolve(undefined as any);
return Promise.reject(new Error('ENOENT'));
});
const result = await resolver.resolve();
expect(result).toBe(expectedPath);
});
it('should discover CLI from alternate casing of storage path', async () => {
// Simulate the caller providing 'GitHub.vscode-codeql' (StoragePaths publisher casing)
// but the actual directory on disk is 'github.vscode-codeql' (lowercased by VS Code).
const lowercaseExtStorage = '/mock/globalStorage/github.vscode-codeql';
const publisherCaseExtStorage = '/mock/globalStorage/GitHub.vscode-codeql';
resolver = new CliResolver(logger, publisherCaseExtStorage);
// distribution.json at the publisher-cased path throws; the lowercase path returns valid JSON
vi.mocked(readFile).mockImplementation((path: any) => {
if (String(path).startsWith(publisherCaseExtStorage)) {
return Promise.reject(new Error('ENOENT'));
}
return Promise.resolve(JSON.stringify({ folderIndex: 1 }) as any);
});
const expectedPath = join(lowercaseExtStorage, 'distribution1', 'codeql', binaryName);
vi.mocked(access).mockImplementation((path: any) => {
if (String(path) === expectedPath) return Promise.resolve(undefined as any);
return Promise.reject(new Error('ENOENT'));
});
const result = await resolver.resolve();
expect(result).toBe(expectedPath);
});
it('should handle distribution.json without folderIndex property', async () => {
resolver = new CliResolver(logger, storagePath);
vi.mocked(readFile).mockResolvedValueOnce(
JSON.stringify({ release: { name: 'v2.24.2' } }),
);
vi.mocked(readdir).mockResolvedValueOnce([
{ name: 'distribution1', isDirectory: () => true },
] as any);
const expectedPath = join(storagePath, 'distribution1', 'codeql', binaryName);
vi.mocked(access).mockImplementation((path: any) => {
if (String(path) === expectedPath) return Promise.resolve(undefined as any);
return Promise.reject(new Error('ENOENT'));
});
const result = await resolver.resolve();
expect(result).toBe(expectedPath);
});
});
describe('PATH resolution version detection', () => {
let originalEnv: string | undefined;
beforeEach(() => {
originalEnv = process.env.CODEQL_PATH;
delete process.env.CODEQL_PATH;
});
afterEach(() => {
if (originalEnv === undefined) {
delete process.env.CODEQL_PATH;
} else {
process.env.CODEQL_PATH = originalEnv;
}
});
it('should detect CLI version when resolved via PATH', async () => {
// `which codeql` succeeds, then `codeql --version` returns version
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
const cmd = String(_cmd);
const args = Array.isArray(_args) ? _args : [];
if (cmd === 'which' || cmd === 'where') {
callback(null, '/usr/local/bin/codeql\n', '');
} else if (args.includes('--version')) {
callback(null, 'CodeQL CLI 2.24.1\n', '');
}
return {} as any;
},
);
vi.mocked(access).mockResolvedValue(undefined as any);
const result = await resolver.resolve();
expect(result).toBe('/usr/local/bin/codeql');
expect(resolver.getCliVersion()).toBe('2.24.1');
});
it('should fall through when PATH binary fails validation', async () => {
// `which codeql` returns a path, but --version fails
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
const cmd = String(_cmd);
if (cmd === 'which' || cmd === 'where') {
callback(null, '/broken/codeql\n', '');
} else {
callback(new Error('not a valid binary'), '', '');
}
return {} as any;
},
);
// access fails for everything (including known locations)
vi.mocked(access).mockRejectedValue(new Error('ENOENT'));
const result = await resolver.resolve();
expect(result).toBeUndefined();
expect(resolver.getCliVersion()).toBeUndefined();
});
});
describe('concurrent resolution', () => {
let originalEnv: string | undefined;
beforeEach(() => {
originalEnv = process.env.CODEQL_PATH;
process.env.CODEQL_PATH = '/usr/local/bin/codeql';
});
afterEach(() => {
if (originalEnv === undefined) {
delete process.env.CODEQL_PATH;
} else {
process.env.CODEQL_PATH = originalEnv;
}
});
it('should not duplicate resolution work for concurrent calls', async () => {
vi.mocked(access).mockResolvedValue(undefined as any);
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callback(null, 'CodeQL CLI 2.25.1\n', '');
return {} as any;
},
);
// Fire two concurrent resolve() calls
const [result1, result2] = await Promise.all([
resolver.resolve(),
resolver.resolve(),
]);
expect(result1).toBe('/usr/local/bin/codeql');
expect(result2).toBe('/usr/local/bin/codeql');
// Should only validate once, not twice
expect(access).toHaveBeenCalledTimes(1);
});
it('should allow re-resolution after invalidateCache', async () => {
vi.mocked(access).mockResolvedValue(undefined as any);
vi.mocked(execFile).mockImplementation(
(_cmd: any, _args: any, callback: any) => {
callback(null, 'CodeQL CLI 2.25.1\n', '');
return {} as any;
},
);
await resolver.resolve();
resolver.invalidateCache();
const result = await resolver.resolve();
expect(result).toBe('/usr/local/bin/codeql');
// access called twice: once before invalidation, once after
expect(access).toHaveBeenCalledTimes(2);
});
});
});