Skip to content

Commit 7903201

Browse files
committed
Refactor
1 parent 11efe0a commit 7903201

File tree

5 files changed

+55
-79
lines changed

5 files changed

+55
-79
lines changed

extensions/ql-vscode/src/codeql-cli/cli.ts

Lines changed: 42 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -202,9 +202,7 @@ interface BqrsDecodeOptions {
202202
entities?: string[];
203203
}
204204

205-
type OnLineCallback = (
206-
line: string,
207-
) => Promise<string | undefined> | string | undefined;
205+
type OnLineCallback = (line: string) => Promise<string | undefined>;
208206

209207
type VersionChangedListener = (
210208
newVersionAndFeatures: VersionAndFeatures | undefined,
@@ -368,12 +366,11 @@ export class CodeQLCliServer implements Disposable {
368366
*/
369367
private async launchProcess(): Promise<ChildProcessWithoutNullStreams> {
370368
const codeQlPath = await this.getCodeQlPath();
371-
const args = [];
372-
if (shouldDebugCliServer()) {
373-
args.push(
374-
"-J=-agentlib:jdwp=transport=dt_socket,address=localhost:9012,server=n,suspend=y,quiet=y",
375-
);
376-
}
369+
const args = shouldDebugCliServer()
370+
? [
371+
"-J=-agentlib:jdwp=transport=dt_socket,address=localhost:9012,server=n,suspend=y,quiet=y",
372+
]
373+
: [];
377374

378375
return spawnServer(
379376
codeQlPath,
@@ -399,15 +396,11 @@ export class CodeQLCliServer implements Disposable {
399396
}
400397
this.commandInProcess = true;
401398
try {
402-
//Launch the process if it doesn't exist
403-
if (!this.process) {
404-
this.process = await this.launchProcess();
405-
}
406-
// Grab the process so that typescript know that it is always defined.
407-
const process = this.process;
399+
// Launch the process if it doesn't exist
400+
this.process ??= await this.launchProcess();
408401

409402
// Compute the full args array
410-
const args = command.concat(LOGGING_FLAGS).concat(commandArgs);
403+
const args = command.concat(LOGGING_FLAGS, commandArgs);
411404
const argsString = args.join(" ");
412405
// If we are running silently, we don't want to print anything to the console.
413406
if (!silent) {
@@ -416,7 +409,7 @@ export class CodeQLCliServer implements Disposable {
416409
);
417410
}
418411
try {
419-
return await this.handleProcessOutput(process, {
412+
return await this.handleProcessOutput(this.process, {
420413
handleNullTerminator: true,
421414
onListenStart: (process) => {
422415
// Write the command followed by a null terminator.
@@ -451,7 +444,7 @@ export class CodeQLCliServer implements Disposable {
451444
): Promise<string> {
452445
const codeqlPath = await this.getCodeQlPath();
453446

454-
const args = command.concat(LOGGING_FLAGS).concat(commandArgs);
447+
const args = command.concat(LOGGING_FLAGS, commandArgs);
455448
const argsString = args.join(" ");
456449

457450
// If we are running silently, we don't want to print anything to the console.
@@ -569,16 +562,15 @@ export class CodeQLCliServer implements Disposable {
569562

570563
stdoutBuffers.push(newData);
571564

572-
if (handleNullTerminator) {
565+
if (
566+
handleNullTerminator &&
573567
// If the buffer ends in '0' then exit.
574568
// We don't have to check the middle as no output will be written after the null until
575569
// the next command starts
576-
if (
577-
newData.length > 0 &&
578-
newData.readUInt8(newData.length - 1) === 0
579-
) {
580-
resolve();
581-
}
570+
newData.length > 0 &&
571+
newData.readUInt8(newData.length - 1) === 0
572+
) {
573+
resolve();
582574
}
583575
};
584576
stderrListener = (newData: Buffer) => {
@@ -693,9 +685,7 @@ export class CodeQLCliServer implements Disposable {
693685
*/
694686
private runNext(): void {
695687
const callback = this.commandQueue.shift();
696-
if (callback) {
697-
callback();
698-
}
688+
callback?.();
699689
}
700690

701691
/**
@@ -813,7 +803,7 @@ export class CodeQLCliServer implements Disposable {
813803
* is false or not specified, this option is ignored.
814804
* @returns The contents of the command's stdout, if the command succeeded.
815805
*/
816-
runCodeQlCliCommand(
806+
private runCodeQlCliCommand(
817807
command: string[],
818808
commandArgs: string[],
819809
description: string,
@@ -825,9 +815,7 @@ export class CodeQLCliServer implements Disposable {
825815
token,
826816
}: RunOptions = {},
827817
): Promise<string> {
828-
if (progressReporter) {
829-
progressReporter.report({ message: description });
830-
}
818+
progressReporter?.report({ message: description });
831819

832820
if (runInNewProcess) {
833821
return this.runCodeQlCliInNewProcess(
@@ -874,18 +862,17 @@ export class CodeQLCliServer implements Disposable {
874862
* @param progressReporter Used to output progress messages, e.g. to the status bar.
875863
* @returns The contents of the command's stdout, if the command succeeded.
876864
*/
877-
async runJsonCodeQlCliCommand<OutputType>(
865+
private async runJsonCodeQlCliCommand<OutputType>(
878866
command: string[],
879867
commandArgs: string[],
880868
description: string,
881869
{ addFormat = true, ...runOptions }: JsonRunOptions = {},
882870
): Promise<OutputType> {
883-
let args: string[] = [];
884-
if (addFormat) {
871+
const args = [
885872
// Add format argument first, in case commandArgs contains positional parameters.
886-
args = args.concat(["--format", "json"]);
887-
}
888-
args = args.concat(commandArgs);
873+
...(addFormat ? ["--format", "json"] : []),
874+
...commandArgs,
875+
];
889876
const result = await this.runCodeQlCliCommand(
890877
command,
891878
args,
@@ -922,7 +909,7 @@ export class CodeQLCliServer implements Disposable {
922909
* @param runOptions Options for running the command.
923910
* @returns The contents of the command's stdout, if the command succeeded.
924911
*/
925-
async runJsonCodeQlCliCommandWithAuthentication<OutputType>(
912+
private async runJsonCodeQlCliCommandWithAuthentication<OutputType>(
926913
command: string[],
927914
commandArgs: string[],
928915
description: string,
@@ -1226,8 +1213,8 @@ export class CodeQLCliServer implements Disposable {
12261213
}
12271214

12281215
/**
1229-
* Gets the results from a bqrs.
1230-
* @param bqrsPath The path to the bqrs.
1216+
* Gets the results from a bqrs file.
1217+
* @param bqrsPath The path to the bqrs file.
12311218
* @param resultSet The result set to get.
12321219
* @param options Optional BqrsDecodeOptions arguments
12331220
*/
@@ -1240,23 +1227,23 @@ export class CodeQLCliServer implements Disposable {
12401227
`--entities=${entities.join(",")}`,
12411228
"--result-set",
12421229
resultSet,
1243-
]
1244-
.concat(pageSize ? ["--rows", pageSize.toString()] : [])
1245-
.concat(offset ? ["--start-at", offset.toString()] : [])
1246-
.concat([bqrsPath]);
1247-
return await this.runJsonCodeQlCliCommand<DecodedBqrsChunk>(
1230+
...(pageSize ? ["--rows", pageSize.toString()] : []),
1231+
...(offset ? ["--start-at", offset.toString()] : []),
1232+
bqrsPath,
1233+
];
1234+
return this.runJsonCodeQlCliCommand<DecodedBqrsChunk>(
12481235
["bqrs", "decode"],
12491236
subcommandArgs,
12501237
"Reading bqrs data",
12511238
);
12521239
}
12531240

12541241
/**
1255-
* Gets all results from a bqrs.
1256-
* @param bqrsPath The path to the bqrs.
1242+
* Gets all results from a bqrs file.
1243+
* @param bqrsPath The path to the bqrs file.
12571244
*/
12581245
async bqrsDecodeAll(bqrsPath: string): Promise<DecodedBqrs> {
1259-
return await this.runJsonCodeQlCliCommand<DecodedBqrs>(
1246+
return this.runJsonCodeQlCliCommand<DecodedBqrs>(
12601247
["bqrs", "decode"],
12611248
[bqrsPath],
12621249
"Reading all bqrs data",
@@ -1797,7 +1784,7 @@ export class CodeQLCliServer implements Disposable {
17971784
* Spawns a child server process using the CodeQL CLI
17981785
* and attaches listeners to it.
17991786
*
1800-
* @param config The configuration containing the path to the CLI.
1787+
* @param codeqlPath The configuration containing the path to the CLI.
18011788
* @param name Name of the server being started, to be shown in log and error messages.
18021789
* @param command The `codeql` command to be run, provided as an array of command/subcommand names.
18031790
* @param commandArgs The arguments to pass to the `codeql` command.
@@ -1823,9 +1810,9 @@ export function spawnServer(
18231810
// Start the server process.
18241811
const base = codeqlPath;
18251812
const argsString = args.join(" ");
1826-
if (progressReporter !== undefined) {
1827-
progressReporter.report({ message: `Starting ${name}` });
1828-
}
1813+
1814+
progressReporter?.report({ message: `Starting ${name}` });
1815+
18291816
void logger.log(`Starting ${name} using CodeQL CLI: ${base} ${argsString}`);
18301817
const child = spawnChildProcess(base, args);
18311818
if (!child || !child.pid) {
@@ -1859,9 +1846,8 @@ export function spawnServer(
18591846
child.stdout.on("data", stdoutListener);
18601847
}
18611848

1862-
if (progressReporter !== undefined) {
1863-
progressReporter.report({ message: `Started ${name}` });
1864-
}
1849+
progressReporter?.report({ message: `Started ${name}` });
1850+
18651851
void logger.log(`${name} started on PID: ${child.pid}`);
18661852
return child;
18671853
}

extensions/ql-vscode/src/codeql-cli/query-language.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export async function findLanguage(
1919
cliServer: CodeQLCliServer,
2020
queryUri: Uri | undefined,
2121
): Promise<QueryLanguage | undefined> {
22-
const uri = queryUri || window.activeTextEditor?.document.uri;
22+
const uri = queryUri ?? window.activeTextEditor?.document.uri;
2323
if (uri !== undefined) {
2424
try {
2525
const queryInfo = await cliServer.resolveQueryByLanguage(

extensions/ql-vscode/src/common/bqrs-raw-results-mapper.ts

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,20 +27,13 @@ export function bqrsToResultSet(
2727
schema: BqrsResultSetSchema,
2828
chunk: DecodedBqrsChunk,
2929
): RawResultSet {
30-
const name = schema.name;
31-
const totalRowCount = schema.rows;
32-
33-
const columns = schema.columns.map(mapColumn);
34-
35-
const rows = chunk.tuples.map(
36-
(tuple): Row => tuple.map((cell): CellValue => mapCellValue(cell)),
37-
);
38-
3930
const resultSet: RawResultSet = {
40-
name,
41-
totalRowCount,
42-
columns,
43-
rows,
31+
name: schema.name,
32+
totalRowCount: schema.rows,
33+
columns: schema.columns.map(mapColumn),
34+
rows: chunk.tuples.map(
35+
(tuple): Row => tuple.map((cell): CellValue => mapCellValue(cell)),
36+
),
4437
};
4538

4639
if (chunk.next) {

extensions/ql-vscode/src/view/compare/Compare.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ export function Compare(_: Record<string, never>): React.JSX.Element {
4646
null,
4747
);
4848

49-
const message = comparison?.message || "Empty comparison";
49+
const message = comparison?.message ?? "Empty comparison";
5050
const hasRows =
5151
comparison?.result &&
5252
(comparison.result.to.length || comparison.result.from.length);
@@ -170,7 +170,7 @@ export function Compare(_: Record<string, never>): React.JSX.Element {
170170
queryInfo={queryInfo}
171171
comparison={comparison}
172172
userSettings={userSettings}
173-
></CompareTable>
173+
/>
174174
) : (
175175
<Message>{message}</Message>
176176
)}

extensions/ql-vscode/src/view/compare/CompareTable.tsx

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,20 +31,17 @@ const Table = styled.table`
3131
}
3232
`;
3333

34+
async function openQuery(kind: "from" | "to") {
35+
vscode.postMessage({ t: "openQuery", kind });
36+
}
37+
3438
export default function CompareTable({
3539
queryInfo,
3640
comparison,
3741
userSettings,
3842
}: Props) {
3943
const result = comparison.result!;
4044

41-
async function openQuery(kind: "from" | "to") {
42-
vscode.postMessage({
43-
t: "openQuery",
44-
kind,
45-
});
46-
}
47-
4845
return (
4946
<Table>
5047
<thead>

0 commit comments

Comments
 (0)