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`.
This commit is contained in:
Andrew Eisenberg
2021-06-09 16:18:10 -07:00
parent 2f3be92a71
commit 1d414bac55
31 changed files with 216 additions and 215 deletions

View File

@@ -24,6 +24,7 @@ module.exports = {
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-floating-promises": [ "error", { ignoreVoid: true } ],
"prefer-const": ["warn", { destructuring: "all" }],
indent: "off",
"@typescript-eslint/indent": "off",

View File

@@ -115,7 +115,7 @@ class InvalidSourceArchiveUriError extends Error {
export function decodeSourceArchiveUri(uri: vscode.Uri): ZipFileReference {
if (!uri.authority) {
// Uri is malformed, but this is recoverable
logger.log(`Warning: ${new InvalidSourceArchiveUriError(uri).message}`);
void logger.log(`Warning: ${new InvalidSourceArchiveUriError(uri).message}`);
return {
pathWithinSourceArchive: '/',
sourceArchiveZipPath: uri.path
@@ -141,7 +141,7 @@ function ensureFile(map: DirectoryHierarchyMap, file: string) {
const dirname = path.dirname(file);
if (dirname === '.') {
const error = `Ill-formed path ${file} in zip archive (expected absolute path)`;
logger.log(error);
void logger.log(error);
throw new Error(error);
}
ensureDir(map, dirname);

View File

@@ -18,7 +18,7 @@ export async function getCodeQlCliVersion(codeQlPath: string, logger: Logger): P
} catch (e) {
// Failed to run the version command. This might happen if the cli version is _really_ old, or it is corrupted.
// Either way, we can't determine compatibility.
logger.log(`Failed to run 'codeql version'. Reason: ${e.message}`);
void logger.log(`Failed to run 'codeql version'. Reason: ${e.message}`);
return undefined;
}
}

View File

@@ -183,15 +183,15 @@ export class CodeQLCliServer implements Disposable {
killProcessIfRunning(): void {
if (this.process) {
// Tell the Java CLI server process to shut down.
this.logger.log('Sending shutdown request');
void this.logger.log('Sending shutdown request');
try {
this.process.stdin.write(JSON.stringify(['shutdown']), 'utf8');
this.process.stdin.write(this.nullBuffer);
this.logger.log('Sent shutdown request');
void this.logger.log('Sent shutdown request');
} catch (e) {
// We are probably fine here, the process has already closed stdin.
this.logger.log(`Shutdown request failed: process stdin may have already closed. The error was ${e}`);
this.logger.log('Stopping the process anyway.');
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.
@@ -271,7 +271,7 @@ export class CodeQLCliServer implements Disposable {
// Compute the full args array
const args = command.concat(LOGGING_FLAGS).concat(commandArgs);
const argsString = args.join(' ');
this.logger.log(`${description} using CodeQL CLI: ${argsString}...`);
void this.logger.log(`${description} using CodeQL CLI: ${argsString}...`);
try {
await new Promise<void>((resolve, reject) => {
// Start listening to stdout
@@ -298,7 +298,7 @@ export class CodeQLCliServer implements Disposable {
const fullBuffer = Buffer.concat(stdoutBuffers);
// Make sure we remove the terminator;
const data = fullBuffer.toString('utf8', 0, fullBuffer.length - 1);
this.logger.log('CLI command succeeded.');
void this.logger.log('CLI command succeeded.');
return data;
} catch (err) {
// Kill the process if it isn't already dead.
@@ -311,7 +311,7 @@ export class CodeQLCliServer implements Disposable {
newError.stack += (err.stack || '');
throw newError;
} finally {
this.logger.log(Buffer.concat(stderrBuffers).toString('utf8'));
void this.logger.log(Buffer.concat(stderrBuffers).toString('utf8'));
// Remove the listeners we set up.
process.stdout.removeAllListeners('data');
process.stderr.removeAllListeners('data');
@@ -371,7 +371,7 @@ export class CodeQLCliServer implements Disposable {
}
if (logger !== undefined) {
// The human-readable output goes to stderr.
logStream(child.stderr!, logger);
void logStream(child.stderr!, logger);
}
for await (const event of await splitStreamAtSeparators(child.stdout!, ['\0'])) {
@@ -813,7 +813,7 @@ export function spawnServer(
if (progressReporter !== undefined) {
progressReporter.report({ message: `Starting ${name}` });
}
logger.log(`Starting ${name} using CodeQL CLI: ${base} ${argsString}`);
void logger.log(`Starting ${name} using CodeQL CLI: ${base} ${argsString}`);
const child = child_process.spawn(base, args);
if (!child || !child.pid) {
throw new Error(`Failed to start ${name} using command ${base} ${argsString}.`);
@@ -829,7 +829,7 @@ export function spawnServer(
if (progressReporter !== undefined) {
progressReporter.report({ message: `Started ${name}` });
}
logger.log(`${name} started on PID: ${child.pid}`);
void logger.log(`${name} started on PID: ${child.pid}`);
return child;
}
@@ -858,10 +858,10 @@ export async function runCodeQlCliCommand(
if (progressReporter !== undefined) {
progressReporter.report({ message: description });
}
logger.log(`${description} using CodeQL CLI: ${codeQlPath} ${argsString}...`);
void logger.log(`${description} using CodeQL CLI: ${codeQlPath} ${argsString}...`);
const result = await promisify(child_process.execFile)(codeQlPath, args);
logger.log(result.stderr);
logger.log('CLI command succeeded.');
void logger.log(result.stderr);
void logger.log('CLI command succeeded.');
return result.stdout;
} catch (err) {
throw new Error(`${description} failed: ${err.stderr || err}`);
@@ -976,7 +976,7 @@ const lineEndings = ['\r\n', '\r', '\n'];
*/
async function logStream(stream: Readable, logger: Logger): Promise<void> {
for await (const line of await splitStreamAtSeparators(stream, lineEndings)) {
logger.log(line);
await logger.log(line);
}
}

View File

@@ -126,16 +126,16 @@ export function commandRunner(
if (e instanceof UserCancellationException) {
// User has cancelled this action manually
if (e.silent) {
logger.log(errorMessage);
void logger.log(errorMessage);
} else {
showAndLogWarningMessage(errorMessage);
void showAndLogWarningMessage(errorMessage);
}
} else {
// Include the full stack in the error log only.
const fullMessage = e.stack
? `${errorMessage}\n${e.stack}`
: errorMessage;
showAndLogErrorMessage(errorMessage, {
void showAndLogErrorMessage(errorMessage, {
fullMessage
});
}
@@ -177,16 +177,16 @@ export function commandRunnerWithProgress<R>(
if (e instanceof UserCancellationException) {
// User has cancelled this action manually
if (e.silent) {
logger.log(errorMessage);
void logger.log(errorMessage);
} else {
showAndLogWarningMessage(errorMessage);
void showAndLogWarningMessage(errorMessage);
}
} else {
// Include the full stack in the error log only.
const fullMessage = e.stack
? `${errorMessage}\n${e.stack}`
: errorMessage;
showAndLogErrorMessage(errorMessage, {
void showAndLogErrorMessage(errorMessage, {
fullMessage
});
}

View File

@@ -173,7 +173,7 @@ export class CompareInterfaceManager extends DisposableObject {
break;
case 'changeCompare':
this.changeTable(msg.newResultSetName);
await this.changeTable(msg.newResultSetName);
break;
case 'viewSourceFile':
@@ -267,11 +267,11 @@ export class CompareInterfaceManager extends DisposableObject {
return resultsDiff(fromResults, toResults);
}
private openQuery(kind: 'from' | 'to') {
private async openQuery(kind: 'from' | 'to') {
const toOpen =
kind === 'from' ? this.comparePair?.from : this.comparePair?.to;
if (toOpen) {
this.showQueryResultsCallback(toOpen);
await this.showQueryResultsCallback(toOpen);
}
}
}

View File

@@ -226,7 +226,7 @@ export class QueryServerConfigListener extends ConfigListener implements QuerySe
return undefined;
}
if (memory == 0 || typeof (memory) !== 'number') {
logger.log(`Ignoring value '${memory}' for setting ${MEMORY_SETTING.qualifiedName}`);
void logger.log(`Ignoring value '${memory}' for setting ${MEMORY_SETTING.qualifiedName}`);
return undefined;
}
return memory;

View File

@@ -37,7 +37,7 @@ export async function resolveQueries(cli: CodeQLCliServer, qlpack: string, keyTy
const queries = await cli.resolveQueriesInSuite(suiteFile, helpers.getOnDiskWorkspaceFolders());
if (queries.length === 0) {
helpers.showAndLogErrorMessage(
void helpers.showAndLogErrorMessage(
`No ${nameOfKeyType(keyType)} queries (tagged "${tagOfKeyType(keyType)}") could be found in the current library path. \
Try upgrading the CodeQL libraries. If that doesn't work, then ${nameOfKeyType(keyType)} queries are not yet available \
for this language.`

