-
Notifications
You must be signed in to change notification settings - Fork 189
/
cli.ts
1843 lines (1686 loc) · 56.1 KB
/
cli.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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { EOL } from "os";
import { spawn } from "child-process-promise";
import * as child_process from "child_process";
import { readFile } from "fs-extra";
import { dirname, join, delimiter } from "path";
import * as sarif from "sarif";
import { SemVer } from "semver";
import { Readable } from "stream";
import tk from "tree-kill";
import { promisify } from "util";
import { CancellationToken, Disposable, Uri } from "vscode";
import { BQRSInfo, DecodedBqrsChunk } from "../common/bqrs-cli-types";
import { allowCanaryQueryServer, CliConfig } from "../config";
import {
DistributionProvider,
FindDistributionResultKind,
} from "./distribution";
import {
assertNever,
getChildProcessErrorMessage,
getErrorMessage,
getErrorStack,
} from "../common/helpers-pure";
import { walkDirectory } from "../common/files";
import { QueryMetadata, SortDirection } from "../common/interface-types";
import { BaseLogger, Logger } from "../common/logging";
import { ProgressReporter } from "../common/logging/vscode";
import { CompilationMessage } from "../query-server/legacy-messages";
import { sarifParser } from "../common/sarif-parser";
import { App } from "../common/app";
import { QueryLanguage } from "../common/query-language";
import { LINE_ENDINGS, splitStreamAtSeparators } from "../common/split-stream";
/**
* The version of the SARIF format that we are using.
*/
const SARIF_FORMAT = "sarifv2.1.0";
/**
* The string used to specify CSV format.
*/
const CSV_FORMAT = "csv";
/**
* Flags to pass to all cli commands.
*/
const LOGGING_FLAGS = ["-v", "--log-to-stderr"];
/**
* The expected output of `codeql resolve library-path`.
*/
export interface QuerySetup {
libraryPath: string[];
dbscheme: string;
relativeName?: string;
compilationCache?: string;
}
/**
* The expected output of `codeql resolve queries --format bylanguage`.
*/
export interface QueryInfoByLanguage {
// Using `unknown` as a placeholder. For now, the value is only ever an empty object.
byLanguage: Record<string, Record<string, unknown>>;
noDeclaredLanguage: Record<string, unknown>;
multipleDeclaredLanguages: Record<string, unknown>;
}
/**
* The expected output of `codeql resolve database`.
*/
export interface DbInfo {
sourceLocationPrefix: string;
columnKind: string;
unicodeNewlines: boolean;
sourceArchiveZip: string;
sourceArchiveRoot: string;
datasetFolder: string;
logsFolder: string;
languages: string[];
}
/**
* The expected output of `codeql resolve upgrades`.
*/
export interface UpgradesInfo {
scripts: string[];
finalDbscheme: string;
matchesTarget?: boolean;
}
/**
* The expected output of `codeql resolve qlpacks`.
*/
export type QlpacksInfo = { [name: string]: string[] };
/**
* The expected output of `codeql resolve languages`.
*/
export type LanguagesInfo = { [name: string]: string[] };
/** Information about an ML model, as resolved by `codeql resolve ml-models`. */
export type MlModelInfo = {
checksum: string;
path: string;
};
/** The expected output of `codeql resolve ml-models`. */
export type MlModelsInfo = { models: MlModelInfo[] };
/** Information about a data extension predicate, as resolved by `codeql resolve extensions`. */
export type DataExtensionResult = {
predicate: string;
file: string;
index: number;
};
/** The expected output of `codeql resolve extensions`. */
export type ResolveExtensionsResult = {
models: MlModelInfo[];
data: {
[path: string]: DataExtensionResult[];
};
};
export type GenerateExtensiblePredicateMetadataResult = {
// There are other properties in this object, but they are
// not relevant for its use in the extension, so we omit them.
extensible_predicates: Array<{
// pack relative path
path: string;
}>;
};
/**
* The expected output of `codeql resolve qlref`.
*/
export type QlrefInfo = { resolvedPath: string };
// `codeql bqrs interpret` requires both of these to be present or
// both absent.
export interface SourceInfo {
sourceArchive: string;
sourceLocationPrefix: string;
}
/**
* The expected output of `codeql resolve queries`.
*/
export type ResolvedQueries = string[];
/**
* The expected output of `codeql resolve tests`.
*/
export type ResolvedTests = string[];
/**
* Event fired by `codeql test run`.
*/
export interface TestCompleted {
test: string;
pass: boolean;
messages: CompilationMessage[];
compilationMs: number;
evaluationMs: number;
expected: string;
actual?: string;
diff: string[] | undefined;
failureDescription?: string;
failureStage?: string;
}
/**
* Optional arguments for the `bqrsDecode` function
*/
interface BqrsDecodeOptions {
/** How many results to get. */
pageSize?: number;
/** The 0-based index of the first result to get. */
offset?: number;
/** The entity names to retrieve from the bqrs file. Default is url, string */
entities?: string[];
}
export type OnLineCallback = (
line: string,
) => Promise<string | undefined> | string | undefined;
type VersionChangedListener = (newVersion: SemVer | undefined) => void;
/**
* This class manages a cli server started by `codeql execute cli-server` to
* run commands without the overhead of starting a new java
* virtual machine each time. This class also controls access to the server
* by queueing the commands sent to it.
*/
export class CodeQLCliServer implements Disposable {
/** The process for the cli server, or undefined if one doesn't exist yet */
process?: child_process.ChildProcessWithoutNullStreams;
/** Queue of future commands*/
commandQueue: Array<() => void>;
/** Whether a command is running */
commandInProcess: boolean;
/** A buffer with a single null byte. */
nullBuffer: Buffer;
/** Version of current cli, lazily computed by the `getVersion()` method */
private _version: SemVer | undefined;
private _versionChangedListeners: VersionChangedListener[] = [];
/**
* The languages supported by the current version of the CLI, computed by `getSupportedLanguages()`.
*/
private _supportedLanguages: string[] | undefined;
/** Path to current codeQL executable, or undefined if not running yet. */
codeQlPath: string | undefined;
cliConstraints = new CliVersionConstraint(this);
/**
* When set to true, ignore some modal popups and assume user has clicked "yes".
*/
public quiet = false;
constructor(
private readonly app: App,
private distributionProvider: DistributionProvider,
private cliConfig: CliConfig,
public readonly logger: Logger,
) {
this.commandQueue = [];
this.commandInProcess = false;
this.nullBuffer = Buffer.alloc(1);
if (this.distributionProvider.onDidChangeDistribution) {
this.distributionProvider.onDidChangeDistribution(() => {
this.restartCliServer();
this._version = undefined;
this._supportedLanguages = undefined;
});
}
if (this.cliConfig.onDidChangeConfiguration) {
this.cliConfig.onDidChangeConfiguration(() => {
this.restartCliServer();
this._version = undefined;
this._supportedLanguages = undefined;
});
}
}
dispose(): void {
this.killProcessIfRunning();
}
killProcessIfRunning(): void {
if (this.process) {
// Tell the Java CLI server process to shut down.
void this.logger.log("Sending shutdown request");
try {
this.process.stdin.write(JSON.stringify(["shutdown"]), "utf8");
this.process.stdin.write(this.nullBuffer);
void this.logger.log("Sent shutdown request");
} catch (e) {
// We are probably fine here, the process has already closed stdin.
void this.logger.log(
`Shutdown request failed: process stdin may have already closed. The error was ${e}`,
);
void this.logger.log("Stopping the process anyway.");
}
// Close the stdin and stdout streams.
// This is important on Windows where the child process may not die cleanly.
this.process.stdin.end();
this.process.kill();
this.process.stdout.destroy();
this.process.stderr.destroy();
this.process = undefined;
}
}
/**
* Restart the server when the current command terminates
*/
restartCliServer(): void {
const callback = (): void => {
try {
this.killProcessIfRunning();
} finally {
this.runNext();
}
};
// If the server is not running a command run this immediately
// otherwise add to the front of the queue (as we want to run this after the next command()).
if (this.commandInProcess) {
this.commandQueue.unshift(callback);
} else {
callback();
}
}
/**
* Get the path to the CodeQL CLI distribution, or throw an exception if not found.
*/
private async getCodeQlPath(): Promise<string> {
const codeqlPath =
await this.distributionProvider.getCodeQlPathWithoutVersionCheck();
if (!codeqlPath) {
throw new Error("Failed to find CodeQL distribution.");
}
return codeqlPath;
}
/**
* Launch the cli server
*/
private async launchProcess(): Promise<child_process.ChildProcessWithoutNullStreams> {
const codeQlPath = await this.getCodeQlPath();
const args = [];
if (shouldDebugCliServer()) {
args.push(
"-J=-agentlib:jdwp=transport=dt_socket,address=localhost:9012,server=n,suspend=y,quiet=y",
);
}
return spawnServer(
codeQlPath,
"CodeQL CLI Server",
["execute", "cli-server"],
args,
this.logger,
(_data) => {
/**/
},
);
}
private async runCodeQlCliInternal(
command: string[],
commandArgs: string[],
description: string,
onLine?: OnLineCallback,
silent?: boolean,
): Promise<string> {
const stderrBuffers: Buffer[] = [];
if (this.commandInProcess) {
throw new Error("runCodeQlCliInternal called while cli was running");
}
this.commandInProcess = true;
try {
//Launch the process if it doesn't exist
if (!this.process) {
this.process = await this.launchProcess();
}
// Grab the process so that typescript know that it is always defined.
const process = this.process;
// The array of fragments of stdout
const stdoutBuffers: Buffer[] = [];
// Compute the full args array
const args = command.concat(LOGGING_FLAGS).concat(commandArgs);
const argsString = args.join(" ");
// If we are running silently, we don't want to print anything to the console.
if (!silent) {
void this.logger.log(
`${description} using CodeQL CLI: ${argsString}...`,
);
}
try {
await new Promise<void>((resolve, reject) => {
// Start listening to stdout
process.stdout.addListener("data", (newData: Buffer) => {
if (onLine) {
void (async () => {
const response = await onLine(newData.toString("utf-8"));
if (!response) {
return;
}
process.stdin.write(`${response}${EOL}`);
// Remove newData from stdoutBuffers because the data has been consumed
// by the onLine callback.
stdoutBuffers.splice(stdoutBuffers.indexOf(newData), 1);
})();
}
stdoutBuffers.push(newData);
// If the buffer ends in '0' then exit.
// We don't have to check the middle as no output will be written after the null until
// the next command starts
if (
newData.length > 0 &&
newData.readUInt8(newData.length - 1) === 0
) {
resolve();
}
});
// Listen to stderr
process.stderr.addListener("data", (newData: Buffer) => {
stderrBuffers.push(newData);
});
// Listen for process exit.
process.addListener("close", (code) => reject(code));
// Write the command followed by a null terminator.
process.stdin.write(JSON.stringify(args), "utf8");
process.stdin.write(this.nullBuffer);
});
// Join all the data together
const fullBuffer = Buffer.concat(stdoutBuffers);
// Make sure we remove the terminator;
const data = fullBuffer.toString("utf8", 0, fullBuffer.length - 1);
if (!silent) {
void this.logger.log("CLI command succeeded.");
}
return data;
} catch (err) {
// Kill the process if it isn't already dead.
this.killProcessIfRunning();
// Report the error (if there is a stderr then use that otherwise just report the error code or nodejs error)
const newError =
stderrBuffers.length === 0
? new Error(
`${description} failed with args:${EOL} ${argsString}${EOL}${err}`,
)
: new Error(
`${description} failed with args:${EOL} ${argsString}${EOL}${Buffer.concat(
stderrBuffers,
).toString("utf8")}`,
);
newError.stack += getErrorStack(err);
throw newError;
} finally {
if (!silent) {
void this.logger.log(Buffer.concat(stderrBuffers).toString("utf8"));
}
// Remove the listeners we set up.
process.stdout.removeAllListeners("data");
process.stderr.removeAllListeners("data");
process.removeAllListeners("close");
}
} finally {
this.commandInProcess = false;
// start running the next command immediately
this.runNext();
}
}
/**
* Run the next command in the queue
*/
private runNext(): void {
const callback = this.commandQueue.shift();
if (callback) {
callback();
}
}
/**
* Runs an asynchronous CodeQL CLI command without invoking the CLI server, returning any events
* fired by the command as an asynchronous generator.
*
* @param command The `codeql` command to be run, provided as an array of command/subcommand names.
* @param commandArgs The arguments to pass to the `codeql` command.
* @param cancellationToken CancellationToken to terminate the test process.
* @param logger Logger to write text output from the command.
* @returns The sequence of async events produced by the command.
*/
private async *runAsyncCodeQlCliCommandInternal(
command: string[],
commandArgs: string[],
cancellationToken?: CancellationToken,
logger?: BaseLogger,
): AsyncGenerator<string, void, unknown> {
// Add format argument first, in case commandArgs contains positional parameters.
const args = [...command, "--format", "jsonz", ...commandArgs];
// Spawn the CodeQL process
const codeqlPath = await this.getCodeQlPath();
const childPromise = spawn(codeqlPath, args);
// Avoid a runtime message about unhandled rejection.
childPromise.catch(() => {
/**/
});
const child = childPromise.childProcess;
let cancellationRegistration: Disposable | undefined = undefined;
try {
if (cancellationToken !== undefined) {
cancellationRegistration = cancellationToken.onCancellationRequested(
(_e) => {
tk(child.pid || 0);
},
);
}
if (logger !== undefined) {
// The human-readable output goes to stderr.
void logStream(child.stderr!, logger);
}
for await (const event of splitStreamAtSeparators(child.stdout!, [
"\0",
])) {
yield event;
}
await childPromise;
} finally {
if (cancellationRegistration !== undefined) {
cancellationRegistration.dispose();
}
}
}
/**
* Runs an asynchronous CodeQL CLI command without invoking the CLI server, returning any events
* fired by the command as an asynchronous generator.
*
* @param command The `codeql` command to be run, provided as an array of command/subcommand names.
* @param commandArgs The arguments to pass to the `codeql` command.
* @param description Description of the action being run, to be shown in log and error messages.
* @param cancellationToken CancellationToken to terminate the test process.
* @param logger Logger to write text output from the command.
* @returns The sequence of async events produced by the command.
*/
public async *runAsyncCodeQlCliCommand<EventType>(
command: string[],
commandArgs: string[],
description: string,
{
cancellationToken,
logger,
}: {
cancellationToken?: CancellationToken;
logger?: BaseLogger;
} = {},
): AsyncGenerator<EventType, void, unknown> {
for await (const event of this.runAsyncCodeQlCliCommandInternal(
command,
commandArgs,
cancellationToken,
logger,
)) {
try {
yield JSON.parse(event) as EventType;
} catch (err) {
throw new Error(
`Parsing output of ${description} failed: ${getErrorMessage(err)}`,
);
}
}
}
/**
* Runs a CodeQL CLI command on the server, returning the output as a string.
* @param command The `codeql` command to be run, provided as an array of command/subcommand names.
* @param commandArgs The arguments to pass to the `codeql` command.
* @param description Description of the action being run, to be shown in log and error messages.
* @param progressReporter Used to output progress messages, e.g. to the status bar.
* @param onLine Used for responding to interactive output on stdout/stdin.
* @returns The contents of the command's stdout, if the command succeeded.
*/
runCodeQlCliCommand(
command: string[],
commandArgs: string[],
description: string,
{
progressReporter,
onLine,
silent = false,
}: {
progressReporter?: ProgressReporter;
onLine?: OnLineCallback;
silent?: boolean;
} = {},
): Promise<string> {
if (progressReporter) {
progressReporter.report({ message: description });
}
return new Promise((resolve, reject) => {
// Construct the command that actually does the work
const callback = (): void => {
try {
this.runCodeQlCliInternal(
command,
commandArgs,
description,
onLine,
silent,
).then(resolve, reject);
} catch (err) {
reject(err);
}
};
// If the server is not running a command, then run the given command immediately,
// otherwise add to the queue
if (this.commandInProcess) {
this.commandQueue.push(callback);
} else {
callback();
}
});
}
/**
* Runs a CodeQL CLI command, parsing the output as JSON.
* @param command The `codeql` command to be run, provided as an array of command/subcommand names.
* @param commandArgs The arguments to pass to the `codeql` command.
* @param description Description of the action being run, to be shown in log and error messages.
* @param addFormat Whether or not to add commandline arguments to specify the format as JSON.
* @param progressReporter Used to output progress messages, e.g. to the status bar.
* @param onLine Used for responding to interactive output on stdout/stdin.
* @returns The contents of the command's stdout, if the command succeeded.
*/
async runJsonCodeQlCliCommand<OutputType>(
command: string[],
commandArgs: string[],
description: string,
{
addFormat = true,
progressReporter,
onLine,
silent = false,
}: {
addFormat?: boolean;
progressReporter?: ProgressReporter;
onLine?: OnLineCallback;
silent?: boolean;
} = {},
): Promise<OutputType> {
let args: string[] = [];
if (addFormat)
// Add format argument first, in case commandArgs contains positional parameters.
args = args.concat(["--format", "json"]);
args = args.concat(commandArgs);
const result = await this.runCodeQlCliCommand(command, args, description, {
progressReporter,
onLine,
silent,
});
try {
return JSON.parse(result) as OutputType;
} catch (err) {
throw new Error(
`Parsing output of ${description} failed: ${getErrorMessage(err)}`,
);
}
}
/**
* Runs a CodeQL CLI command with authentication, parsing the output as JSON.
*
* This method is intended for use with commands that accept a `--github-auth-stdin` argument. This
* will be added to the command line arguments automatically if an access token is available.
*
* When the argument is given to the command, the CLI server will prompt for the access token on
* stdin. This method will automatically respond to the prompt with the access token.
*
* There are a few race conditions that can potentially happen:
* 1. The user logs in after the command has started. In this case, no access token will be given.
* 2. The user logs out after the command has started. In this case, the user will be prompted
* to login again. If they cancel the login, the old access token that was present before the
* command was started will be used.
*
* @param command The `codeql` command to be run, provided as an array of command/subcommand names.
* @param commandArgs The arguments to pass to the `codeql` command.
* @param description Description of the action being run, to be shown in log and error messages.
* @param addFormat Whether or not to add commandline arguments to specify the format as JSON.
* @param progressReporter Used to output progress messages, e.g. to the status bar.
* @returns The contents of the command's stdout, if the command succeeded.
*/
async runJsonCodeQlCliCommandWithAuthentication<OutputType>(
command: string[],
commandArgs: string[],
description: string,
{
addFormat,
progressReporter,
}: {
addFormat?: boolean;
progressReporter?: ProgressReporter;
} = {},
): Promise<OutputType> {
const accessToken = await this.app.credentials.getExistingAccessToken();
const extraArgs = accessToken ? ["--github-auth-stdin"] : [];
return this.runJsonCodeQlCliCommand(
command,
[...extraArgs, ...commandArgs],
description,
{
addFormat,
progressReporter,
onLine: async (line) => {
if (line.startsWith("Enter value for --github-auth-stdin")) {
try {
return await this.app.credentials.getAccessToken();
} catch (e) {
// If the user cancels the authentication prompt, we still need to give a value to the CLI.
// By giving a potentially invalid value, the user will just get a 401/403 when they try to access a
// private package and the access token is invalid.
// This code path is very rare to hit. It would only be hit if the user is logged in when
// starting the command, then logging out before the getAccessToken() is called again and
// then cancelling the authentication prompt.
return accessToken;
}
}
return undefined;
},
},
);
}
/**
* Resolve the library path and dbscheme for a query.
* @param workspaces The current open workspaces
* @param queryPath The path to the query
*/
async resolveLibraryPath(
workspaces: string[],
queryPath: string,
silent = false,
): Promise<QuerySetup> {
const subcommandArgs = [
"--query",
queryPath,
...this.getAdditionalPacksArg(workspaces),
];
return await this.runJsonCodeQlCliCommand<QuerySetup>(
["resolve", "library-path"],
subcommandArgs,
"Resolving library paths",
{ silent },
);
}
/**
* Resolves the language for a query.
* @param queryUri The URI of the query
*/
async resolveQueryByLanguage(
workspaces: string[],
queryUri: Uri,
): Promise<QueryInfoByLanguage> {
const subcommandArgs = [
"--format",
"bylanguage",
queryUri.fsPath,
...this.getAdditionalPacksArg(workspaces),
];
return JSON.parse(
await this.runCodeQlCliCommand(
["resolve", "queries"],
subcommandArgs,
"Resolving query by language",
),
);
}
/**
* Finds all available queries in a given directory.
* @param queryDir Root of directory tree to search for queries.
* @param silent If true, don't print logs to the CodeQL extension log.
* @returns The list of queries that were found.
*/
public async resolveQueries(
queryDir: string,
silent?: boolean,
): Promise<ResolvedQueries> {
const subcommandArgs = [queryDir];
return await this.runJsonCodeQlCliCommand<ResolvedQueries>(
["resolve", "queries"],
subcommandArgs,
"Resolving queries",
{ silent },
);
}
/**
* Finds all available QL tests in a given directory.
* @param testPath Root of directory tree to search for tests.
* @returns The list of tests that were found.
*/
public async resolveTests(testPath: string): Promise<ResolvedTests> {
const subcommandArgs = [testPath];
return await this.runJsonCodeQlCliCommand<ResolvedTests>(
["resolve", "tests", "--strict-test-discovery"],
subcommandArgs,
"Resolving tests",
);
}
public async resolveQlref(qlref: string): Promise<QlrefInfo> {
const subcommandArgs = [qlref];
return await this.runJsonCodeQlCliCommand<QlrefInfo>(
["resolve", "qlref"],
subcommandArgs,
"Resolving qlref",
{
addFormat: false,
},
);
}
/**
* Issues an internal clear-cache command to the cli server. This
* command is used to clear the qlpack cache of the server.
*
* This cache is generally cleared every 1s. This method is used
* to force an early clearing of the cache.
*/
public async clearCache(): Promise<void> {
await this.runCodeQlCliCommand(
["clear-cache"],
[],
"Clearing qlpack cache",
);
}
/**
* Runs QL tests.
* @param testPaths Full paths of the tests to run.
* @param workspaces Workspace paths to use as search paths for QL packs.
* @param options Additional options.
*/
public async *runTests(
testPaths: string[],
workspaces: string[],
{
cancellationToken,
logger,
}: {
cancellationToken?: CancellationToken;
logger?: BaseLogger;
},
): AsyncGenerator<TestCompleted, void, unknown> {
const subcommandArgs = this.cliConfig.additionalTestArguments.concat([
...this.getAdditionalPacksArg(workspaces),
"--threads",
this.cliConfig.numberTestThreads.toString(),
...testPaths,
]);
for await (const event of this.runAsyncCodeQlCliCommand<TestCompleted>(
["test", "run"],
subcommandArgs,
"Run CodeQL Tests",
{
cancellationToken,
logger,
},
)) {
yield event;
}
}
/**
* Gets the metadata for a query.
* @param queryPath The path to the query.
*/
async resolveMetadata(queryPath: string): Promise<QueryMetadata> {
return await this.runJsonCodeQlCliCommand<QueryMetadata>(
["resolve", "metadata"],
[queryPath],
"Resolving query metadata",
);
}
/** Resolves the ML models that should be available when evaluating a query. */
async resolveMlModels(
additionalPacks: string[],
queryPath: string,
): Promise<MlModelsInfo> {
const args = (await this.cliConstraints.supportsPreciseResolveMlModels())
? // use the dirname of the path so that we can handle query libraries
[...this.getAdditionalPacksArg(additionalPacks), dirname(queryPath)]
: this.getAdditionalPacksArg(additionalPacks);
return await this.runJsonCodeQlCliCommand<MlModelsInfo>(
["resolve", "ml-models"],
args,
"Resolving ML models",
{
addFormat: false,
},
);
}
/**
* Gets the RAM setting for the query server.
* @param queryMemoryMb The maximum amount of RAM to use, in MB.
* Leave `undefined` for CodeQL to choose a limit based on the available system memory.
* @param progressReporter The progress reporter to send progress information to.
* @returns String arguments that can be passed to the CodeQL query server,
* indicating how to split the given RAM limit between heap and off-heap memory.
*/
async resolveRam(
queryMemoryMb: number | undefined,
progressReporter?: ProgressReporter,
): Promise<string[]> {
const args: string[] = [];
if (queryMemoryMb !== undefined) {
args.push("--ram", queryMemoryMb.toString());
}
return await this.runJsonCodeQlCliCommand<string[]>(
["resolve", "ram"],
args,
"Resolving RAM settings",
{
progressReporter,
},
);
}
/**
* Gets the headers (and optionally pagination info) of a bqrs.
* @param bqrsPath The path to the bqrs.
* @param pageSize The page size to precompute offsets into the binary file for.
*/
async bqrsInfo(bqrsPath: string, pageSize?: number): Promise<BQRSInfo> {
const subcommandArgs = (
pageSize ? ["--paginate-rows", pageSize.toString()] : []
).concat(bqrsPath);
return await this.runJsonCodeQlCliCommand<BQRSInfo>(
["bqrs", "info"],
subcommandArgs,
"Reading bqrs header",
);
}
async databaseUnbundle(
archivePath: string,
target: string,
name?: string,
): Promise<string> {
const subcommandArgs = [];
if (target) subcommandArgs.push("--target", target);
if (name) subcommandArgs.push("--name", name);
subcommandArgs.push(archivePath);
return await this.runCodeQlCliCommand(
["database", "unbundle"],
subcommandArgs,
`Extracting ${archivePath} to directory ${target}`,
);
}
/**
* Uses a .qhelp file to generate Query Help documentation in a specified format.
* @param pathToQhelp The path to the .qhelp file
* @param format The format in which the query help should be generated {@link https://codeql.github.com/docs/codeql-cli/manual/generate-query-help/#cmdoption-codeql-generate-query-help-format}
* @param outputDirectory The output directory for the generated file
*/
async generateQueryHelp(
pathToQhelp: string,
outputDirectory?: string,
): Promise<string> {
const subcommandArgs = ["--format=markdown"];
if (outputDirectory) subcommandArgs.push("--output", outputDirectory);
subcommandArgs.push(pathToQhelp);
return await this.runCodeQlCliCommand(
["generate", "query-help"],
subcommandArgs,
`Generating qhelp in markdown format at ${outputDirectory}`,
);
}
/**
* Generate a summary of an evaluation log.
* @param endSummaryPath The path to write only the end of query part of the human-readable summary to.
* @param inputPath The path of an evaluation event log.
* @param outputPath The path to write a human-readable summary of it to.
*/
async generateLogSummary(
inputPath: string,
outputPath: string,
endSummaryPath: string,
): Promise<string> {
const subcommandArgs = [
"--format=text",
`--end-summary=${endSummaryPath}`,
...((await this.cliConstraints.supportsSourceMap())
? ["--sourcemap"]
: []),
inputPath,
outputPath,
];
return await this.runCodeQlCliCommand(
["generate", "log-summary"],
subcommandArgs,
"Generating log summary",
);
}
/**