Skip to content

Commit 1d414ba

Browse files
committed
Update linting rules
Add the `@typescript-eslint/no-floating-promises` rule with an allowance for floating promises if `void` is used. This increases safety and ensures that we are explicit when we avoid awaiting a promise. I already caught a few bugish locations. In general, we don't need to await the results of logging calls. databases-ui, we were using a deprecated method for removing a directory. `fs.rmdir` instead of `fs.remove`.
1 parent 2f3be92 commit 1d414ba

31 files changed

+216
-215
lines changed

extensions/ql-vscode/.eslintrc.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ module.exports = {
2424
"@typescript-eslint/explicit-function-return-type": "off",
2525
"@typescript-eslint/no-non-null-assertion": "off",
2626
"@typescript-eslint/no-explicit-any": "off",
27+
"@typescript-eslint/no-floating-promises": [ "error", { ignoreVoid: true } ],
2728
"prefer-const": ["warn", { destructuring: "all" }],
2829
indent: "off",
2930
"@typescript-eslint/indent": "off",

extensions/ql-vscode/src/archive-filesystem-provider.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ class InvalidSourceArchiveUriError extends Error {
115115
export function decodeSourceArchiveUri(uri: vscode.Uri): ZipFileReference {
116116
if (!uri.authority) {
117117
// Uri is malformed, but this is recoverable
118-
logger.log(`Warning: ${new InvalidSourceArchiveUriError(uri).message}`);
118+
void logger.log(`Warning: ${new InvalidSourceArchiveUriError(uri).message}`);
119119
return {
120120
pathWithinSourceArchive: '/',
121121
sourceArchiveZipPath: uri.path
@@ -141,7 +141,7 @@ function ensureFile(map: DirectoryHierarchyMap, file: string) {
141141
const dirname = path.dirname(file);
142142
if (dirname === '.') {
143143
const error = `Ill-formed path ${file} in zip archive (expected absolute path)`;
144-
logger.log(error);
144+
void logger.log(error);
145145
throw new Error(error);
146146
}
147147
ensureDir(map, dirname);

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ export async function getCodeQlCliVersion(codeQlPath: string, logger: Logger): P
1818
} catch (e) {
1919
// Failed to run the version command. This might happen if the cli version is _really_ old, or it is corrupted.
2020
// Either way, we can't determine compatibility.
21-
logger.log(`Failed to run 'codeql version'. Reason: ${e.message}`);
21+
void logger.log(`Failed to run 'codeql version'. Reason: ${e.message}`);
2222
return undefined;
2323
}
2424
}

extensions/ql-vscode/src/cli.ts

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -183,15 +183,15 @@ export class CodeQLCliServer implements Disposable {
183183
killProcessIfRunning(): void {
184184
if (this.process) {
185185
// Tell the Java CLI server process to shut down.
186-
this.logger.log('Sending shutdown request');
186+
void this.logger.log('Sending shutdown request');
187187
try {
188188
this.process.stdin.write(JSON.stringify(['shutdown']), 'utf8');
189189
this.process.stdin.write(this.nullBuffer);
190-
this.logger.log('Sent shutdown request');
190+
void this.logger.log('Sent shutdown request');
191191
} catch (e) {
192192
// We are probably fine here, the process has already closed stdin.
193-
this.logger.log(`Shutdown request failed: process stdin may have already closed. The error was ${e}`);
194-
this.logger.log('Stopping the process anyway.');
193+
void this.logger.log(`Shutdown request failed: process stdin may have already closed. The error was ${e}`);
194+
void this.logger.log('Stopping the process anyway.');
195195
}
196196
// Close the stdin and stdout streams.
197197
// This is important on Windows where the child process may not die cleanly.
@@ -271,7 +271,7 @@ export class CodeQLCliServer implements Disposable {
271271
// Compute the full args array
272272
const args = command.concat(LOGGING_FLAGS).concat(commandArgs);
273273
const argsString = args.join(' ');
274-
this.logger.log(`${description} using CodeQL CLI: ${argsString}...`);
274+
void this.logger.log(`${description} using CodeQL CLI: ${argsString}...`);
275275
try {
276276
await new Promise<void>((resolve, reject) => {
277277
// Start listening to stdout
@@ -298,7 +298,7 @@ export class CodeQLCliServer implements Disposable {
298298
const fullBuffer = Buffer.concat(stdoutBuffers);
299299
// Make sure we remove the terminator;
300300
const data = fullBuffer.toString('utf8', 0, fullBuffer.length - 1);
301-
this.logger.log('CLI command succeeded.');
301+
void this.logger.log('CLI command succeeded.');
302302
return data;
303303
} catch (err) {
304304
// Kill the process if it isn't already dead.
@@ -311,7 +311,7 @@ export class CodeQLCliServer implements Disposable {
311311
newError.stack += (err.stack || '');
312312
throw newError;
313313
} finally {
314-
this.logger.log(Buffer.concat(stderrBuffers).toString('utf8'));
314+
void this.logger.log(Buffer.concat(stderrBuffers).toString('utf8'));
315315
// Remove the listeners we set up.
316316
process.stdout.removeAllListeners('data');
317317
process.stderr.removeAllListeners('data');
@@ -371,7 +371,7 @@ export class CodeQLCliServer implements Disposable {
371371
}
372372
if (logger !== undefined) {
373373
// The human-readable output goes to stderr.
374-
logStream(child.stderr!, logger);
374+
void logStream(child.stderr!, logger);
375375
}
376376

377377
for await (const event of await splitStreamAtSeparators(child.stdout!, ['\0'])) {
@@ -813,7 +813,7 @@ export function spawnServer(
813813
if (progressReporter !== undefined) {
814814
progressReporter.report({ message: `Starting ${name}` });
815815
}
816-
logger.log(`Starting ${name} using CodeQL CLI: ${base} ${argsString}`);
816+
void logger.log(`Starting ${name} using CodeQL CLI: ${base} ${argsString}`);
817817
const child = child_process.spawn(base, args);
818818
if (!child || !child.pid) {
819819
throw new Error(`Failed to start ${name} using command ${base} ${argsString}.`);
@@ -829,7 +829,7 @@ export function spawnServer(
829829
if (progressReporter !== undefined) {
830830
progressReporter.report({ message: `Started ${name}` });
831831
}
832-
logger.log(`${name} started on PID: ${child.pid}`);
832+
void logger.log(`${name} started on PID: ${child.pid}`);
833833
return child;
834834
}
835835

@@ -858,10 +858,10 @@ export async function runCodeQlCliCommand(
858858
if (progressReporter !== undefined) {
859859
progressReporter.report({ message: description });
860860
}
861-
logger.log(`${description} using CodeQL CLI: ${codeQlPath} ${argsString}...`);
861+
void logger.log(`${description} using CodeQL CLI: ${codeQlPath} ${argsString}...`);
862862
const result = await promisify(child_process.execFile)(codeQlPath, args);
863-
logger.log(result.stderr);
864-
logger.log('CLI command succeeded.');
863+
void logger.log(result.stderr);
864+
void logger.log('CLI command succeeded.');
865865
return result.stdout;
866866
} catch (err) {
867867
throw new Error(`${description} failed: ${err.stderr || err}`);
@@ -976,7 +976,7 @@ const lineEndings = ['\r\n', '\r', '\n'];
976976
*/
977977
async function logStream(stream: Readable, logger: Logger): Promise<void> {
978978
for await (const line of await splitStreamAtSeparators(stream, lineEndings)) {
979-
logger.log(line);
979+
await logger.log(line);
980980
}
981981
}
982982

extensions/ql-vscode/src/commandRunner.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -126,16 +126,16 @@ export function commandRunner(
126126
if (e instanceof UserCancellationException) {
127127
// User has cancelled this action manually
128128
if (e.silent) {
129-
logger.log(errorMessage);
129+
void logger.log(errorMessage);
130130
} else {
131-
showAndLogWarningMessage(errorMessage);
131+
void showAndLogWarningMessage(errorMessage);
132132
}
133133
} else {
134134
// Include the full stack in the error log only.
135135
const fullMessage = e.stack
136136
? `${errorMessage}\n${e.stack}`
137137
: errorMessage;
138-
showAndLogErrorMessage(errorMessage, {
138+
void showAndLogErrorMessage(errorMessage, {
139139
fullMessage
140140
});
141141
}
@@ -177,16 +177,16 @@ export function commandRunnerWithProgress<R>(
177177
if (e instanceof UserCancellationException) {
178178
// User has cancelled this action manually
179179
if (e.silent) {
180-
logger.log(errorMessage);
180+
void logger.log(errorMessage);
181181
} else {
182-
showAndLogWarningMessage(errorMessage);
182+
void showAndLogWarningMessage(errorMessage);
183183
}
184184
} else {
185185
// Include the full stack in the error log only.
186186
const fullMessage = e.stack
187187
? `${errorMessage}\n${e.stack}`
188188
: errorMessage;
189-
showAndLogErrorMessage(errorMessage, {
189+
void showAndLogErrorMessage(errorMessage, {
190190
fullMessage
191191
});
192192
}

extensions/ql-vscode/src/compare/compare-interface.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ export class CompareInterfaceManager extends DisposableObject {
173173
break;
174174

175175
case 'changeCompare':
176-
this.changeTable(msg.newResultSetName);
176+
await this.changeTable(msg.newResultSetName);
177177
break;
178178

179179
case 'viewSourceFile':
@@ -267,11 +267,11 @@ export class CompareInterfaceManager extends DisposableObject {
267267
return resultsDiff(fromResults, toResults);
268268
}
269269

270-
private openQuery(kind: 'from' | 'to') {
270+
private async openQuery(kind: 'from' | 'to') {
271271
const toOpen =
272272
kind === 'from' ? this.comparePair?.from : this.comparePair?.to;
273273
if (toOpen) {
274-
this.showQueryResultsCallback(toOpen);
274+
await this.showQueryResultsCallback(toOpen);
275275
}
276276
}
277277
}

extensions/ql-vscode/src/config.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ export class QueryServerConfigListener extends ConfigListener implements QuerySe
226226
return undefined;
227227
}
228228
if (memory == 0 || typeof (memory) !== 'number') {
229-
logger.log(`Ignoring value '${memory}' for setting ${MEMORY_SETTING.qualifiedName}`);
229+
void logger.log(`Ignoring value '${memory}' for setting ${MEMORY_SETTING.qualifiedName}`);
230230
return undefined;
231231
}
232232
return memory;

extensions/ql-vscode/src/contextual/queryResolver.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ export async function resolveQueries(cli: CodeQLCliServer, qlpack: string, keyTy
3737

3838
const queries = await cli.resolveQueriesInSuite(suiteFile, helpers.getOnDiskWorkspaceFolders());
3939
if (queries.length === 0) {
40-
helpers.showAndLogErrorMessage(
40+
void helpers.showAndLogErrorMessage(
4141
`No ${nameOfKeyType(keyType)} queries (tagged "${tagOfKeyType(keyType)}") could be found in the current library path. \
4242
Try upgrading the CodeQL libraries. If that doesn't work, then ${nameOfKeyType(keyType)} queries are not yet available \
4343
for this language.`

extensions/ql-vscode/src/databaseFetcher.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,8 @@ export async function promptImportInternetDatabase(
5151
);
5252

5353
if (item) {
54-
commands.executeCommand('codeQLDatabases.focus');
55-
showAndLogInformationMessage('Database downloaded and imported successfully.');
54+
await commands.executeCommand('codeQLDatabases.focus');
55+
void showAndLogInformationMessage('Database downloaded and imported successfully.');
5656
}
5757
return item;
5858

@@ -91,8 +91,8 @@ export async function promptImportLgtmDatabase(
9191
token
9292
);
9393
if (item) {
94-
commands.executeCommand('codeQLDatabases.focus');
95-
showAndLogInformationMessage('Database downloaded and imported successfully.');
94+
await commands.executeCommand('codeQLDatabases.focus');
95+
void showAndLogInformationMessage('Database downloaded and imported successfully.');
9696
}
9797
return item;
9898
}
@@ -125,8 +125,8 @@ export async function importArchiveDatabase(
125125
token
126126
);
127127
if (item) {
128-
commands.executeCommand('codeQLDatabases.focus');
129-
showAndLogInformationMessage('Database unzipped and imported successfully.');
128+
await commands.executeCommand('codeQLDatabases.focus');
129+
void showAndLogInformationMessage('Database unzipped and imported successfully.');
130130
}
131131
return item;
132132
} catch (e) {
@@ -433,7 +433,7 @@ export async function convertToDatabaseUrl(lgtmUrl: string) {
433433
language,
434434
].join('/')}`;
435435
} catch (e) {
436-
logger.log(`Error: ${e.message}`);
436+
void logger.log(`Error: ${e.message}`);
437437
throw new Error(`Invalid LGTM URL: ${lgtmUrl}`);
438438
}
439439
}

extensions/ql-vscode/src/databases-ui.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ export class DatabaseUI extends DisposableObject {
234234
}
235235

236236
init() {
237-
logger.log('Registering database panel commands.');
237+
void logger.log('Registering database panel commands.');
238238
this.push(
239239
commandRunnerWithProgress(
240240
'codeQL.setCurrentDatabase',
@@ -369,20 +369,20 @@ export class DatabaseUI extends DisposableObject {
369369
try {
370370
return await this.chooseAndSetDatabase(true, progress, token);
371371
} catch (e) {
372-
showAndLogErrorMessage(e.message);
372+
void showAndLogErrorMessage(e.message);
373373
return undefined;
374374
}
375375
};
376376

377377
handleRemoveOrphanedDatabases = async (): Promise<void> => {
378-
logger.log('Removing orphaned databases from workspace storage.');
378+
void logger.log('Removing orphaned databases from workspace storage.');
379379
let dbDirs = undefined;
380380

381381
if (
382382
!(await fs.pathExists(this.storagePath)) ||
383383
!(await fs.stat(this.storagePath)).isDirectory()
384384
) {
385-
logger.log('Missing or invalid storage directory. Not trying to remove orphaned databases.');
385+
void logger.log('Missing or invalid storage directory. Not trying to remove orphaned databases.');
386386
return;
387387
}
388388

@@ -403,7 +403,7 @@ export class DatabaseUI extends DisposableObject {
403403
dbDirs = await asyncFilter(dbDirs, isLikelyDatabaseRoot);
404404

405405
if (!dbDirs.length) {
406-
logger.log('No orphaned databases found.');
406+
void logger.log('No orphaned databases found.');
407407
return;
408408
}
409409

@@ -412,8 +412,8 @@ export class DatabaseUI extends DisposableObject {
412412
await Promise.all(
413413
dbDirs.map(async dbDir => {
414414
try {
415-
logger.log(`Deleting orphaned database '${dbDir}'.`);
416-
await fs.rmdir(dbDir, { recursive: true } as any); // typings doesn't recognize the options argument
415+
void logger.log(`Deleting orphaned database '${dbDir}'.`);
416+
await fs.remove(dbDir);
417417
} catch (e) {
418418
failures.push(`${path.basename(dbDir)}`);
419419
}
@@ -422,7 +422,7 @@ export class DatabaseUI extends DisposableObject {
422422

423423
if (failures.length) {
424424
const dirname = path.dirname(failures[0]);
425-
showAndLogErrorMessage(
425+
void showAndLogErrorMessage(
426426
`Failed to delete unused databases (${
427427
failures.join(', ')
428428
}).\nTo delete unused databases, please remove them manually from the storage folder ${dirname}.`
@@ -438,7 +438,7 @@ export class DatabaseUI extends DisposableObject {
438438
try {
439439
return await this.chooseAndSetDatabase(false, progress, token);
440440
} catch (e) {
441-
showAndLogErrorMessage(e.message);
441+
void showAndLogErrorMessage(e.message);
442442
return undefined;
443443
}
444444
};
@@ -617,7 +617,7 @@ export class DatabaseUI extends DisposableObject {
617617
});
618618

619619
if (newName) {
620-
this.databaseManager.renameDatabaseItem(databaseItem, newName);
620+
await this.databaseManager.renameDatabaseItem(databaseItem, newName);
621621
}
622622
};
623623

0 commit comments

Comments
 (0)