View File

@@ -51,8 +51,8 @@ export async function promptImportInternetDatabase(
);
if (item) {
commands.executeCommand('codeQLDatabases.focus');
showAndLogInformationMessage('Database downloaded and imported successfully.');
await commands.executeCommand('codeQLDatabases.focus');
void showAndLogInformationMessage('Database downloaded and imported successfully.');
}
return item;
@@ -91,8 +91,8 @@ export async function promptImportLgtmDatabase(
token
);
if (item) {
commands.executeCommand('codeQLDatabases.focus');
showAndLogInformationMessage('Database downloaded and imported successfully.');
await commands.executeCommand('codeQLDatabases.focus');
void showAndLogInformationMessage('Database downloaded and imported successfully.');
}
return item;
}
@@ -125,8 +125,8 @@ export async function importArchiveDatabase(
token
);
if (item) {
commands.executeCommand('codeQLDatabases.focus');
showAndLogInformationMessage('Database unzipped and imported successfully.');
await commands.executeCommand('codeQLDatabases.focus');
void showAndLogInformationMessage('Database unzipped and imported successfully.');
}
return item;
} catch (e) {
@@ -433,7 +433,7 @@ export async function convertToDatabaseUrl(lgtmUrl: string) {
language,
].join('/')}`;
} catch (e) {
logger.log(`Error: ${e.message}`);
void logger.log(`Error: ${e.message}`);
throw new Error(`Invalid LGTM URL: ${lgtmUrl}`);
}
}

View File

@@ -234,7 +234,7 @@ export class DatabaseUI extends DisposableObject {
}
init() {
logger.log('Registering database panel commands.');
void logger.log('Registering database panel commands.');
this.push(
commandRunnerWithProgress(
'codeQL.setCurrentDatabase',
@@ -369,20 +369,20 @@ export class DatabaseUI extends DisposableObject {
try {
return await this.chooseAndSetDatabase(true, progress, token);
} catch (e) {
showAndLogErrorMessage(e.message);
void showAndLogErrorMessage(e.message);
return undefined;
}
};
handleRemoveOrphanedDatabases = async (): Promise<void> => {
logger.log('Removing orphaned databases from workspace storage.');
void logger.log('Removing orphaned databases from workspace storage.');
let dbDirs = undefined;
if (
!(await fs.pathExists(this.storagePath)) ||
!(await fs.stat(this.storagePath)).isDirectory()
) {
logger.log('Missing or invalid storage directory. Not trying to remove orphaned databases.');
void logger.log('Missing or invalid storage directory. Not trying to remove orphaned databases.');
return;
}
@@ -403,7 +403,7 @@ export class DatabaseUI extends DisposableObject {
dbDirs = await asyncFilter(dbDirs, isLikelyDatabaseRoot);
if (!dbDirs.length) {
logger.log('No orphaned databases found.');
void logger.log('No orphaned databases found.');
return;
}
@@ -412,8 +412,8 @@ export class DatabaseUI extends DisposableObject {
await Promise.all(
dbDirs.map(async dbDir => {
try {
logger.log(`Deleting orphaned database '${dbDir}'.`);
await fs.rmdir(dbDir, { recursive: true } as any); // typings doesn't recognize the options argument
void logger.log(`Deleting orphaned database '${dbDir}'.`);
await fs.remove(dbDir);
} catch (e) {
failures.push(`${path.basename(dbDir)}`);
}
@@ -422,7 +422,7 @@ export class DatabaseUI extends DisposableObject {
if (failures.length) {
const dirname = path.dirname(failures[0]);
showAndLogErrorMessage(
void showAndLogErrorMessage(
`Failed to delete unused databases (${
failures.join(', ')
}).\nTo delete unused databases, please remove them manually from the storage folder ${dirname}.`
@@ -438,7 +438,7 @@ export class DatabaseUI extends DisposableObject {
try {
return await this.chooseAndSetDatabase(false, progress, token);
} catch (e) {
showAndLogErrorMessage(e.message);
void showAndLogErrorMessage(e.message);
return undefined;
}
};
@@ -617,7 +617,7 @@ export class DatabaseUI extends DisposableObject {
});
if (newName) {
this.databaseManager.renameDatabaseItem(databaseItem, newName);
await this.databaseManager.renameDatabaseItem(databaseItem, newName);
}
};

View File

@@ -115,7 +115,7 @@ async function findDataset(parentDirectory: string): Promise<vscode.Uri> {
const dbAbsolutePath = path.join(parentDirectory, dbRelativePaths[0]);
if (dbRelativePaths.length > 1) {
showAndLogWarningMessage(`Found multiple dataset directories in database, using '${dbAbsolutePath}'.`);
void showAndLogWarningMessage(`Found multiple dataset directories in database, using '${dbAbsolutePath}'.`);
}
return vscode.Uri.file(dbAbsolutePath);
@@ -138,7 +138,7 @@ async function findSourceArchive(
}
}
if (!silent) {
showAndLogInformationMessage(
void showAndLogInformationMessage(
`Could not find source archive for database '${databasePath}'. Assuming paths are absolute.`
);
}
@@ -506,7 +506,7 @@ export class DatabaseItemImpl implements DatabaseItem {
function eventFired<T>(event: vscode.Event<T>, timeoutMs = 1000): Promise<T | undefined> {
return new Promise((res, _rej) => {
const timeout = setTimeout(() => {
logger.log(`Waiting for event ${event} timed out after ${timeoutMs}ms`);
void logger.log(`Waiting for event ${event} timed out after ${timeoutMs}ms`);
res(undefined);
dispose();
}, timeoutMs);
@@ -543,7 +543,7 @@ export class DatabaseManager extends DisposableObject {
qs.onDidStartQueryServer(this.reregisterDatabases.bind(this));
// Let this run async.
this.loadPersistedState();
void this.loadPersistedState();
}
public async openDatabase(
@@ -605,15 +605,15 @@ export class DatabaseManager extends DisposableObject {
const end = (vscode.workspace.workspaceFolders || []).length;
const uri = item.getSourceArchiveExplorerUri();
if (uri === undefined) {
logger.log(`Couldn't obtain file explorer uri for ${item.name}`);
void logger.log(`Couldn't obtain file explorer uri for ${item.name}`);
}
else {
logger.log(`Adding workspace folder for ${item.name} source archive at index ${end}`);
void logger.log(`Adding workspace folder for ${item.name} source archive at index ${end}`);
if ((vscode.workspace.workspaceFolders || []).length < 2) {
// Adding this workspace folder makes the workspace
// multi-root, which may surprise the user. Let them know
// we're doing this.
vscode.window.showInformationMessage(`Adding workspace folder for source archive of database ${item.name}.`);
void vscode.window.showInformationMessage(`Adding workspace folder for source archive of database ${item.name}.`);
}
vscode.workspace.updateWorkspaceFolders(end, 0, {
name: `[${item.name} source archive]`,
@@ -696,7 +696,7 @@ export class DatabaseManager extends DisposableObject {
await databaseItem.refresh();
await this.registerDatabase(progress, token, databaseItem);
if (currentDatabaseUri === database.uri) {
this.setCurrentDatabaseItem(databaseItem, true);
await this.setCurrentDatabaseItem(databaseItem, true);
}
}
catch (e) {
@@ -706,7 +706,7 @@ export class DatabaseManager extends DisposableObject {
}
} catch (e) {
// database list had an unexpected type - nothing to be done?
showAndLogErrorMessage(`Database list loading failed: ${e.message}`);
void showAndLogErrorMessage(`Database list loading failed: ${e.message}`);
}
});
}
@@ -807,16 +807,16 @@ export class DatabaseManager extends DisposableObject {
folder => item.belongsToSourceArchiveExplorerUri(folder.uri)
);
if (folderIndex >= 0) {
logger.log(`Removing workspace folder at index ${folderIndex}`);
void logger.log(`Removing workspace folder at index ${folderIndex}`);
vscode.workspace.updateWorkspaceFolders(folderIndex, 1);
}
// Delete folder from file system only if it is controlled by the extension
if (this.isExtensionControlledLocation(item.databaseUri)) {
logger.log('Deleting database from filesystem.');
void logger.log('Deleting database from filesystem.');
fs.remove(item.databaseUri.fsPath).then(
() => logger.log(`Deleted '${item.databaseUri.fsPath}'`),
e => logger.log(`Failed to delete '${item.databaseUri.fsPath}'. Reason: ${e.message}`));
() => void logger.log(`Deleted '${item.databaseUri.fsPath}'`),
e => void logger.log(`Failed to delete '${item.databaseUri.fsPath}'. Reason: ${e.message}`));
}
// Remove this database item from the allow-list
@@ -858,12 +858,12 @@ export class DatabaseManager extends DisposableObject {
}
private updatePersistedCurrentDatabaseItem(): void {
this.ctx.workspaceState.update(CURRENT_DB, this._currentDatabaseItem ?
void this.ctx.workspaceState.update(CURRENT_DB, this._currentDatabaseItem ?
this._currentDatabaseItem.databaseUri.toString(true) : undefined);
}
private updatePersistedDatabaseList(): void {
this.ctx.workspaceState.update(DB_LIST, this._databaseItems.map(item => item.getPersistedState()));
void this.ctx.workspaceState.update(DB_LIST, this._databaseItems.map(item => item.getPersistedState()));
}
private isExtensionControlledLocation(uri: vscode.Uri) {

View File

@@ -59,23 +59,23 @@ export abstract class Discovery<T> extends DisposableObject {
this.discoveryInProgress = false;
this.update(results);
}
});
})
discoveryPromise.catch(err => {
logger.log(`${this.name} failed. Reason: ${err.message}`);
});
.catch(err => {
void logger.log(`${this.name} failed. Reason: ${err.message}`);
})
discoveryPromise.finally(() => {
if (this.retry) {
// Another refresh request came in while we were still running a previous discovery
// operation. Since the discovery results we just computed are now stale, we'll launch
// another discovery operation instead of updating.
// Note that by doing this inside of `finally`, we will relaunch discovery even if the
// initial discovery operation failed.
this.retry = false;
this.launchDiscovery();
}
});
.finally(() => {
if (this.retry) {
// Another refresh request came in while we were still running a previous discovery
// operation. Since the discovery results we just computed are now stale, we'll launch
// another discovery operation instead of updating.
// Note that by doing this inside of `finally`, we will relaunch discovery even if the
// initial discovery operation failed.
this.retry = false;
this.launchDiscovery();
}
});
}
/**

View File

@@ -153,7 +153,7 @@ export class DistributionManager implements DistributionProvider {
// Check config setting, then extension specific distribution, then PATH.
if (this.config.customCodeQlPath) {
if (!await fs.pathExists(this.config.customCodeQlPath)) {
showAndLogErrorMessage(`The CodeQL executable path is specified as "${this.config.customCodeQlPath}" ` +
void showAndLogErrorMessage(`The CodeQL executable path is specified as "${this.config.customCodeQlPath}" ` +
'by a configuration setting, but a CodeQL executable could not be found at that path. Please check ' +
'that a CodeQL executable exists at the specified path or remove the setting.');
return undefined;
@@ -191,7 +191,7 @@ export class DistributionManager implements DistributionProvider {
};
}
}
logger.log('INFO: Could not find CodeQL on path.');
void logger.log('INFO: Could not find CodeQL on path.');
}
return undefined;
@@ -276,7 +276,7 @@ class ExtensionSpecificDistributionManager {
try {
await this.removeDistribution();
} catch (e) {
logger.log('WARNING: Tried to remove corrupted CodeQL CLI at ' +
void logger.log('WARNING: Tried to remove corrupted CodeQL CLI at ' +
`${this.getDistributionStoragePath()} but encountered an error: ${e}.`);
}
}
@@ -313,7 +313,7 @@ class ExtensionSpecificDistributionManager {
progressCallback?: ProgressCallback): Promise<void> {
await this.downloadDistribution(release, progressCallback);
// Store the installed release within the global extension state.
this.storeInstalledRelease(release);
await this.storeInstalledRelease(release);
}
private async downloadDistribution(release: Release,
@@ -321,7 +321,7 @@ class ExtensionSpecificDistributionManager {
try {
await this.removeDistribution();
} catch (e) {
logger.log(`Tried to clean up old version of CLI at ${this.getDistributionStoragePath()} ` +
void logger.log(`Tried to clean up old version of CLI at ${this.getDistributionStoragePath()} ` +
`but encountered an error: ${e}.`);
}
@@ -332,7 +332,7 @@ class ExtensionSpecificDistributionManager {
throw new Error(`Invariant violation: chose a release to install that didn't have ${requiredAssetName}`);
}
if (assets.length > 1) {
logger.log('WARNING: chose a release with more than one asset to install, found ' +
void logger.log('WARNING: chose a release with more than one asset to install, found ' +
assets.map(asset => asset.name).join(', '));
}
@@ -355,7 +355,7 @@ class ExtensionSpecificDistributionManager {
await this.bumpDistributionFolderIndex();
logger.log(`Extracting CodeQL CLI to ${this.getDistributionStoragePath()}`);
void logger.log(`Extracting CodeQL CLI to ${this.getDistributionStoragePath()}`);
await extractZipArchive(archivePath, this.getDistributionStoragePath());
} finally {
await fs.remove(tmpDirectory);
@@ -368,7 +368,7 @@ class ExtensionSpecificDistributionManager {
* This should not be called for a distribution that is currently in use, as remove may fail.
*/
private async removeDistribution(): Promise<void> {
this.storeInstalledRelease(undefined);
await this.storeInstalledRelease(undefined);
if (await fs.pathExists(this.getDistributionStoragePath())) {
await fs.remove(this.getDistributionStoragePath());
}
@@ -376,7 +376,7 @@ class ExtensionSpecificDistributionManager {
private async getLatestRelease(): Promise<Release> {
const requiredAssetName = DistributionManager.getRequiredAssetName();
logger.log(`Searching for latest release including ${requiredAssetName}.`);
void logger.log(`Searching for latest release including ${requiredAssetName}.`);
return this.createReleasesApiConsumer().getLatestRelease(
this.versionRange,
this.config.includePrerelease,
@@ -384,11 +384,11 @@ class ExtensionSpecificDistributionManager {
const matchingAssets = release.assets.filter(asset => asset.name === requiredAssetName);
if (matchingAssets.length === 0) {
// For example, this could be a release with no platform-specific assets.
logger.log(`INFO: Ignoring a release with no assets named ${requiredAssetName}`);
void logger.log(`INFO: Ignoring a release with no assets named ${requiredAssetName}`);
return false;
}
if (matchingAssets.length > 1) {
logger.log(`WARNING: Ignoring a release with more than one asset named ${requiredAssetName}`);
void logger.log(`WARNING: Ignoring a release with more than one asset named ${requiredAssetName}`);
return false;
}
return true;
@@ -707,16 +707,14 @@ export async function getExecutableFromDirectory(directory: string, warnWhenNotF
return alternateExpectedLauncherPath;
}
if (warnWhenNotFound) {
logger.log(`WARNING: Expected to find a CodeQL CLI executable at ${expectedLauncherPath} but one was not found. ` +
void logger.log(`WARNING: Expected to find a CodeQL CLI executable at ${expectedLauncherPath} but one was not found. ` +
'Will try PATH.');
}
return undefined;
}
function warnDeprecatedLauncher() {
showAndLogWarningMessage(
void showAndLogWarningMessage(
`The "${deprecatedCodeQlLauncherName()!}" launcher has been deprecated and will be removed in a future version. ` +
`Please use "${codeQlLauncherName()}" instead. It is recommended to update to the latest CodeQL binaries.`
);

View File

@@ -149,7 +149,7 @@ export interface CodeQLExtensionInterface {
* @returns CodeQLExtensionInterface
*/
export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionInterface | {}> {
logger.log(`Starting ${extensionId} extension`);
void logger.log(`Starting ${extensionId} extension`);
if (extension === undefined) {
throw new Error(`Can't find extension ${extensionId}`);
}
@@ -166,7 +166,7 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
const shouldUpdateOnNextActivationKey = 'shouldUpdateOnNextActivation';
registerErrorStubs([checkForUpdatesCommand], command => (async () => {
helpers.showAndLogErrorMessage(`Can't execute ${command}: waiting to finish loading CodeQL CLI.`);
void helpers.showAndLogErrorMessage(`Can't execute ${command}: waiting to finish loading CodeQL CLI.`);
}));
interface DistributionUpdateConfig {
@@ -178,7 +178,7 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
async function installOrUpdateDistributionWithProgressTitle(progressTitle: string, config: DistributionUpdateConfig): Promise<void> {
const minSecondsSinceLastUpdateCheck = config.isUserInitiated ? 0 : 86400;
const noUpdatesLoggingFunc = config.shouldDisplayMessageWhenNoUpdates ?
helpers.showAndLogInformationMessage : async (message: string) => logger.log(message);
helpers.showAndLogInformationMessage : async (message: string) => void logger.log(message);
const result = await distributionManager.checkForUpdatesToExtensionManagedDistribution(minSecondsSinceLastUpdateCheck);
// We do want to auto update if there is no distribution at all
@@ -186,7 +186,7 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
switch (result.kind) {
case DistributionUpdateCheckResultKind.AlreadyCheckedRecentlyResult:
logger.log('Didn\'t perform CodeQL CLI update check since a check was already performed within the previous ' +
void logger.log('Didn\'t perform CodeQL CLI update check since a check was already performed within the previous ' +
`${minSecondsSinceLastUpdateCheck} seconds.`);
break;
case DistributionUpdateCheckResultKind.AlreadyUpToDate:
@@ -213,7 +213,7 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
distributionManager.installExtensionManagedDistributionRelease(result.updatedRelease, progress));
await ctx.globalState.update(shouldUpdateOnNextActivationKey, false);
helpers.showAndLogInformationMessage(`CodeQL CLI updated to version "${result.updatedRelease.name}".`);
void helpers.showAndLogInformationMessage(`CodeQL CLI updated to version "${result.updatedRelease.name}".`);
}
break;
default:
@@ -245,12 +245,12 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
codeQlInstalled ? 'check for updates to' : 'install') + ' CodeQL CLI';
if (e instanceof GithubRateLimitedError) {
alertFunction(`Rate limited while trying to ${taskDescription}. Please try again after ` +
void alertFunction(`Rate limited while trying to ${taskDescription}. Please try again after ` +
`your rate limit window resets at ${e.rateLimitResetDate.toLocaleString(env.language)}.`);
} else if (e instanceof GithubApiError) {
alertFunction(`Encountered GitHub API error while trying to ${taskDescription}. ` + e);
void alertFunction(`Encountered GitHub API error while trying to ${taskDescription}. ` + e);
}
alertFunction(`Unable to ${taskDescription}. ` + e);
void alertFunction(`Unable to ${taskDescription}. ` + e);
} finally {
isInstallingOrUpdatingDistribution = false;
}
@@ -260,7 +260,7 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
const result = await distributionManager.getDistribution();
switch (result.kind) {
case FindDistributionResultKind.CompatibleDistribution:
logger.log(`Found compatible version of CodeQL CLI (version ${result.version.raw})`);
void logger.log(`Found compatible version of CodeQL CLI (version ${result.version.raw})`);
break;
case FindDistributionResultKind.IncompatibleDistribution: {
const fixGuidanceMessage = (() => {
@@ -275,16 +275,20 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
}
})();
helpers.showAndLogWarningMessage(`The current version of the CodeQL CLI (${result.version.raw}) ` +
'is incompatible with this extension. ' + fixGuidanceMessage);
void helpers.showAndLogWarningMessage(
`The current version of the CodeQL CLI (${result.version.raw}) ` +
`is incompatible with this extension. ${fixGuidanceMessage}`
);
break;
}
case FindDistributionResultKind.UnknownCompatibilityDistribution:
helpers.showAndLogWarningMessage('Compatibility with the configured CodeQL CLI could not be determined. ' +
'You may experience problems using the extension.');
void helpers.showAndLogWarningMessage(
'Compatibility with the configured CodeQL CLI could not be determined. ' +
'You may experience problems using the extension.'
);
break;
case FindDistributionResultKind.NoDistribution:
helpers.showAndLogErrorMessage('The CodeQL CLI could not be found.');
void helpers.showAndLogErrorMessage('The CodeQL CLI could not be found.');
break;
default:
assertNever(result);
@@ -311,7 +315,7 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
} else if (distributionResult.kind === FindDistributionResultKind.NoDistribution) {
registerErrorStubs([checkForUpdatesCommand], command => async () => {
const installActionName = 'Install CodeQL CLI';
const chosenAction = await helpers.showAndLogErrorMessage(`Can't execute ${command}: missing CodeQL CLI.`, {
const chosenAction = await void helpers.showAndLogErrorMessage(`Can't execute ${command}: missing CodeQL CLI.`, {
items: [installActionName]
});
if (chosenAction === installActionName) {
@@ -357,13 +361,13 @@ async function activateWithInstalledDistribution(
// of activation.
errorStubs.forEach((stub) => stub.dispose());
logger.log('Initializing configuration listener...');
void logger.log('Initializing configuration listener...');
const qlConfigurationListener = await QueryServerConfigListener.createQueryServerConfigListener(
distributionManager
);
ctx.subscriptions.push(qlConfigurationListener);
logger.log('Initializing CodeQL cli server...');
void logger.log('Initializing CodeQL cli server...');
const cliServer = new CodeQLCliServer(
distributionManager,
new CliConfigListener(),
@@ -374,7 +378,7 @@ async function activateWithInstalledDistribution(
const statusBar = new CodeQlStatusBarHandler(cliServer, distributionConfigListener);
ctx.subscriptions.push(statusBar);
logger.log('Initializing query server client.');
void logger.log('Initializing query server client.');
const qs = new qsClient.QueryServerClient(
qlConfigurationListener,
cliServer,
@@ -391,10 +395,10 @@ async function activateWithInstalledDistribution(
ctx.subscriptions.push(qs);
await qs.startQueryServer();
logger.log('Initializing database manager.');
void logger.log('Initializing database manager.');
const dbm = new DatabaseManager(ctx, qs, cliServer, logger);
ctx.subscriptions.push(dbm);
logger.log('Initializing database panel.');
void logger.log('Initializing database panel.');
const databaseUI = new DatabaseUI(
dbm,
qs,
@@ -404,7 +408,7 @@ async function activateWithInstalledDistribution(
databaseUI.init();
ctx.subscriptions.push(databaseUI);
logger.log('Initializing query history manager.');
void logger.log('Initializing query history manager.');
const queryHistoryConfigurationListener = new QueryHistoryConfigListener();
ctx.subscriptions.push(queryHistoryConfigurationListener);
const showResults = async (item: CompletedQuery) =>
@@ -419,11 +423,11 @@ async function activateWithInstalledDistribution(
showResultsForComparison(from, to),
);
ctx.subscriptions.push(qhm);
logger.log('Initializing results panel interface.');
void logger.log('Initializing results panel interface.');
const intm = new InterfaceManager(ctx, dbm, cliServer, queryServerLogger);
ctx.subscriptions.push(intm);
logger.log('Initializing compare panel interface.');
void logger.log('Initializing compare panel interface.');
const cmpm = new CompareInterfaceManager(
ctx,
dbm,
@@ -433,7 +437,7 @@ async function activateWithInstalledDistribution(
);
ctx.subscriptions.push(cmpm);
logger.log('Initializing source archive filesystem provider.');
void logger.log('Initializing source archive filesystem provider.');
archiveFilesystemProvider.activate(ctx);
async function showResultsForComparison(
@@ -443,7 +447,7 @@ async function activateWithInstalledDistribution(
try {
await cmpm.showResults(from, to);
} catch (e) {
helpers.showAndLogErrorMessage(e.message);
void helpers.showAndLogErrorMessage(e.message);
}
}
@@ -491,7 +495,7 @@ async function activateWithInstalledDistribution(
const uri = Uri.file(resolved.resolvedPath);
await window.showTextDocument(uri, { preview: false });
} else {
helpers.showAndLogErrorMessage(
void helpers.showAndLogErrorMessage(
'Jumping from a .qlref file to the .ql file it references is not '
+ 'supported with the CLI version you are running.\n'
+ `Please upgrade your CLI to version ${
@@ -503,7 +507,7 @@ async function activateWithInstalledDistribution(
ctx.subscriptions.push(tmpDirDisposal);
logger.log('Initializing CodeQL language server.');
void logger.log('Initializing CodeQL language server.');
const client = new LanguageClient(
'CodeQL Language Server',
() => spawnIdeServer(qlConfigurationListener),
@@ -521,7 +525,7 @@ async function activateWithInstalledDistribution(
true
);
logger.log('Initializing QLTest interface.');
void logger.log('Initializing QLTest interface.');
const testExplorerExtension = extensions.getExtension<TestHub>(
testExplorerExtensionId
);
@@ -534,7 +538,7 @@ async function activateWithInstalledDistribution(
ctx.subscriptions.push(testUIService);
}
logger.log('Registering top-level command palette commands.');
void logger.log('Registering top-level command palette commands.');
ctx.subscriptions.push(
commandRunnerWithProgress(
'codeQL.runQuery',
@@ -650,7 +654,7 @@ async function activateWithInstalledDistribution(
token: CancellationToken
) => {
await qs.restartQueryServer(progress, token);
helpers.showAndLogInformationMessage('CodeQL Query Server restarted.', {
void helpers.showAndLogInformationMessage('CodeQL Query Server restarted.', {
outputLogger: queryServerLogger,
});
}, {
@@ -705,16 +709,16 @@ async function activateWithInstalledDistribution(
ctx.subscriptions.push(
commandRunner('codeQL.copyVersion', async () => {
const text = `CodeQL extension version: ${extension?.packageJSON.version} \nCodeQL CLI version: ${await cliServer.getVersion()} \nPlatform: ${os.platform()} ${os.arch()}`;
env.clipboard.writeText(text);
helpers.showAndLogInformationMessage(text);
await env.clipboard.writeText(text);
void helpers.showAndLogInformationMessage(text);
}));
logger.log('Starting language server.');
void logger.log('Starting language server.');
ctx.subscriptions.push(client.start());
// Jump-to-definition and find-references
logger.log('Registering jump-to-definition handlers.');
void logger.log('Registering jump-to-definition handlers.');
languages.registerDefinitionProvider(
{ scheme: archiveFilesystemProvider.zipArchiveScheme },
new TemplateQueryDefinitionProvider(cliServer, qs, dbm)
@@ -746,9 +750,9 @@ async function activateWithInstalledDistribution(
title: 'Calculate AST'
}));
commands.executeCommand('codeQLDatabases.removeOrphanedDatabases');
await commands.executeCommand('codeQLDatabases.removeOrphanedDatabases');
logger.log('Successfully finished extension initialization.');
void logger.log('Successfully finished extension initialization.');
return {
ctx,

View File

@@ -77,7 +77,7 @@ async function internalShowAndLog(
fullMessage?: string
): Promise<string | undefined> {
const label = 'Show Log';
outputLogger.log(fullMessage || message);
void outputLogger.log(fullMessage || message);
const result = await fn(message, label, ...items);
if (result === label) {
outputLogger.show();
@@ -259,11 +259,11 @@ export async function getQlPackForDbscheme(cliServer: CodeQLCliServer, dbschemeP
const packs: { packDir: string | undefined; packName: string }[] =
Object.entries(qlpacks).map(([packName, dirs]) => {
if (dirs.length < 1) {
logger.log(`In getQlPackFor ${dbschemePath}, qlpack ${packName} has no directories`);
void logger.log(`In getQlPackFor ${dbschemePath}, qlpack ${packName} has no directories`);
return { packName, packDir: undefined };
}
if (dirs.length > 1) {
logger.log(`In getQlPackFor ${dbschemePath}, qlpack ${packName} has more than one directory; arbitrarily choosing the first`);
void logger.log(`In getQlPackFor ${dbschemePath}, qlpack ${packName} has more than one directory; arbitrarily choosing the first`);
}
return {
packName,
@@ -292,7 +292,7 @@ export async function getPrimaryDbscheme(datasetFolder: string): Promise<string>
const dbscheme = dbschemes[0];
if (dbschemes.length > 1) {
Window.showErrorMessage(`Found multiple dbschemes in ${datasetFolder} during quick query; arbitrarily choosing the first, ${dbscheme}, to decide what library to use.`);
void Window.showErrorMessage(`Found multiple dbschemes in ${datasetFolder} during quick query; arbitrarily choosing the first, ${dbscheme}, to decide what library to use.`);
}
return dbscheme;
}

View File

@@ -224,14 +224,14 @@ export async function jumpToLocation(
} catch (e) {
if (e instanceof Error) {
if (e.message.match(/File not found/)) {
Window.showErrorMessage(
void Window.showErrorMessage(
'Original file of this result is not in the database\'s source archive.'
);
} else {
logger.log(`Unable to handleMsgFromView: ${e.message}`);
void logger.log(`Unable to handleMsgFromView: ${e.message}`);
}
} else {
logger.log(`Unable to handleMsgFromView: ${e}`);
void logger.log(`Unable to handleMsgFromView: ${e}`);
}
}
}

View File

@@ -119,7 +119,7 @@ export class InterfaceManager extends DisposableObject {
this.handleSelectionChange.bind(this)
)
);
logger.log('Registering path-step navigation commands.');
void logger.log('Registering path-step navigation commands.');
this.push(
commandRunner(
'codeQLQueryResults.nextPathStep',
@@ -138,7 +138,7 @@ export class InterfaceManager extends DisposableObject {
if (kind === DatabaseEventKind.Remove) {
this._diagnosticCollection.clear();
if (this.isShowingPanel()) {
this.postMessage({
void this.postMessage({
t: 'untoggleShowProblems'
});
}
@@ -148,7 +148,7 @@ export class InterfaceManager extends DisposableObject {
}
async navigatePathStep(direction: number): Promise<void> {
this.postMessage({ t: 'navigatePath', direction });
await this.postMessage({ t: 'navigatePath', direction });
}
private isShowingPanel() {
@@ -207,14 +207,14 @@ export class InterfaceManager extends DisposableObject {
sortState: InterpretedResultsSortState | undefined
): Promise<void> {
if (this._displayedQuery === undefined) {
showAndLogErrorMessage(
void showAndLogErrorMessage(
'Failed to sort results since evaluation info was unknown.'
);
return;
}
// Notify the webview that it should expect new results.
await this.postMessage({ t: 'resultsUpdating' });
this._displayedQuery.updateInterpretedSortState(sortState);
await this._displayedQuery.updateInterpretedSortState(sortState);
await this.showResults(this._displayedQuery, WebviewReveal.NotForced, true);
}
@@ -223,7 +223,7 @@ export class InterfaceManager extends DisposableObject {
sortState: RawResultsSortState | undefined
): Promise<void> {
if (this._displayedQuery === undefined) {
showAndLogErrorMessage(
void showAndLogErrorMessage(
'Failed to sort results since evaluation info was unknown.'
);
return;
@@ -301,7 +301,7 @@ export class InterfaceManager extends DisposableObject {
assertNever(msg);
}
} catch (e) {
showAndLogErrorMessage(e.message, {
void showAndLogErrorMessage(e.message, {
fullMessage: e.stack
});
}
@@ -372,7 +372,7 @@ export class InterfaceManager extends DisposableObject {
);
// Address this click asynchronously so we still update the
// query history immediately.
resultPromise.then((result) => {
void resultPromise.then((result) => {
if (result === showButton) {
panel.reveal();
}
@@ -556,7 +556,7 @@ export class InterfaceManager extends DisposableObject {
sortState: InterpretedResultsSortState | undefined
): Promise<Interpretation | undefined> {
if (!resultsPaths) {
this.logger.log('No results path. Cannot display interpreted results.');
void this.logger.log('No results path. Cannot display interpreted results.');
return undefined;
}
@@ -603,7 +603,7 @@ export class InterfaceManager extends DisposableObject {
throw new Error('Tried to get interpreted results before interpretation finished');
}
if (this._interpretation.sarif.runs.length !== 1) {
this.logger.log(`Warning: SARIF file had ${this._interpretation.sarif.runs.length} runs, expected 1`);
void this.logger.log(`Warning: SARIF file had ${this._interpretation.sarif.runs.length} runs, expected 1`);
}
const interp = this._interpretation;
return {
@@ -642,7 +642,7 @@ export class InterfaceManager extends DisposableObject {
} catch (e) {
// If interpretation fails, accept the error and continue
// trying to render uninterpreted results anyway.
showAndLogErrorMessage(
void showAndLogErrorMessage(
`Showing raw results instead of interpreted ones due to an error. ${e.message}`
);
}
@@ -683,7 +683,7 @@ export class InterfaceManager extends DisposableObject {
await this.showProblemResultsAsDiagnostics(interpretation, database);
} catch (e) {
const msg = e instanceof Error ? e.message : e.toString();
this.logger.log(
void this.logger.log(
`Exception while computing problem results as diagnostics: ${msg}`
);
this._diagnosticCollection.clear();
@@ -697,7 +697,7 @@ export class InterfaceManager extends DisposableObject {
const { sarif, sourceLocationPrefix } = interpretation;
if (!sarif.runs || !sarif.runs[0].results) {
this.logger.log(
void this.logger.log(
'Didn\'t find a run in the sarif results. Error processing sarif?'
);
return;
@@ -708,11 +708,11 @@ export class InterfaceManager extends DisposableObject {
for (const result of sarif.runs[0].results) {
const message = result.message.text;
if (message === undefined) {
this.logger.log('Sarif had result without plaintext message');
void this.logger.log('Sarif had result without plaintext message');
continue;
}
if (!result.locations) {
this.logger.log('Sarif had result without location');
void this.logger.log('Sarif had result without location');
continue;
}
@@ -725,7 +725,7 @@ export class InterfaceManager extends DisposableObject {
}
const resultLocation = tryResolveLocation(sarifLoc, databaseItem);
if (!resultLocation) {
this.logger.log('Sarif location was not resolvable ' + sarifLoc);
void this.logger.log('Sarif location was not resolvable ' + sarifLoc);
continue;
}
const parsedMessage = parseSarifPlainTextMessage(message);

View File

@@ -249,7 +249,7 @@ export class QueryHistoryManager extends DisposableObject {
})
);
logger.log('Registering query history panel commands.');
void logger.log('Registering query history panel commands.');
this.push(
commandRunner(
'codeQLQueryHistory.openQuery',
@@ -402,7 +402,7 @@ export class QueryHistoryManager extends DisposableObject {
});
const current = this.treeDataProvider.getCurrent();
if (current !== undefined) {
this.treeView.reveal(current);
await this.treeView.reveal(current);
await this.invokeCallbackOn(current);
}
}
@@ -470,10 +470,10 @@ export class QueryHistoryManager extends DisposableObject {
const to = await this.findOtherQueryToCompare(from, multiSelect);
if (from && to) {
this.doCompareCallback(from, to);
await this.doCompareCallback(from, to);
}
} catch (e) {
showAndLogErrorMessage(e.message);
void showAndLogErrorMessage(e.message);
}
}
@@ -520,7 +520,7 @@ export class QueryHistoryManager extends DisposableObject {
if (singleItem.logFileLocation) {
await this.tryOpenExternalFile(singleItem.logFileLocation);
} else {
showAndLogWarningMessage('No log file available');
void showAndLogWarningMessage('No log file available');
}
}
@@ -565,7 +565,7 @@ export class QueryHistoryManager extends DisposableObject {
);
} else {
const label = singleItem.getLabel();
showAndLogInformationMessage(
void showAndLogInformationMessage(
`Query ${label} has no interpreted results.`
);
}
@@ -644,7 +644,7 @@ export class QueryHistoryManager extends DisposableObject {
// We must fire the onDidChangeTreeData event to ensure the current element can be selected
// using `reveal` if the tree view was not visible when the current element was added.
this.treeDataProvider.refresh();
this.treeView.reveal(current);
void this.treeView.reveal(current);
}
}
}
@@ -671,13 +671,13 @@ the file in the file explorer and dragging it into the workspace.`
try {
await vscode.commands.executeCommand('revealFileInOS', uri);
} catch (e) {
showAndLogErrorMessage(e.message);
void showAndLogErrorMessage(e.message);
}
}
} else {
showAndLogErrorMessage(`Could not open file ${fileLocation}`);
logger.log(e.message);
logger.log(e.stack);
void showAndLogErrorMessage(`Could not open file ${fileLocation}`);
void logger.log(e.message);
void logger.log(e.stack);
}
}
}
@@ -729,7 +729,7 @@ the file in the file explorer and dragging it into the workspace.`
private assertSingleQuery(multiSelect: CompletedQuery[] = [], message = 'Please select a single query.') {
if (multiSelect.length > 1) {
showAndLogErrorMessage(
void showAndLogErrorMessage(
message
);
return false;
@@ -797,4 +797,3 @@ the file in the file explorer and dragging it into the workspace.`
this.treeDataProvider.refresh(completedQuery);
}
}

View File

@@ -30,7 +30,7 @@ class ServerProcess implements Disposable {
}
dispose(): void {
this.logger.log('Stopping query server...');
void this.logger.log('Stopping query server...');
this.connection.dispose();
this.child.stdin!.end();
this.child.stderr!.destroy();
@@ -38,7 +38,7 @@ class ServerProcess implements Disposable {
// On Windows, we usually have to terminate the process before closing its stdout.
this.child.stdout!.destroy();
this.logger.log('Stopped query server.');
void this.logger.log('Stopped query server.');
}
}
@@ -97,11 +97,11 @@ export class QueryServerClient extends DisposableObject {
if (!(await fs.pathExists(this.config.customLogDirectory))) {
await fs.mkdir(this.config.customLogDirectory);
}
this.logger.log(`Saving query server logs to user-specified directory: ${this.config.customLogDirectory}.`);
void this.logger.log(`Saving query server logs to user-specified directory: ${this.config.customLogDirectory}.`);
storagePath = this.config.customLogDirectory;
isCustomLogDirectory = true;
} catch (e) {
helpers.showAndLogErrorMessage(`${this.config.customLogDirectory} is not a valid directory. Logs will be stored in a temporary workspace directory instead.`);
void helpers.showAndLogErrorMessage(`${this.config.customLogDirectory} is not a valid directory. Logs will be stored in a temporary workspace directory instead.`);
}
}
@@ -118,7 +118,7 @@ export class QueryServerClient extends DisposableObject {
if (this.serverProcess !== undefined) {
this.disposeAndStopTracking(this.serverProcess);
} else {
this.logger.log('No server process to be stopped.');
void this.logger.log('No server process to be stopped.');
}
}
@@ -192,9 +192,8 @@ export class QueryServerClient extends DisposableObject {
const connection = createMessageConnection(child.stdout, child.stdin);
connection.onRequest(completeQuery, res => {
if (!(res.runId in this.evaluationResultCallbacks)) {
this.logger.log(`No callback associated with run id ${res.runId}, continuing without executing any callback`);
}
else {
void this.logger.log(`No callback associated with run id ${res.runId}, continuing without executing any callback`);
} else {
const baseLocation = this.logger.getBaseLocation();
if (baseLocation && this.activeQueryName) {
res.logFileLocation = path.join(baseLocation, this.activeQueryName);

View File

@@ -156,7 +156,7 @@ export class QueryInfo {
compiled = await qs.sendRequest(messages.compileQuery, params, token, progress);
} finally {
qs.logger.log(' - - - COMPILATION DONE - - - ');
void qs.logger.log(' - - - COMPILATION DONE - - - ');
}
return (compiled?.messages || []).filter(msg => msg.severity === messages.Severity.ERROR);
}
@@ -167,12 +167,12 @@ export class QueryInfo {
async canHaveInterpretedResults(): Promise<boolean> {
const hasMetadataFile = await this.dbItem.hasMetadataFile();
if (!hasMetadataFile) {
logger.log('Cannot produce interpreted results since the database does not have a .dbinfo or codeql-database.yml file.');
void logger.log('Cannot produce interpreted results since the database does not have a .dbinfo or codeql-database.yml file.');
}
const hasKind = !!this.metadata?.kind;
if (!hasKind) {
logger.log('Cannot produce interpreted results since the query does not have @kind metadata.');
void logger.log('Cannot produce interpreted results since the query does not have @kind metadata.');
}
const isTable = hasKind && this.metadata?.kind === 'table';
@@ -499,7 +499,7 @@ export async function determineSelectedQuery(selectedResourceUri: Uri | undefine
// then prompt the user to save it first.
if (editor !== undefined && editor.document.uri.fsPath === queryPath) {
if (await promptUserToSaveChanges(editor.document)) {
editor.document.save();
void editor.document.save();
}
}
@@ -562,7 +562,7 @@ export async function compileAndRunQueryAgainstDatabase(
const querySchemaName = path.basename(packConfig.dbscheme);
const dbSchemaName = path.basename(db.contents.dbSchemeUri.fsPath);
if (querySchemaName != dbSchemaName) {
logger.log(`Query schema was ${querySchemaName}, but database schema was ${dbSchemaName}.`);
void logger.log(`Query schema was ${querySchemaName}, but database schema was ${dbSchemaName}.`);
throw new Error(`The query ${path.basename(queryPath)} cannot be run against the selected database: their target languages are different. Please select a different database and try again.`);
}
@@ -584,7 +584,7 @@ export async function compileAndRunQueryAgainstDatabase(
metadata = await cliServer.resolveMetadata(qlProgram.queryPath);
} catch (e) {
// Ignore errors and provide no metadata.
logger.log(`Couldn't resolve metadata for ${qlProgram.queryPath}: ${e}`);
void logger.log(`Couldn't resolve metadata for ${qlProgram.queryPath}: ${e}`);
}
const query = new QueryInfo(qlProgram, db, packConfig.dbscheme, quickEvalPosition, metadata, templates);
@@ -612,8 +612,8 @@ export async function compileAndRunQueryAgainstDatabase(
const result = await query.run(qs, upgradeQlo, progress, token);
if (result.resultType !== messages.QueryResultType.SUCCESS) {
const message = result.message || 'Failed to run query';
logger.log(message);
showAndLogErrorMessage(message);
void logger.log(message);
void showAndLogErrorMessage(message);
}
return {
query,
@@ -633,7 +633,7 @@ export async function compileAndRunQueryAgainstDatabase(
// so we include a general description of the problem,
// and direct the user to the output window for the detailed compilation messages.
// However we don't show quick eval errors there so we need to display them anyway.
qs.logger.log(`Failed to compile query ${query.program.queryPath} against database scheme ${query.program.dbschemePath}:`);
void qs.logger.log(`Failed to compile query ${query.program.queryPath} against database scheme ${query.program.dbschemePath}:`);
const formattedMessages: string[] = [];
@@ -641,24 +641,24 @@ export async function compileAndRunQueryAgainstDatabase(
const message = error.message || '[no error message available]';
const formatted = `ERROR: ${message} (${error.position.fileName}:${error.position.line}:${error.position.column}:${error.position.endLine}:${error.position.endColumn})`;
formattedMessages.push(formatted);
qs.logger.log(formatted);
void qs.logger.log(formatted);
}
if (quickEval && formattedMessages.length <= 2) {
// If there are more than 2 error messages, they will not be displayed well in a popup
// and will be trimmed by the function displaying the error popup. Accordingly, we only
// try to show the errors if there are 2 or less, otherwise we direct the user to the log.
showAndLogErrorMessage('Quick evaluation compilation failed: ' + formattedMessages.join('\n'));
void showAndLogErrorMessage('Quick evaluation compilation failed: ' + formattedMessages.join('\n'));
} else {
showAndLogErrorMessage((quickEval ? 'Quick evaluation' : 'Query') + compilationFailedErrorTail);
void showAndLogErrorMessage((quickEval ? 'Quick evaluation' : 'Query') + compilationFailedErrorTail);
}
return createSyntheticResult(query, db, historyItemOptions, 'Query had compilation errors', messages.QueryResultType.OTHER_ERROR);
}
} finally {
try {
upgradeDir.cleanup();
await upgradeDir.cleanup();
} catch (e) {
qs.logger.log(`Could not clean up the upgrades dir. Reason: ${e.message || e}`);
void qs.logger.log(`Could not clean up the upgrades dir. Reason: ${e.message || e}`);
}
}
}

View File

@@ -20,7 +20,7 @@ export class CodeQlStatusBarHandler extends DisposableObject {
this.push(workspace.onDidChangeConfiguration(this.handleDidChangeConfiguration, this));
this.push(distributionConfigListener.onDidChangeConfiguration(() => this.updateStatusItem()));
this.item.command = 'codeQL.copyVersion';
this.updateStatusItem();
void this.updateStatusItem();
}
private handleDidChangeConfiguration(e: ConfigurationChangeEvent) {

View File

@@ -119,7 +119,7 @@ export class TelemetryListener extends ConfigListener {
}
if (LOG_TELEMETRY.getValue<boolean>()) {
logger.log(`Telemetry: ${JSON.stringify(envelope)}`);
void logger.log(`Telemetry: ${JSON.stringify(envelope)}`);
}
return true;
});
@@ -128,7 +128,7 @@ export class TelemetryListener extends ConfigListener {
dispose() {
super.dispose();
this.reporter?.dispose();
void this.reporter?.dispose();
}
sendCommandUsage(name: string, executionTime: number, error?: Error) {
@@ -187,7 +187,7 @@ export class TelemetryListener extends ConfigListener {
private disposeReporter() {
if (this.reporter) {
this.reporter.dispose();
void this.reporter.dispose();
this.reporter = undefined;
}
}
@@ -209,6 +209,6 @@ export let telemetryListener: TelemetryListener;
export async function initializeTelemetry(extension: Extension<any>, ctx: ExtensionContext): Promise<void> {
telemetryListener = new TelemetryListener(extension.id, extension.packageJSON.version, key, ctx);
telemetryListener.initialize();
await telemetryListener.initialize();
ctx.subscriptions.push(telemetryListener);
}

View File

@@ -218,7 +218,7 @@ export class QLTestAdapter extends DisposableObject implements TestAdapter {
// This method is invoked from Test Explorer UI, and testing indicates that Test
// Explorer UI swallows any thrown exception without reporting it to the user.
// So we need to display the error message ourselves and then rethrow.
showAndLogErrorMessage(`Cannot remove database ${database.name}: ${e}`);
void showAndLogErrorMessage(`Cannot remove database ${database.name}: ${e}`);
throw e;
}
}
@@ -242,7 +242,7 @@ export class QLTestAdapter extends DisposableObject implements TestAdapter {
// This method is invoked from Test Explorer UI, and testing indicates that Test
// Explorer UI swallows any thrown exception without reporting it to the user.
// So we need to display the error message ourselves and then rethrow.
showAndLogWarningMessage(`Cannot reopen database ${uri}: ${e}`);
void showAndLogWarningMessage(`Cannot reopen database ${uri}: ${e}`);
throw e;
}
}
@@ -268,7 +268,7 @@ export class QLTestAdapter extends DisposableObject implements TestAdapter {
public cancel(): void {
if (this.runningTask !== undefined) {
testLogger.log('Cancelling test run...');
void testLogger.log('Cancelling test run...');
this.runningTask.cancel();
this.clearTask();
}
@@ -288,7 +288,7 @@ export class QLTestAdapter extends DisposableObject implements TestAdapter {
let message: string | undefined;
if (event.failureDescription || event.diff?.length) {
message = ['', `${state}: ${event.test}`, event.failureDescription || event.diff?.join('\n'), ''].join('\n');
testLogger.log(message);
void testLogger.log(message);
}
this._testStates.fire({
type: 'test',

View File

@@ -44,7 +44,7 @@ export class TestUIService extends UIService implements TestController {
constructor(private readonly testHub: TestHub) {
super();
logger.log('Registering CodeQL test panel commands.');
void logger.log('Registering CodeQL test panel commands.');
this.registerCommand('codeQLTests.showOutputDifferences', this.showOutputDifferences);
this.registerCommand('codeQLTests.acceptOutput', this.acceptOutput);
@@ -90,7 +90,7 @@ export class TestUIService extends UIService implements TestController {
};
if (!await fs.pathExists(expectedPath)) {
showAndLogWarningMessage(`'${path.basename(expectedPath)}' does not exist. Creating an empty file.`);
void showAndLogWarningMessage(`'${path.basename(expectedPath)}' does not exist. Creating an empty file.`);
await fs.createFile(expectedPath);
}

View File

@@ -103,7 +103,7 @@ async function checkAndConfirmDatabaseUpgrade(
descriptionMessage += `Would perform upgrade: ${script.description}\n`;
descriptionMessage += `\t-> Compatibility: ${script.compatibility}\n`;
}
logger.log(descriptionMessage);
void logger.log(descriptionMessage);
// If the quiet flag is set, do the upgrade without a popup.
@@ -187,35 +187,35 @@ export async function upgradeDatabaseExplicit(
compileUpgradeResult = await compileDatabaseUpgrade(qs, db, finalDbscheme, scripts, currentUpgradeTmp, progress, token);
}
catch (e) {
showAndLogErrorMessage(`Compilation of database upgrades failed: ${e}`);
void showAndLogErrorMessage(`Compilation of database upgrades failed: ${e}`);
return;
}
finally {
qs.logger.log('Done compiling database upgrade.');
void qs.logger.log('Done compiling database upgrade.');
}
if (!compileUpgradeResult.compiledUpgrades) {
const error = compileUpgradeResult.error || '[no error message available]';
showAndLogErrorMessage(`Compilation of database upgrades failed: ${error}`);
void showAndLogErrorMessage(`Compilation of database upgrades failed: ${error}`);
return;
}
await checkAndConfirmDatabaseUpgrade(compileUpgradeResult.compiledUpgrades, db, qs.cliServer.quiet);
try {
qs.logger.log('Running the following database upgrade:');
void qs.logger.log('Running the following database upgrade:');
getUpgradeDescriptions(compileUpgradeResult.compiledUpgrades).map(s => s.description).join('\n');
return await runDatabaseUpgrade(qs, db, compileUpgradeResult.compiledUpgrades, progress, token);
}
catch (e) {
showAndLogErrorMessage(`Database upgrade failed: ${e}`);
void showAndLogErrorMessage(`Database upgrade failed: ${e}`);
return;
} finally {
qs.logger.log('Done running database upgrade.');
void qs.logger.log('Done running database upgrade.');
}
} finally {
currentUpgradeTmp.cleanup();
await currentUpgradeTmp.cleanup();
}
}

View File

@@ -102,7 +102,7 @@ class App extends React.Component<{}, ResultsViewState> {
queryPath: msg.queryPath,
});
this.loadResults();
void this.loadResults();
break;
case 'showInterpretedPage':
this.updateStateWithNewResultsInfo({
@@ -134,7 +134,7 @@ class App extends React.Component<{}, ResultsViewState> {
queryName: msg.queryName,
queryPath: msg.queryPath,
});
this.loadResults();
void this.loadResults();
break;
case 'resultsUpdating':
this.setState({

View File

@@ -27,7 +27,7 @@ export default function(mocha: Mocha) {
if (!fs.existsSync(dbLoc)) {
try {
await new Promise((resolve, reject) => {
fetch(DB_URL).then(response => {
return fetch(DB_URL).then(response => {
const dest = fs.createWriteStream(dbLoc);
response.body.pipe(dest);

View File

@@ -119,7 +119,7 @@ describe('using the query server', function() {
it('should be able to start the query server', async function() {
await qs.startQueryServer();
queryServerStarted.resolve();
await queryServerStarted.resolve();
});
for (const queryTestCase of queryTestCases) {
@@ -160,10 +160,10 @@ describe('using the query server', function() {
};
const result = await qs.sendRequest(messages.compileQuery, params, token, () => { /**/ });
expect(result.messages!.length).to.equal(0);
compilationSucceeded.resolve();
await compilationSucceeded.resolve();
}
catch (e) {
compilationSucceeded.reject(e);
await compilationSucceeded.reject(e);
}
});
@@ -171,7 +171,7 @@ describe('using the query server', function() {
try {
await compilationSucceeded.done();
const callbackId = qs.registerCallback(_res => {
evaluationSucceeded.resolve();
void evaluationSucceeded.resolve();
});
const queryToRun: messages.QueryToRun = {
resultsPath: RESULTS_PATH,
@@ -190,7 +190,7 @@ describe('using the query server', function() {
await qs.sendRequest(messages.runQueries, params, token, () => { /**/ });
}
catch (e) {
evaluationSucceeded.reject(e);
await evaluationSucceeded.reject(e);
}
});
@@ -203,7 +203,7 @@ describe('using the query server', function() {
const decoded = await cliServer.bqrsDecode(RESULTS_PATH, resultSet.name);
actualResultSets[resultSet.name] = decoded.tuples;
}
parsedResults.resolve();
await parsedResults.resolve();
});
it(`should have correct results for query ${queryName}`, async function() {

View File

@@ -135,7 +135,7 @@ describe('AstBuilder', () => {
};
const astBuilder = createAstBuilder();
expect(astBuilder.getRoots()).to.be.rejectedWith('AST is invalid');
await expect(astBuilder.getRoots()).to.be.rejectedWith('AST is invalid');
});
function createAstBuilder() {

View File

@@ -69,7 +69,7 @@ describe('databaseFetcher', function() {
it('should fail on a nonexistent project', async () => {
quickPickSpy.resolves('javascript');
const lgtmUrl = 'https://lgtm.com/projects/g/github/hucairz';
expect(convertToDatabaseUrl(lgtmUrl)).to.rejectedWith(/Invalid LGTM URL/);
await expect(convertToDatabaseUrl(lgtmUrl)).to.rejectedWith(/Invalid LGTM URL/);
});
});

View File

@@ -105,7 +105,7 @@ async function main() {
}
}
main();
void main();
function getLaunchArgs(dir: TestDir) {