-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli-resolver.ts
More file actions
323 lines (292 loc) · 10.8 KB
/
cli-resolver.ts
File metadata and controls
323 lines (292 loc) · 10.8 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
import { execFile } from 'child_process';
import { access, readdir, readFile } from 'fs/promises';
import { constants } from 'fs';
import { dirname, join } from 'path';
import { DisposableObject } from '../common/disposable';
import type { Logger } from '../common/logger';
/** Expected binary name for the CodeQL CLI on the current platform. */
const CODEQL_BINARY_NAME = process.platform === 'win32' ? 'codeql.exe' : 'codeql';
/** Known filesystem locations where the CodeQL CLI may be installed. */
const KNOWN_LOCATIONS = [
'/usr/local/bin/codeql',
'/opt/homebrew/bin/codeql',
`${process.env.HOME}/.codeql/codeql`,
`${process.env.HOME}/codeql/codeql`,
];
/**
* Resolves the absolute path to the CodeQL CLI binary.
*
* Detection strategy (in order):
* 1. `CODEQL_PATH` environment variable
* 2. `codeql` on `$PATH` (via `which`)
* 3. `vscode-codeql` managed distribution (via `distribution.json` hint
* or directory scan of `distribution*` folders)
* 4. Known filesystem locations
*
* Results are cached. Call `invalidateCache()` when the environment changes
* (e.g. `extensions.onDidChange` fires).
*/
export class CliResolver extends DisposableObject {
private cachedPath: string | undefined | null = null; // null = not yet resolved
private cachedVersion: string | undefined;
private resolvePromise: Promise<string | undefined> | null = null;
/**
* Monotonically increasing generation counter, bumped by `invalidateCache()`.
* Used to discard results from in-flight `doResolve()` calls that started
* before the most recent invalidation.
*/
private _generation = 0;
constructor(
private readonly logger: Logger,
private readonly vsCodeCodeqlStoragePath?: string,
) {
super();
}
/**
* Get the CodeQL CLI version string (e.g. '2.25.1').
*
* Returns the cached version detected during the most recent `resolve()`,
* or `undefined` if no CLI has been resolved yet or the version could not
* be parsed.
*/
getCliVersion(): string | undefined {
return this.cachedVersion;
}
/** Resolve the CodeQL CLI path. Returns `undefined` if not found. */
async resolve(): Promise<string | undefined> {
if (this.cachedPath !== null) {
return this.cachedPath;
}
// Return the in-flight promise if a resolution is already in progress
if (this.resolvePromise) {
return this.resolvePromise;
}
this.resolvePromise = this.doResolve();
try {
return await this.resolvePromise;
} finally {
this.resolvePromise = null;
}
}
/** Internal resolution logic. Called at most once per cache cycle. */
private async doResolve(): Promise<string | undefined> {
const startGeneration = this._generation;
this.logger.debug('Resolving CodeQL CLI path...');
/**
* Check whether the cache was invalidated while an async operation
* was in flight. If so, discard any version that `validateBinary()`
* may have written and bail out immediately.
*/
const isStale = (): boolean => {
if (this._generation !== startGeneration) {
this.cachedVersion = undefined;
return true;
}
return false;
};
// Strategy 1: CODEQL_PATH env var
const envPath = process.env.CODEQL_PATH;
if (envPath) {
const validated = await this.validateBinary(envPath);
if (isStale()) return undefined;
if (validated) {
this.logger.info(`CodeQL CLI found via CODEQL_PATH: ${envPath}`);
this.cachedPath = envPath;
return envPath;
}
this.logger.warn(`CODEQL_PATH is set to '${envPath}' but it is not a valid CodeQL binary.`);
}
// Strategy 2: which/command -v
const whichPath = await this.resolveFromPath();
if (isStale()) return undefined;
if (whichPath) {
const validated = await this.validateBinary(whichPath);
if (isStale()) return undefined;
if (validated) {
this.logger.info(`CodeQL CLI found on PATH: ${whichPath}`);
this.cachedPath = whichPath;
return whichPath;
}
this.logger.warn(`Found 'codeql' on PATH at '${whichPath}' but it failed validation.`);
}
// Strategy 3: vscode-codeql managed distribution
const distPath = await this.resolveFromVsCodeDistribution();
if (isStale()) return undefined;
if (distPath) {
this.logger.info(`CodeQL CLI found via vscode-codeql distribution: ${distPath}`);
this.cachedPath = distPath;
return distPath;
}
// Strategy 4: known filesystem locations
for (const location of KNOWN_LOCATIONS) {
const validated = await this.validateBinary(location);
if (isStale()) return undefined;
if (validated) {
this.logger.info(`CodeQL CLI found at known location: ${location}`);
this.cachedPath = location;
return location;
}
}
this.logger.warn('CodeQL CLI not found. Install it or set CODEQL_PATH.');
this.cachedPath = undefined;
return undefined;
}
/** Clear the cached path so the next `resolve()` re-probes. */
invalidateCache(): void {
this.cachedPath = null;
this.cachedVersion = undefined;
this.resolvePromise = null;
this._generation++;
}
/** Check if a path exists and responds to `--version`. */
private async validateBinary(binaryPath: string): Promise<boolean> {
try {
await access(binaryPath, constants.X_OK);
const versionOutput = await this.getVersion(binaryPath);
this.cachedVersion = CliResolver.parseVersionString(versionOutput);
return true;
} catch {
return false;
}
}
/**
* Parse a version number from the `codeql --version` output.
*
* Recognises both legacy and current formats:
* - "CodeQL command-line toolchain release 2.19.0."
* - "CodeQL CLI 2.25.1"
*
* The regex looks for the last `X.Y.Z` triplet on the first line,
* which avoids matching unrelated version numbers that may appear
* earlier in error messages.
*
* Returns the bare version (e.g. '2.25.1') or `undefined` if not parseable.
*/
static parseVersionString(versionOutput: string): string | undefined {
const firstLine = versionOutput.split('\n')[0] ?? '';
const matches = [...firstLine.matchAll(/(\d+\.\d+\.\d+)/g)];
return matches.length > 0 ? matches[matches.length - 1][1] : undefined;
}
/**
* Discover the CodeQL CLI binary from the `vscode-codeql` extension's
* managed distribution directory.
*
* The `GitHub.vscode-codeql` extension downloads the CodeQL CLI into:
* `<globalStorage>/github.vscode-codeql/distribution<N>/codeql/codeql`
*
* where `<N>` is an incrementing folder index that increases each time
* the extension upgrades the CLI. A `distribution.json` file in the
* storage root contains a `folderIndex` property that identifies the
* current distribution directory. We use that as a fast-path hint and
* fall back to scanning for the highest-numbered `distribution*` folder.
*/
private async resolveFromVsCodeDistribution(): Promise<string | undefined> {
if (!this.vsCodeCodeqlStoragePath) return undefined;
const parent = dirname(this.vsCodeCodeqlStoragePath);
// VS Code stores the extension directory as either 'GitHub.vscode-codeql'
// (original publisher casing) or 'github.vscode-codeql' (lowercased by VS Code
// on some platforms/versions). Probe both to ensure discovery works on
// case-sensitive filesystems.
const candidatePaths = [
...new Set([
this.vsCodeCodeqlStoragePath,
join(parent, 'github.vscode-codeql'),
join(parent, 'GitHub.vscode-codeql'),
]),
];
for (const storagePath of candidatePaths) {
try {
// Fast path: read distribution.json for the exact folder index
const hintPath = await this.resolveFromDistributionJson(storagePath);
if (hintPath) return hintPath;
} catch {
this.logger.debug('distribution.json hint unavailable, falling back to directory scan');
}
// Fallback: scan for distribution* directories
const scanPath = await this.resolveFromDistributionScan(storagePath);
if (scanPath) return scanPath;
}
return undefined;
}
/**
* Read `distribution.json` to get the current `folderIndex` and validate
* the binary at the corresponding path.
*/
private async resolveFromDistributionJson(storagePath: string): Promise<string | undefined> {
const jsonPath = join(storagePath, 'distribution.json');
const content = await readFile(jsonPath, 'utf-8');
const data = JSON.parse(content) as { folderIndex?: number };
if (typeof data.folderIndex !== 'number') return undefined;
const binaryPath = join(
storagePath,
`distribution${data.folderIndex}`,
'codeql',
CODEQL_BINARY_NAME,
);
const validated = await this.validateBinary(binaryPath);
if (validated) {
this.logger.debug(`Resolved CLI via distribution.json (folderIndex=${data.folderIndex})`);
return binaryPath;
}
return undefined;
}
/**
* Scan for `distribution*` directories sorted by numeric suffix (highest
* first) and return the first one containing a valid `codeql` binary.
*/
private async resolveFromDistributionScan(storagePath: string): Promise<string | undefined> {
try {
const entries = await readdir(storagePath, { withFileTypes: true });
const distDirs = entries
.filter(e => e.isDirectory() && /^distribution\d+$/.test(e.name))
.map(e => ({
name: e.name,
num: parseInt(e.name.replace('distribution', ''), 10),
}))
.sort((a, b) => b.num - a.num);
for (const dir of distDirs) {
const binaryPath = join(
storagePath,
dir.name,
'codeql',
CODEQL_BINARY_NAME,
);
const validated = await this.validateBinary(binaryPath);
if (validated) {
this.logger.debug(`Resolved CLI via distribution scan: ${dir.name}`);
return binaryPath;
}
}
} catch {
this.logger.debug(
`Could not scan vscode-codeql distribution directory: ${storagePath}`,
);
}
return undefined;
}
/** Attempt to find `codeql` on PATH. */
private resolveFromPath(): Promise<string | undefined> {
return new Promise((resolve) => {
const cmd = process.platform === 'win32' ? 'where' : 'which';
execFile(cmd, ['codeql'], (err, stdout) => {
if (err || !stdout.trim()) {
resolve(undefined);
return;
}
resolve(stdout.trim().split('\n')[0]);
});
});
}
/** Run `codeql --version` to validate the binary. */
private getVersion(binaryPath: string): Promise<string> {
return new Promise((resolve, reject) => {
execFile(binaryPath, ['--version'], (err, stdout) => {
if (err) {
reject(err);
return;
}
resolve(stdout.trim());
});
});
}
}