From 45ffd8a45c3a5426910ac59efaab75aba32ef871 Mon Sep 17 00:00:00 2001 From: Charis Kyriakou Date: Wed, 30 Nov 2022 09:59:44 +0000 Subject: [PATCH 1/2] Tidy up logging docs --- .../ql-vscode/src/common/logging/logger.ts | 23 ++++++++++++++----- .../src/common/logging/vscode/loggers.ts | 12 ++++++---- .../logging/vscode/output-channel-logger.ts | 14 ++++------- 3 files changed, 29 insertions(+), 20 deletions(-) diff --git a/extensions/ql-vscode/src/common/logging/logger.ts b/extensions/ql-vscode/src/common/logging/logger.ts index b66cb1054..89fc1e54b 100644 --- a/extensions/ql-vscode/src/common/logging/logger.ts +++ b/extensions/ql-vscode/src/common/logging/logger.ts @@ -1,23 +1,34 @@ export interface LogOptions { - /** If false, don't output a trailing newline for the log entry. Default true. */ + // If false, don't output a trailing newline for the log entry. Default true. trailingNewline?: boolean; - /** If specified, add this log entry to the log file at the specified location. */ + // If specified, add this log entry to the log file at the specified location. additionalLogLocation?: string; } export interface Logger { - /** Writes the given log message, optionally followed by a newline. */ - log(message: string, options?: LogOptions): Promise; /** - * Reveal this channel in the UI. + * Writes the given log message, optionally followed by a newline. + * This function is asynchronous and will only resolve once the message is written + * to the side log (if required). It is not necessary to await the results of this + * function if you don't need to guarantee that the log writing is complete before + * continuing. + * + * @param message The message to log. + * @param options Optional settings. + */ + log(message: string, options?: LogOptions): Promise; + + /** + * Reveal the logger channel in the UI. * * @param preserveFocus When `true` the channel will not take focus. */ show(preserveFocus?: boolean): void; /** - * Remove the log at the specified location + * Remove the log at the specified location. + * * @param location log to remove */ removeAdditionalLogLocation(location: string | undefined): void; diff --git a/extensions/ql-vscode/src/common/logging/vscode/loggers.ts b/extensions/ql-vscode/src/common/logging/vscode/loggers.ts index abebd2fa5..af7eb5258 100644 --- a/extensions/ql-vscode/src/common/logging/vscode/loggers.ts +++ b/extensions/ql-vscode/src/common/logging/vscode/loggers.ts @@ -1,15 +1,19 @@ +/** + * This module contains instantiated loggers to use in the extension. + */ + import { OutputChannelLogger } from "./output-channel-logger"; -/** The global logger for the extension. */ +// Global logger for the extension. export const logger = new OutputChannelLogger("CodeQL Extension Log"); -/** The logger for messages from the query server. */ +// Logger for messages from the query server. export const queryServerLogger = new OutputChannelLogger("CodeQL Query Server"); -/** The logger for messages from the language server. */ +// Logger for messages from the language server. export const ideServerLogger = new OutputChannelLogger( "CodeQL Language Server", ); -/** The logger for messages from tests. */ +// Logger for messages from tests. export const testLogger = new OutputChannelLogger("CodeQL Tests"); diff --git a/extensions/ql-vscode/src/common/logging/vscode/output-channel-logger.ts b/extensions/ql-vscode/src/common/logging/vscode/output-channel-logger.ts index c8b37bfbe..f4646a0f5 100644 --- a/extensions/ql-vscode/src/common/logging/vscode/output-channel-logger.ts +++ b/extensions/ql-vscode/src/common/logging/vscode/output-channel-logger.ts @@ -4,7 +4,9 @@ import * as path from "path"; import { Logger, LogOptions } from "../logger"; import { DisposableObject } from "../../../pure/disposable-object"; -/** A logger that writes messages to an output channel in the Output tab. */ +/** + * A logger that writes messages to an output channel in the VS Code Output tab. + */ export class OutputChannelLogger extends DisposableObject implements Logger { public readonly outputChannel: OutputChannel; private readonly additionalLocations = new Map< @@ -20,12 +22,6 @@ export class OutputChannelLogger extends DisposableObject implements Logger { this.isCustomLogDirectory = false; } - /** - * This function is asynchronous and will only resolve once the message is written - * to the side log (if required). It is not necessary to await the results of this - * function if you don't need to guarantee that the log writing is complete before - * continuing. - */ async log(message: string, options = {} as LogOptions): Promise { try { if (options.trailingNewline === undefined) { @@ -82,9 +78,7 @@ export class OutputChannelLogger extends DisposableObject implements Logger { } class AdditionalLogLocation { - constructor(private location: string) { - /**/ - } + constructor(private location: string) {} async log(message: string, options = {} as LogOptions): Promise { if (options.trailingNewline === undefined) { From c889c0958407779d5ad151e10c72af2f1f42e991 Mon Sep 17 00:00:00 2001 From: Charis Kyriakou Date: Wed, 30 Nov 2022 13:53:17 +0000 Subject: [PATCH 2/2] Rename logger to extLogger --- .../src/archive-filesystem-provider.ts | 6 +- extensions/ql-vscode/src/commandRunner.ts | 6 +- .../src/common/logging/vscode/loggers.ts | 2 +- extensions/ql-vscode/src/config.ts | 4 +- .../ql-vscode/src/contextual/queryResolver.ts | 12 ++-- extensions/ql-vscode/src/databaseFetcher.ts | 6 +- extensions/ql-vscode/src/databases-ui.ts | 12 ++-- extensions/ql-vscode/src/databases.ts | 16 ++--- .../ql-vscode/src/databases/db-module.ts | 4 +- extensions/ql-vscode/src/discovery.ts | 4 +- extensions/ql-vscode/src/distribution.ts | 25 ++++--- extensions/ql-vscode/src/extension.ts | 71 ++++++++++--------- extensions/ql-vscode/src/helpers.ts | 22 +++--- .../src/legacy-query-server/run-queries.ts | 12 ++-- .../src/legacy-query-server/upgrades.ts | 6 +- .../src/log-insights/log-scanner-service.ts | 4 +- .../log-insights/summary-language-support.ts | 4 +- extensions/ql-vscode/src/packaging.ts | 4 +- .../ql-vscode/src/query-history-scrubber.ts | 22 +++--- extensions/ql-vscode/src/query-history.ts | 22 +++--- .../ql-vscode/src/query-server/run-queries.ts | 4 +- .../src/remote-queries/export-results.ts | 10 +-- .../gh-api/gh-actions-api-client.ts | 6 +- .../remote-queries/repository-selection.ts | 10 +-- .../src/remote-queries/run-remote-query.ts | 18 ++--- .../remote-queries/variant-analysis-view.ts | 4 +- .../ql-vscode/src/run-queries-shared.ts | 6 +- extensions/ql-vscode/src/telemetry.ts | 4 +- extensions/ql-vscode/src/test-ui.ts | 4 +- .../cli-integration/legacy-query.test.ts | 4 +- .../cli-integration/new-query.test.ts | 4 +- .../variant-analysis-manager.test.ts | 6 +- .../variant-analysis-results-manager.test.ts | 6 +- .../no-workspace/distribution.test.ts | 6 +- .../no-workspace/query-history.test.ts | 4 +- 35 files changed, 184 insertions(+), 176 deletions(-) diff --git a/extensions/ql-vscode/src/archive-filesystem-provider.ts b/extensions/ql-vscode/src/archive-filesystem-provider.ts index 8681d681a..6ef1b6d7d 100644 --- a/extensions/ql-vscode/src/archive-filesystem-provider.ts +++ b/extensions/ql-vscode/src/archive-filesystem-provider.ts @@ -1,7 +1,7 @@ import * as fs from "fs-extra"; import * as unzipper from "unzipper"; import * as vscode from "vscode"; -import { logger } from "./common"; +import { extLogger } from "./common"; // All path operations in this file must be on paths *within* the zip // archive. @@ -118,7 +118,7 @@ class InvalidSourceArchiveUriError extends Error { export function decodeSourceArchiveUri(uri: vscode.Uri): ZipFileReference { if (!uri.authority) { // Uri is malformed, but this is recoverable - void logger.log( + void extLogger.log( `Warning: ${new InvalidSourceArchiveUriError(uri).message}`, ); return { @@ -148,7 +148,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)`; - void logger.log(error); + void extLogger.log(error); throw new Error(error); } ensureDir(map, dirname); diff --git a/extensions/ql-vscode/src/commandRunner.ts b/extensions/ql-vscode/src/commandRunner.ts index a0881d4b4..8b9fa1013 100644 --- a/extensions/ql-vscode/src/commandRunner.ts +++ b/extensions/ql-vscode/src/commandRunner.ts @@ -7,7 +7,7 @@ import { ProgressLocation, } from "vscode"; import { showAndLogErrorMessage, showAndLogWarningMessage } from "./helpers"; -import { logger } from "./common"; +import { extLogger } from "./common"; import { getErrorMessage, getErrorStack } from "./pure/helpers-pure"; import { telemetryListener } from "./telemetry"; @@ -131,7 +131,7 @@ export function commandRunner( if (e instanceof UserCancellationException) { // User has cancelled this action manually if (e.silent) { - void logger.log(errorMessage); + void extLogger.log(errorMessage); } else { void showAndLogWarningMessage(errorMessage); } @@ -166,7 +166,7 @@ export function commandRunnerWithProgress( commandId: string, task: ProgressTask, progressOptions: Partial, - outputLogger = logger, + outputLogger = extLogger, ): Disposable { return commands.registerCommand(commandId, async (...args: any[]) => { const startTime = Date.now(); diff --git a/extensions/ql-vscode/src/common/logging/vscode/loggers.ts b/extensions/ql-vscode/src/common/logging/vscode/loggers.ts index af7eb5258..ff91b00fb 100644 --- a/extensions/ql-vscode/src/common/logging/vscode/loggers.ts +++ b/extensions/ql-vscode/src/common/logging/vscode/loggers.ts @@ -5,7 +5,7 @@ import { OutputChannelLogger } from "./output-channel-logger"; // Global logger for the extension. -export const logger = new OutputChannelLogger("CodeQL Extension Log"); +export const extLogger = new OutputChannelLogger("CodeQL Extension Log"); // Logger for messages from the query server. export const queryServerLogger = new OutputChannelLogger("CodeQL Query Server"); diff --git a/extensions/ql-vscode/src/config.ts b/extensions/ql-vscode/src/config.ts index 5ac442afe..56b2fc1e5 100644 --- a/extensions/ql-vscode/src/config.ts +++ b/extensions/ql-vscode/src/config.ts @@ -7,7 +7,7 @@ import { ConfigurationTarget, } from "vscode"; import { DistributionManager } from "./distribution"; -import { logger } from "./common"; +import { extLogger } from "./common"; import { ONE_DAY_IN_MS } from "./pure/time"; export const ALL_SETTINGS: Setting[] = []; @@ -349,7 +349,7 @@ export class QueryServerConfigListener return undefined; } if (memory == 0 || typeof memory !== "number") { - void logger.log( + void extLogger.log( `Ignoring value '${memory}' for setting ${MEMORY_SETTING.qualifiedName}`, ); return undefined; diff --git a/extensions/ql-vscode/src/contextual/queryResolver.ts b/extensions/ql-vscode/src/contextual/queryResolver.ts index ecb2f30d7..e3be499e5 100644 --- a/extensions/ql-vscode/src/contextual/queryResolver.ts +++ b/extensions/ql-vscode/src/contextual/queryResolver.ts @@ -8,7 +8,7 @@ import { KeyType, kindOfKeyType, nameOfKeyType, tagOfKeyType } from "./keyType"; import { CodeQLCliServer } from "../cli"; import { DatabaseItem } from "../databases"; import { QlPacksForLanguage } from "../helpers"; -import { logger } from "../common"; +import { extLogger } from "../common"; import { createInitialQueryInfo } from "../run-queries-shared"; import { CancellationToken, Uri } from "vscode"; import { ProgressCallback } from "../commandRunner"; @@ -161,17 +161,17 @@ async function resolveContextualQuery( // No lock file, likely because this library pack is in the package cache. // Create a lock file so that we can resolve dependencies and library path // for the contextual query. - void logger.log( + void extLogger.log( `Library pack ${packPath} is missing a lock file; creating a temporary lock file`, ); await cli.packResolveDependencies(packPath); createdTempLockFile = true; // Clear CLI server pack cache before installing dependencies, // so that it picks up the new lock file, not the previously cached pack. - void logger.log("Clearing the CodeQL CLI server's pack cache"); + void extLogger.log("Clearing the CodeQL CLI server's pack cache"); await cli.clearCache(); // Install dependencies. - void logger.log( + void extLogger.log( `Installing package dependencies for library pack ${packPath}`, ); await cli.packInstall(packPath); @@ -181,7 +181,7 @@ async function resolveContextualQuery( async function removeTemporaryLockFile(packPath: string) { const tempLockFilePath = path.resolve(packPath, "codeql-pack.lock.yml"); - void logger.log( + void extLogger.log( `Deleting temporary package lock file at ${tempLockFilePath}`, ); // It's fine if the file doesn't exist. @@ -212,7 +212,7 @@ export async function runContextualQuery( }, false, ); - void logger.log( + void extLogger.log( `Running contextual query ${query}; results will be stored in ${queryStorageDir}`, ); const queryResult = await qs.compileAndRunQueryAgainstDatabase( diff --git a/extensions/ql-vscode/src/databaseFetcher.ts b/extensions/ql-vscode/src/databaseFetcher.ts index 40d5a9546..4415d01c0 100644 --- a/extensions/ql-vscode/src/databaseFetcher.ts +++ b/extensions/ql-vscode/src/databaseFetcher.ts @@ -11,7 +11,7 @@ import { retry } from "@octokit/plugin-retry"; import { DatabaseManager, DatabaseItem } from "./databases"; import { showAndLogInformationMessage } from "./helpers"; import { reportStreamProgress, ProgressCallback } from "./commandRunner"; -import { logger } from "./common"; +import { extLogger } from "./common"; import { tmpDir } from "./helpers"; import { Credentials } from "./authentication"; import { REPO_REGEX, getErrorMessage } from "./pure/helpers-pure"; @@ -585,7 +585,7 @@ export async function convertGithubNwoToDatabaseUrl( name: repo, }; } catch (e) { - void logger.log(`Error: ${getErrorMessage(e)}`); + void extLogger.log(`Error: ${getErrorMessage(e)}`); throw new Error(`Unable to get database for '${githubRepo}'`); } } @@ -696,7 +696,7 @@ export async function convertLgtmUrlToDatabaseUrl( language, ].join("/")}`; } catch (e) { - void logger.log(`Error: ${getErrorMessage(e)}`); + void extLogger.log(`Error: ${getErrorMessage(e)}`); throw new Error(`Invalid LGTM URL: ${lgtmUrl}`); } } diff --git a/extensions/ql-vscode/src/databases-ui.ts b/extensions/ql-vscode/src/databases-ui.ts index 902ba0532..fcf450439 100644 --- a/extensions/ql-vscode/src/databases-ui.ts +++ b/extensions/ql-vscode/src/databases-ui.ts @@ -27,7 +27,7 @@ import { isLikelyDbLanguageFolder, showAndLogErrorMessage, } from "./helpers"; -import { logger } from "./common"; +import { extLogger } from "./common"; import { importArchiveDatabase, promptImportGithubDatabase, @@ -241,7 +241,7 @@ export class DatabaseUI extends DisposableObject { } init() { - void logger.log("Registering database panel commands."); + void extLogger.log("Registering database panel commands."); this.push( commandRunnerWithProgress( "codeQL.setCurrentDatabase", @@ -393,14 +393,14 @@ export class DatabaseUI extends DisposableObject { }; handleRemoveOrphanedDatabases = async (): Promise => { - void logger.log("Removing orphaned databases from workspace storage."); + void extLogger.log("Removing orphaned databases from workspace storage."); let dbDirs = undefined; if ( !(await fs.pathExists(this.storagePath)) || !(await fs.stat(this.storagePath)).isDirectory() ) { - void logger.log( + void extLogger.log( "Missing or invalid storage directory. Not trying to remove orphaned databases.", ); return; @@ -425,7 +425,7 @@ export class DatabaseUI extends DisposableObject { dbDirs = await asyncFilter(dbDirs, isLikelyDatabaseRoot); if (!dbDirs.length) { - void logger.log("No orphaned databases found."); + void extLogger.log("No orphaned databases found."); return; } @@ -434,7 +434,7 @@ export class DatabaseUI extends DisposableObject { await Promise.all( dbDirs.map(async (dbDir) => { try { - void logger.log(`Deleting orphaned database '${dbDir}'.`); + void extLogger.log(`Deleting orphaned database '${dbDir}'.`); await fs.remove(dbDir); } catch (e) { failures.push(`${path.basename(dbDir)}`); diff --git a/extensions/ql-vscode/src/databases.ts b/extensions/ql-vscode/src/databases.ts index f27b43f4d..8c4f116ca 100644 --- a/extensions/ql-vscode/src/databases.ts +++ b/extensions/ql-vscode/src/databases.ts @@ -18,7 +18,7 @@ import { encodeSourceArchiveUri, } from "./archive-filesystem-provider"; import { DisposableObject } from "./pure/disposable-object"; -import { Logger, logger } from "./common"; +import { Logger, extLogger } from "./common"; import { getErrorMessage } from "./pure/helpers-pure"; import { QueryRunner } from "./queryRunner"; @@ -545,7 +545,7 @@ function eventFired( ): Promise { return new Promise((res, _rej) => { const timeout = setTimeout(() => { - void logger.log( + void extLogger.log( `Waiting for event ${event} timed out after ${timeoutMs}ms`, ); res(undefined); @@ -657,12 +657,12 @@ export class DatabaseManager extends DisposableObject { const msg = item.verifyZippedSources(); if (msg) { - void logger.log(`Could not add source folder because ${msg}`); + void extLogger.log(`Could not add source folder because ${msg}`); return; } const uri = item.getSourceArchiveExplorerUri(); - void logger.log( + void extLogger.log( `Adding workspace folder for ${item.name} source archive at index ${end}`, ); if ((vscode.workspace.workspaceFolders || []).length < 2) { @@ -916,7 +916,7 @@ export class DatabaseManager extends DisposableObject { (folder) => item.belongsToSourceArchiveExplorerUri(folder.uri), ); if (folderIndex >= 0) { - void logger.log(`Removing workspace folder at index ${folderIndex}`); + void extLogger.log(`Removing workspace folder at index ${folderIndex}`); vscode.workspace.updateWorkspaceFolders(folderIndex, 1); } @@ -925,11 +925,11 @@ export class DatabaseManager extends DisposableObject { // Delete folder from file system only if it is controlled by the extension if (this.isExtensionControlledLocation(item.databaseUri)) { - void logger.log("Deleting database from filesystem."); + void extLogger.log("Deleting database from filesystem."); fs.remove(item.databaseUri.fsPath).then( - () => void logger.log(`Deleted '${item.databaseUri.fsPath}'`), + () => void extLogger.log(`Deleted '${item.databaseUri.fsPath}'`), (e) => - void logger.log( + void extLogger.log( `Failed to delete '${ item.databaseUri.fsPath }'. Reason: ${getErrorMessage(e)}`, diff --git a/extensions/ql-vscode/src/databases/db-module.ts b/extensions/ql-vscode/src/databases/db-module.ts index d7e08bfa4..95348525a 100644 --- a/extensions/ql-vscode/src/databases/db-module.ts +++ b/extensions/ql-vscode/src/databases/db-module.ts @@ -1,6 +1,6 @@ import { App, AppMode } from "../common/app"; import { isCanary, isNewQueryRunExperienceEnabled } from "../config"; -import { logger } from "../common"; +import { extLogger } from "../common"; import { DisposableObject } from "../pure/disposable-object"; import { DbConfigStore } from "./config/db-config-store"; import { DbManager } from "./db-manager"; @@ -19,7 +19,7 @@ export class DbModule extends DisposableObject { return; } - void logger.log("Initializing database module"); + void extLogger.log("Initializing database module"); const dbConfigStore = new DbConfigStore(app); await dbConfigStore.initialize(); diff --git a/extensions/ql-vscode/src/discovery.ts b/extensions/ql-vscode/src/discovery.ts index 95baaa2dc..117df4fd9 100644 --- a/extensions/ql-vscode/src/discovery.ts +++ b/extensions/ql-vscode/src/discovery.ts @@ -1,5 +1,5 @@ import { DisposableObject } from "./pure/disposable-object"; -import { logger } from "./common"; +import { extLogger } from "./common"; /** * Base class for "discovery" operations, which scan the file system to find specific kinds of @@ -62,7 +62,7 @@ export abstract class Discovery extends DisposableObject { }) .catch((err) => { - void logger.log(`${this.name} failed. Reason: ${err.message}`); + void extLogger.log(`${this.name} failed. Reason: ${err.message}`); }) .finally(() => { diff --git a/extensions/ql-vscode/src/distribution.ts b/extensions/ql-vscode/src/distribution.ts index 2e9563296..68ad27ed0 100644 --- a/extensions/ql-vscode/src/distribution.ts +++ b/extensions/ql-vscode/src/distribution.ts @@ -12,7 +12,7 @@ import { showAndLogErrorMessage, showAndLogWarningMessage, } from "./helpers"; -import { logger } from "./common"; +import { extLogger } from "./common"; import { getCodeQlCliVersion } from "./cli-version"; import { ProgressCallback, reportStreamProgress } from "./commandRunner"; import { @@ -90,7 +90,10 @@ export class DistributionManager implements DistributionProvider { kind: FindDistributionResultKind.NoDistribution, }; } - const version = await getCodeQlCliVersion(distribution.codeQlPath, logger); + const version = await getCodeQlCliVersion( + distribution.codeQlPath, + extLogger, + ); if (version === undefined) { return { distribution, @@ -196,7 +199,7 @@ export class DistributionManager implements DistributionProvider { }; } } - void logger.log("INFO: Could not find CodeQL on path."); + void extLogger.log("INFO: Could not find CodeQL on path."); } return undefined; @@ -292,7 +295,7 @@ class ExtensionSpecificDistributionManager { try { await this.removeDistribution(); } catch (e) { - void logger.log( + void extLogger.log( "WARNING: Tried to remove corrupted CodeQL CLI at " + `${this.getDistributionStoragePath()} but encountered an error: ${e}.`, ); @@ -343,7 +346,7 @@ class ExtensionSpecificDistributionManager { try { await this.removeDistribution(); } catch (e) { - void logger.log( + void extLogger.log( `Tried to clean up old version of CLI at ${this.getDistributionStoragePath()} ` + `but encountered an error: ${e}.`, ); @@ -360,7 +363,7 @@ class ExtensionSpecificDistributionManager { ); } if (assets.length > 1) { - void logger.log( + void extLogger.log( "WARNING: chose a release with more than one asset to install, found " + assets.map((asset) => asset.name).join(", "), ); @@ -398,7 +401,7 @@ class ExtensionSpecificDistributionManager { await this.bumpDistributionFolderIndex(); - void logger.log( + void extLogger.log( `Extracting CodeQL CLI to ${this.getDistributionStoragePath()}`, ); await extractZipArchive(archivePath, this.getDistributionStoragePath()); @@ -421,7 +424,7 @@ class ExtensionSpecificDistributionManager { private async getLatestRelease(): Promise { const requiredAssetName = getRequiredAssetName(); - void logger.log( + void extLogger.log( `Searching for latest release including ${requiredAssetName}.`, ); return this.createReleasesApiConsumer().getLatestRelease( @@ -433,13 +436,13 @@ class ExtensionSpecificDistributionManager { ); if (matchingAssets.length === 0) { // For example, this could be a release with no platform-specific assets. - void logger.log( + void extLogger.log( `INFO: Ignoring a release with no assets named ${requiredAssetName}`, ); return false; } if (matchingAssets.length > 1) { - void logger.log( + void extLogger.log( `WARNING: Ignoring a release with more than one asset named ${requiredAssetName}`, ); return false; @@ -817,7 +820,7 @@ export async function getExecutableFromDirectory( return alternateExpectedLauncherPath; } if (warnWhenNotFound) { - void logger.log( + void extLogger.log( `WARNING: Expected to find a CodeQL CLI executable at ${expectedLauncherPath} but one was not found. ` + "Will try PATH.", ); diff --git a/extensions/ql-vscode/src/extension.ts b/extensions/ql-vscode/src/extension.ts index 0a77389fd..4b9584896 100644 --- a/extensions/ql-vscode/src/extension.ts +++ b/extensions/ql-vscode/src/extension.ts @@ -76,7 +76,7 @@ import { ResultsView } from "./interface"; import { WebviewReveal } from "./interface-utils"; import { ideServerLogger, - logger, + extLogger, ProgressReporter, queryServerLogger, } from "./common"; @@ -230,7 +230,7 @@ const MIN_VERSION = "1.67.0"; export async function activate( ctx: ExtensionContext, ): Promise> { - void logger.log(`Starting ${extensionId} extension`); + void extLogger.log(`Starting ${extensionId} extension`); if (extension === undefined) { throw new Error(`Can't find extension ${extensionId}`); } @@ -278,7 +278,7 @@ export async function activate( const minSecondsSinceLastUpdateCheck = config.isUserInitiated ? 0 : 86400; const noUpdatesLoggingFunc = config.shouldDisplayMessageWhenNoUpdates ? showAndLogInformationMessage - : async (message: string) => void logger.log(message); + : async (message: string) => void extLogger.log(message); const result = await distributionManager.checkForUpdatesToExtensionManagedDistribution( minSecondsSinceLastUpdateCheck, @@ -291,7 +291,7 @@ export async function activate( switch (result.kind) { case DistributionUpdateCheckResultKind.AlreadyCheckedRecentlyResult: - void logger.log( + void extLogger.log( "Didn't perform CodeQL CLI update check since a check was already performed within the previous " + `${minSecondsSinceLastUpdateCheck} seconds.`, ); @@ -400,7 +400,7 @@ export async function activate( const result = await distributionManager.getDistribution(); switch (result.kind) { case FindDistributionResultKind.CompatibleDistribution: - void logger.log( + void extLogger.log( `Found compatible version of CodeQL CLI (version ${result.version.raw})`, ); break; @@ -543,18 +543,18 @@ async function activateWithInstalledDistribution( // of activation. errorStubs.forEach((stub) => stub.dispose()); - void logger.log("Initializing configuration listener..."); + void extLogger.log("Initializing configuration listener..."); const qlConfigurationListener = await QueryServerConfigListener.createQueryServerConfigListener( distributionManager, ); ctx.subscriptions.push(qlConfigurationListener); - void logger.log("Initializing CodeQL cli server..."); + void extLogger.log("Initializing CodeQL cli server..."); const cliServer = new CodeQLCliServer( distributionManager, new CliConfigListener(), - logger, + extLogger, ); ctx.subscriptions.push(cliServer); @@ -564,7 +564,7 @@ async function activateWithInstalledDistribution( ); ctx.subscriptions.push(statusBar); - void logger.log("Initializing query server client."); + void extLogger.log("Initializing query server client."); const qs = await createQueryServer(qlConfigurationListener, cliServer, ctx); for (const glob of PACK_GLOBS) { @@ -575,14 +575,14 @@ async function activateWithInstalledDistribution( }); } - void logger.log("Initializing database manager."); - const dbm = new DatabaseManager(ctx, qs, cliServer, logger); + void extLogger.log("Initializing database manager."); + const dbm = new DatabaseManager(ctx, qs, cliServer, extLogger); // Let this run async. void dbm.loadPersistedState(); ctx.subscriptions.push(dbm); - void logger.log("Initializing database panel."); + void extLogger.log("Initializing database panel."); const databaseUI = new DatabaseUI( dbm, qs, @@ -593,11 +593,11 @@ async function activateWithInstalledDistribution( databaseUI.init(); ctx.subscriptions.push(databaseUI); - void logger.log("Initializing evaluator log viewer."); + void extLogger.log("Initializing evaluator log viewer."); const evalLogViewer = new EvalLogViewer(); ctx.subscriptions.push(evalLogViewer); - void logger.log("Initializing query history manager."); + void extLogger.log("Initializing query history manager."); const queryHistoryConfigurationListener = new QueryHistoryConfigListener(); ctx.subscriptions.push(queryHistoryConfigurationListener); const showResults = async (item: CompletedLocalQueryInfo) => @@ -608,7 +608,7 @@ async function activateWithInstalledDistribution( queryHistoryConfigurationListener, ); - void logger.log("Initializing results panel interface."); + void extLogger.log("Initializing results panel interface."); const localQueryResultsView = new ResultsView( ctx, dbm, @@ -618,7 +618,7 @@ async function activateWithInstalledDistribution( ); ctx.subscriptions.push(localQueryResultsView); - void logger.log("Initializing variant analysis manager."); + void extLogger.log("Initializing variant analysis manager."); const variantAnalysisStorageDir = path.join( ctx.globalStorageUri.fsPath, "variant-analyses", @@ -626,7 +626,7 @@ async function activateWithInstalledDistribution( await fs.ensureDir(variantAnalysisStorageDir); const variantAnalysisResultsManager = new VariantAnalysisResultsManager( cliServer, - logger, + extLogger, ); const variantAnalysisManager = new VariantAnalysisManager( ctx, @@ -643,11 +643,16 @@ async function activateWithInstalledDistribution( ), ); - void logger.log("Initializing remote queries manager."); - const rqm = new RemoteQueriesManager(ctx, cliServer, queryStorageDir, logger); + void extLogger.log("Initializing remote queries manager."); + const rqm = new RemoteQueriesManager( + ctx, + cliServer, + queryStorageDir, + extLogger, + ); ctx.subscriptions.push(rqm); - void logger.log("Initializing query history."); + void extLogger.log("Initializing query history."); const qhm = new QueryHistoryManager( qs, dbm, @@ -665,7 +670,7 @@ async function activateWithInstalledDistribution( ctx.subscriptions.push(qhm); - void logger.log("Initializing evaluation log scanners."); + void extLogger.log("Initializing evaluation log scanners."); const logScannerService = new LogScannerService(qhm); ctx.subscriptions.push(logScannerService); ctx.subscriptions.push( @@ -674,7 +679,7 @@ async function activateWithInstalledDistribution( ), ); - void logger.log("Initializing compare view."); + void extLogger.log("Initializing compare view."); const compareView = new CompareView( ctx, dbm, @@ -685,7 +690,7 @@ async function activateWithInstalledDistribution( ); ctx.subscriptions.push(compareView); - void logger.log("Initializing source archive filesystem provider."); + void extLogger.log("Initializing source archive filesystem provider."); archiveFilesystemProvider.activate(ctx); async function showResultsForComparison( @@ -821,7 +826,7 @@ async function activateWithInstalledDistribution( ctx.subscriptions.push(tmpDirDisposal); - void logger.log("Initializing CodeQL language server."); + void extLogger.log("Initializing CodeQL language server."); const client = new LanguageClient( "CodeQL Language Server", () => spawnIdeServer(qlConfigurationListener), @@ -839,7 +844,7 @@ async function activateWithInstalledDistribution( true, ); - void logger.log("Initializing QLTest interface."); + void extLogger.log("Initializing QLTest interface."); const testExplorerExtension = extensions.getExtension( testExplorerExtensionId, ); @@ -856,7 +861,7 @@ async function activateWithInstalledDistribution( ctx.subscriptions.push(testUIService); } - void logger.log("Registering top-level command palette commands."); + void extLogger.log("Registering top-level command palette commands."); ctx.subscriptions.push( commandRunnerWithProgress( "codeQL.runQuery", @@ -938,7 +943,7 @@ async function activateWithInstalledDistribution( } } if (skippedDatabases.length > 0) { - void logger.log(`Errors:\n${errors.join("\n")}`); + void extLogger.log(`Errors:\n${errors.join("\n")}`); void showAndLogWarningMessage( `The following databases were skipped:\n${skippedDatabases.join( "\n", @@ -1415,13 +1420,13 @@ async function activateWithInstalledDistribution( ctx.subscriptions.push( commandRunner("codeQL.showLogs", async () => { - logger.show(); + extLogger.show(); }), ); ctx.subscriptions.push(new SummaryLanguageSupport()); - void logger.log("Starting language server."); + void extLogger.log("Starting language server."); await client.start(); ctx.subscriptions.push({ dispose: () => { @@ -1429,7 +1434,7 @@ async function activateWithInstalledDistribution( }, }); // Jump-to-definition and find-references - void logger.log("Registering jump-to-definition handlers."); + void extLogger.log("Registering jump-to-definition handlers."); // Store contextual queries in a temporary folder so that they are removed // when the application closes. There is no need for the user to interact with them. @@ -1545,14 +1550,14 @@ async function activateWithInstalledDistribution( await commands.executeCommand("codeQLDatabases.removeOrphanedDatabases"); - void logger.log("Reading query history"); + void extLogger.log("Reading query history"); await qhm.readQueryHistory(); const app = new ExtensionApp(ctx); const dbModule = await initializeDbModule(app); ctx.subscriptions.push(dbModule); - void logger.log("Successfully finished extension initialization."); + void extLogger.log("Successfully finished extension initialization."); return { ctx, @@ -1615,7 +1620,7 @@ function getContextStoragePath(ctx: ExtensionContext) { } async function initializeLogging(ctx: ExtensionContext): Promise { - ctx.subscriptions.push(logger); + ctx.subscriptions.push(extLogger); ctx.subscriptions.push(queryServerLogger); ctx.subscriptions.push(ideServerLogger); } diff --git a/extensions/ql-vscode/src/helpers.ts b/extensions/ql-vscode/src/helpers.ts index 28a82d481..7867f1c03 100644 --- a/extensions/ql-vscode/src/helpers.ts +++ b/extensions/ql-vscode/src/helpers.ts @@ -12,7 +12,7 @@ import { } from "vscode"; import { CodeQLCliServer, QlpacksInfo } from "./cli"; import { UserCancellationException } from "./commandRunner"; -import { logger } from "./common"; +import { extLogger } from "./common"; import { QueryMetadata } from "./pure/interface-types"; // Shared temporary folder for the extension. @@ -29,7 +29,7 @@ export const tmpDirDisposal = { try { tmpDir.removeCallback(); } catch (e) { - void logger.log( + void extLogger.log( `Failed to remove temporary directory ${tmpDir.name}: ${e}`, ); } @@ -51,7 +51,7 @@ export const tmpDirDisposal = { export async function showAndLogErrorMessage( message: string, { - outputLogger = logger, + outputLogger = extLogger, items = [] as string[], fullMessage = undefined as string | undefined, } = {}, @@ -80,7 +80,7 @@ function dropLinesExceptInitial(message: string, n = 2) { */ export async function showAndLogWarningMessage( message: string, - { outputLogger = logger, items = [] as string[] } = {}, + { outputLogger = extLogger, items = [] as string[] } = {}, ): Promise { return internalShowAndLog( message, @@ -100,7 +100,7 @@ export async function showAndLogWarningMessage( */ export async function showAndLogInformationMessage( message: string, - { outputLogger = logger, items = [] as string[], fullMessage = "" } = {}, + { outputLogger = extLogger, items = [] as string[], fullMessage = "" } = {}, ): Promise { return internalShowAndLog( message, @@ -119,7 +119,7 @@ type ShowMessageFn = ( async function internalShowAndLog( message: string, items: string[], - outputLogger = logger, + outputLogger = extLogger, fn: ShowMessageFn, fullMessage?: string, ): Promise { @@ -402,13 +402,13 @@ export async function getQlPackForDbscheme( const packs: QlPackWithPath[] = Object.entries(qlpacks).map( ([packName, dirs]) => { if (dirs.length < 1) { - void logger.log( + void extLogger.log( `In getQlPackFor ${dbschemePath}, qlpack ${packName} has no directories`, ); return { packName, packDir: undefined }; } if (dirs.length > 1) { - void logger.log( + void extLogger.log( `In getQlPackFor ${dbschemePath}, qlpack ${packName} has more than one directory; arbitrarily choosing the first`, ); } @@ -622,10 +622,10 @@ export async function findLanguage( uri, ); const language = Object.keys(queryInfo.byLanguage)[0]; - void logger.log(`Detected query language: ${language}`); + void extLogger.log(`Detected query language: ${language}`); return language; } catch (e) { - void logger.log( + void extLogger.log( "Could not autodetect query language. Select language manually.", ); } @@ -673,7 +673,7 @@ export async function tryGetQueryMetadata( return await cliServer.resolveMetadata(queryPath); } catch (e) { // Ignore errors and provide no metadata. - void logger.log(`Couldn't resolve metadata for ${queryPath}: ${e}`); + void extLogger.log(`Couldn't resolve metadata for ${queryPath}: ${e}`); return; } } diff --git a/extensions/ql-vscode/src/legacy-query-server/run-queries.ts b/extensions/ql-vscode/src/legacy-query-server/run-queries.ts index 96edbf308..32d7a151a 100644 --- a/extensions/ql-vscode/src/legacy-query-server/run-queries.ts +++ b/extensions/ql-vscode/src/legacy-query-server/run-queries.ts @@ -16,7 +16,7 @@ import { } from "../helpers"; import { ProgressCallback } from "../commandRunner"; import { QueryMetadata } from "../pure/interface-types"; -import { logger } from "../common"; +import { extLogger } from "../common"; import * as messages from "../pure/legacy-messages"; import { InitialQueryInfo, LocalQueryInfo } from "../query-results"; import * as qsClient from "./queryserver-client"; @@ -382,7 +382,7 @@ export async function compileAndRunQueryAgainstDatabase( const querySchemaName = path.basename(packConfig.dbscheme); const dbSchemaName = path.basename(dbItem.contents.dbSchemeUri.fsPath); if (querySchemaName != dbSchemaName) { - void logger.log( + void extLogger.log( `Query schema was ${querySchemaName}, but database schema was ${dbSchemaName}.`, ); throw new Error( @@ -411,7 +411,7 @@ export async function compileAndRunQueryAgainstDatabase( let availableMlModels: cli.MlModelInfo[] = []; if (!(await cliServer.cliConstraints.supportsResolveMlModels())) { - void logger.log( + void extLogger.log( "Resolving ML models is unsupported by this version of the CLI. Running the query without any ML models.", ); } else { @@ -423,13 +423,13 @@ export async function compileAndRunQueryAgainstDatabase( ) ).models; if (availableMlModels.length) { - void logger.log( + void extLogger.log( `Found available ML models at the following paths: ${availableMlModels .map((x) => `'${x.path}'`) .join(", ")}.`, ); } else { - void logger.log("Did not find any available ML models."); + void extLogger.log("Did not find any available ML models."); } } catch (e) { const message = @@ -502,7 +502,7 @@ export async function compileAndRunQueryAgainstDatabase( ); if (result.resultType !== messages.QueryResultType.SUCCESS) { const message = result.message || "Failed to run query"; - void logger.log(message); + void extLogger.log(message); void showAndLogErrorMessage(message); } const message = formatLegacyMessage(result); diff --git a/extensions/ql-vscode/src/legacy-query-server/upgrades.ts b/extensions/ql-vscode/src/legacy-query-server/upgrades.ts index f38aaeb77..360a8937a 100644 --- a/extensions/ql-vscode/src/legacy-query-server/upgrades.ts +++ b/extensions/ql-vscode/src/legacy-query-server/upgrades.ts @@ -5,7 +5,7 @@ import { tmpDir, } from "../helpers"; import { ProgressCallback, UserCancellationException } from "../commandRunner"; -import { logger } from "../common"; +import { extLogger } from "../common"; import * as messages from "../pure/legacy-messages"; import * as qsClient from "./queryserver-client"; import * as tmp from "tmp-promise"; @@ -107,7 +107,7 @@ async function checkAndConfirmDatabaseUpgrade( descriptionMessage += `Would perform upgrade: ${script.description}\n`; descriptionMessage += `\t-> Compatibility: ${script.compatibility}\n`; } - void logger.log(descriptionMessage); + void extLogger.log(descriptionMessage); // If the quiet flag is set, do the upgrade without a popup. if (quiet) { @@ -143,7 +143,7 @@ async function checkAndConfirmDatabaseUpgrade( ); if (chosenItem === showLogItem) { - logger.outputChannel.show(); + extLogger.outputChannel.show(); } if (chosenItem !== yesItem) { diff --git a/extensions/ql-vscode/src/log-insights/log-scanner-service.ts b/extensions/ql-vscode/src/log-insights/log-scanner-service.ts index d82492ccb..70a9c55d7 100644 --- a/extensions/ql-vscode/src/log-insights/log-scanner-service.ts +++ b/extensions/ql-vscode/src/log-insights/log-scanner-service.ts @@ -8,7 +8,7 @@ import { } from "./log-scanner"; import { PipelineInfo, SummarySymbols } from "./summary-parser"; import * as fs from "fs-extra"; -import { logger } from "../common"; +import { extLogger } from "../common"; /** * Compute the key used to find a predicate in the summary symbols. @@ -56,7 +56,7 @@ class ProblemReporter implements EvaluationLogProblemReporter { } public log(message: string): void { - void logger.log(message); + void extLogger.log(message); } } diff --git a/extensions/ql-vscode/src/log-insights/summary-language-support.ts b/extensions/ql-vscode/src/log-insights/summary-language-support.ts index 8d4d17f28..6d3011167 100644 --- a/extensions/ql-vscode/src/log-insights/summary-language-support.ts +++ b/extensions/ql-vscode/src/log-insights/summary-language-support.ts @@ -14,7 +14,7 @@ import { } from "vscode"; import { DisposableObject } from "../pure/disposable-object"; import { commandRunner } from "../commandRunner"; -import { logger } from "../common"; +import { extLogger } from "../common"; import { getErrorMessage } from "../pure/helpers-pure"; /** A `Position` within a specified file on disk. */ @@ -103,7 +103,7 @@ export class SummaryLanguageSupport extends DisposableObject { this.sourceMap = await new SourceMapConsumer(rawMap); } catch (e: unknown) { // Error reading sourcemap. Pretend there was no sourcemap. - void logger.log( + void extLogger.log( `Error reading sourcemap file '${mapPath}': ${getErrorMessage(e)}`, ); this.sourceMap = undefined; diff --git a/extensions/ql-vscode/src/packaging.ts b/extensions/ql-vscode/src/packaging.ts index 895d9984d..4bd6e4b11 100644 --- a/extensions/ql-vscode/src/packaging.ts +++ b/extensions/ql-vscode/src/packaging.ts @@ -6,7 +6,7 @@ import { } from "./helpers"; import { QuickPickItem, window } from "vscode"; import { ProgressCallback, UserCancellationException } from "./commandRunner"; -import { logger } from "./common"; +import { extLogger } from "./common"; const QUERY_PACKS = [ "codeql/cpp-queries", @@ -139,7 +139,7 @@ export async function handleInstallPackDependencies( } } if (failedPacks.length > 0) { - void logger.log(`Errors:\n${errors.join("\n")}`); + void extLogger.log(`Errors:\n${errors.join("\n")}`); throw new Error( `Unable to install pack dependencies for: ${failedPacks.join( ", ", diff --git a/extensions/ql-vscode/src/query-history-scrubber.ts b/extensions/ql-vscode/src/query-history-scrubber.ts index f89659082..21dfbc065 100644 --- a/extensions/ql-vscode/src/query-history-scrubber.ts +++ b/extensions/ql-vscode/src/query-history-scrubber.ts @@ -2,7 +2,7 @@ import * as fs from "fs-extra"; import * as os from "os"; import * as path from "path"; import { Disposable, ExtensionContext } from "vscode"; -import { logger } from "./common"; +import { extLogger } from "./common"; import { QueryHistoryManager } from "./query-history"; const LAST_SCRUB_TIME_KEY = "lastScrubTime"; @@ -74,9 +74,9 @@ async function scrubQueries( let scrubCount = 0; // total number of directories deleted try { counter?.increment(); - void logger.log("Scrubbing query directory. Removing old queries."); + void extLogger.log("Scrubbing query directory. Removing old queries."); if (!(await fs.pathExists(queryDirectory))) { - void logger.log( + void extLogger.log( `Cannot scrub. Query directory does not exist: ${queryDirectory}`, ); return; @@ -99,9 +99,9 @@ async function scrubQueries( throw new Error(os.EOL + errors.join(os.EOL)); } } catch (e) { - void logger.log(`Error while scrubbing queries: ${e}`); + void extLogger.log(`Error while scrubbing queries: ${e}`); } finally { - void logger.log(`Scrubbed ${scrubCount} old queries.`); + void extLogger.log(`Scrubbed ${scrubCount} old queries.`); } await qhm.removeDeletedQueries(); } @@ -119,30 +119,30 @@ async function scrubDirectory( try { let deleted = true; if (!(await fs.stat(dir)).isDirectory()) { - void logger.log(` ${dir} is not a directory. Deleting.`); + void extLogger.log(` ${dir} is not a directory. Deleting.`); await fs.remove(dir); } else if (!(await fs.pathExists(timestampFile))) { - void logger.log(` ${dir} has no timestamp file. Deleting.`); + void extLogger.log(` ${dir} has no timestamp file. Deleting.`); await fs.remove(dir); } else if (!(await fs.stat(timestampFile)).isFile()) { - void logger.log(` ${timestampFile} is not a file. Deleting.`); + void extLogger.log(` ${timestampFile} is not a file. Deleting.`); await fs.remove(dir); } else { const timestampText = await fs.readFile(timestampFile, "utf8"); const timestamp = parseInt(timestampText, 10); if (Number.isNaN(timestamp)) { - void logger.log( + void extLogger.log( ` ${dir} has invalid timestamp '${timestampText}'. Deleting.`, ); await fs.remove(dir); } else if (now - timestamp > maxQueryTime) { - void logger.log( + void extLogger.log( ` ${dir} is older than ${maxQueryTime / 1000} seconds. Deleting.`, ); await fs.remove(dir); } else { - void logger.log( + void extLogger.log( ` ${dir} is not older than ${maxQueryTime / 1000} seconds. Keeping.`, ); deleted = false; diff --git a/extensions/ql-vscode/src/query-history.ts b/extensions/ql-vscode/src/query-history.ts index 3a63cade5..5ddbc4e28 100644 --- a/extensions/ql-vscode/src/query-history.ts +++ b/extensions/ql-vscode/src/query-history.ts @@ -24,7 +24,7 @@ import { showAndLogWarningMessage, showBinaryChoiceDialog, } from "./helpers"; -import { logger } from "./common"; +import { extLogger } from "./common"; import { URLSearchParams } from "url"; import { DisposableObject } from "./pure/disposable-object"; import { commandRunner } from "./commandRunner"; @@ -460,7 +460,7 @@ export class QueryHistoryManager extends DisposableObject { }), ); - void logger.log("Registering query history panel commands."); + void extLogger.log("Registering query history panel commands."); this.push( commandRunner( "codeQLQueryHistory.openQuery", @@ -705,7 +705,7 @@ export class QueryHistoryManager extends DisposableObject { }); await this.refreshTreeView(); } else { - void logger.log( + void extLogger.log( "Variant analysis status update event received for unknown variant analysis", ); } @@ -775,7 +775,7 @@ export class QueryHistoryManager extends DisposableObject { } await this.refreshTreeView(); } else { - void logger.log( + void extLogger.log( "Variant analysis status update event received for unknown variant analysis", ); } @@ -787,7 +787,7 @@ export class QueryHistoryManager extends DisposableObject { } async readQueryHistory(): Promise { - void logger.log( + void extLogger.log( `Reading cached query history from '${this.queryMetadataStorageLocation}'.`, ); const history = await slurpQueryHistory(this.queryMetadataStorageLocation); @@ -929,9 +929,9 @@ export class QueryHistoryManager extends DisposableObject { // Remote queries can be removed locally, but not remotely. // The user must cancel the query on GitHub Actions explicitly. this.treeDataProvider.remove(item); - void logger.log(`Deleted ${this.labelProvider.getLabel(item)}.`); + void extLogger.log(`Deleted ${this.labelProvider.getLabel(item)}.`); if (item.status === QueryStatus.InProgress) { - void logger.log( + void extLogger.log( "The variant analysis is still running on GitHub Actions. To cancel there, you must go to the workflow run in your browser.", ); } @@ -945,9 +945,9 @@ export class QueryHistoryManager extends DisposableObject { // We can remove a Variant Analysis locally, but not remotely. // The user must cancel the query on GitHub Actions explicitly. this.treeDataProvider.remove(item); - void logger.log(`Deleted ${this.labelProvider.getLabel(item)}.`); + void extLogger.log(`Deleted ${this.labelProvider.getLabel(item)}.`); if (item.status === QueryStatus.InProgress) { - void logger.log( + void extLogger.log( "The variant analysis is still running on GitHub Actions. To cancel there, you must go to the workflow run in your browser.", ); } @@ -1604,8 +1604,8 @@ the file in the file explorer and dragging it into the workspace.`, } } else { void showAndLogErrorMessage(`Could not open file ${fileLocation}`); - void logger.log(getErrorMessage(e)); - void logger.log(getErrorStack(e)); + void extLogger.log(getErrorMessage(e)); + void extLogger.log(getErrorStack(e)); } } } diff --git a/extensions/ql-vscode/src/query-server/run-queries.ts b/extensions/ql-vscode/src/query-server/run-queries.ts index 99f1be795..2b54e688a 100644 --- a/extensions/ql-vscode/src/query-server/run-queries.ts +++ b/extensions/ql-vscode/src/query-server/run-queries.ts @@ -9,7 +9,7 @@ import { showAndLogWarningMessage, tryGetQueryMetadata, } from "../helpers"; -import { logger } from "../common"; +import { extLogger } from "../common"; import * as messages from "../pure/new-messages"; import * as legacyMessages from "../pure/legacy-messages"; import { InitialQueryInfo, LocalQueryInfo } from "../query-results"; @@ -110,7 +110,7 @@ export async function compileAndRunQueryAgainstDatabase( if (result.resultType !== messages.QueryResultType.SUCCESS) { const message = result.message || "Failed to run query"; - void logger.log(message); + void extLogger.log(message); void showAndLogErrorMessage(message); } let message; diff --git a/extensions/ql-vscode/src/remote-queries/export-results.ts b/extensions/ql-vscode/src/remote-queries/export-results.ts index bdb83dfbe..33c5de803 100644 --- a/extensions/ql-vscode/src/remote-queries/export-results.ts +++ b/extensions/ql-vscode/src/remote-queries/export-results.ts @@ -12,7 +12,7 @@ import { import { Credentials } from "../authentication"; import { UserCancellationException } from "../commandRunner"; import { showInformationMessageWithAction } from "../helpers"; -import { logger } from "../common"; +import { extLogger } from "../common"; import { QueryHistoryManager } from "../query-history"; import { createGist } from "./gh-api/gh-api-client"; import { RemoteQueriesManager } from "./remote-queries-manager"; @@ -76,7 +76,7 @@ export async function exportRemoteQueryResults( ): Promise { const queryHistoryItem = queryHistoryManager.getRemoteQueryById(queryId); if (!queryHistoryItem) { - void logger.log(`Could not find query with id ${queryId}`); + void extLogger.log(`Could not find query with id ${queryId}`); throw new Error( "There was an error when trying to retrieve variant analysis information", ); @@ -86,7 +86,7 @@ export async function exportRemoteQueryResults( throw new Error("Variant analysis results are not yet available."); } - void logger.log( + void extLogger.log( `Exporting variant analysis results for query: ${queryHistoryItem.queryId}`, ); const query = queryHistoryItem.remoteQuery; @@ -148,7 +148,7 @@ export async function exportVariantAnalysisResults( variantAnalysisId, ); if (!variantAnalysis) { - void logger.log( + void extLogger.log( `Could not find variant analysis with id ${variantAnalysisId}`, ); throw new Error( @@ -156,7 +156,7 @@ export async function exportVariantAnalysisResults( ); } - void logger.log( + void extLogger.log( `Exporting variant analysis results for variant analysis with id ${variantAnalysis.id}`, ); diff --git a/extensions/ql-vscode/src/remote-queries/gh-api/gh-actions-api-client.ts b/extensions/ql-vscode/src/remote-queries/gh-api/gh-actions-api-client.ts index 80b9ac320..7a3485b28 100644 --- a/extensions/ql-vscode/src/remote-queries/gh-api/gh-actions-api-client.ts +++ b/extensions/ql-vscode/src/remote-queries/gh-api/gh-actions-api-client.ts @@ -6,7 +6,7 @@ import { tmpDir, } from "../../helpers"; import { Credentials } from "../../authentication"; -import { logger } from "../../common"; +import { extLogger } from "../../common"; import { RemoteQueryWorkflowResult } from "../remote-query-workflow-result"; import { DownloadLink, createDownloadPath } from "../download-link"; import { RemoteQuery } from "../remote-query"; @@ -384,10 +384,10 @@ async function unzipBuffer( filePath: string, destinationPath: string, ): Promise { - void logger.log(`Saving file to ${filePath}`); + void extLogger.log(`Saving file to ${filePath}`); await fs.writeFile(filePath, Buffer.from(data)); - void logger.log(`Unzipping file to ${destinationPath}`); + void extLogger.log(`Unzipping file to ${destinationPath}`); await unzipFile(filePath, destinationPath); } diff --git a/extensions/ql-vscode/src/remote-queries/repository-selection.ts b/extensions/ql-vscode/src/remote-queries/repository-selection.ts index 4551ed55c..ccfe92109 100644 --- a/extensions/ql-vscode/src/remote-queries/repository-selection.ts +++ b/extensions/ql-vscode/src/remote-queries/repository-selection.ts @@ -1,6 +1,6 @@ import * as fs from "fs-extra"; import { QuickPickItem, window } from "vscode"; -import { logger } from "../common"; +import { extLogger } from "../common"; import { getRemoteRepositoryLists, getRemoteRepositoryListsPath, @@ -50,12 +50,12 @@ export async function getRepositorySelection(): Promise { ); if (quickpick?.repositories?.length) { - void logger.log( + void extLogger.log( `Selected repositories: ${quickpick.repositories.join(", ")}`, ); return { repositories: quickpick.repositories }; } else if (quickpick?.repositoryList) { - void logger.log(`Selected repository list: ${quickpick.repositoryList}`); + void extLogger.log(`Selected repository list: ${quickpick.repositoryList}`); return { repositoryLists: [quickpick.repositoryList] }; } else if (quickpick?.useCustomRepo) { const customRepo = await getCustomRepo(); @@ -68,7 +68,7 @@ export async function getRepositorySelection(): Promise { "Invalid repository format. Please enter a valid repository in the format / (e.g. github/codeql)", ); } - void logger.log(`Entered repository: ${customRepo}`); + void extLogger.log(`Entered repository: ${customRepo}`); return { repositories: [customRepo] }; } else if (quickpick?.useAllReposOfOwner) { const owner = await getOwner(); @@ -79,7 +79,7 @@ export async function getRepositorySelection(): Promise { if (!owner || !OWNER_REGEX.test(owner)) { throw new Error(`Invalid user or organization: ${owner}`); } - void logger.log(`Entered owner: ${owner}`); + void extLogger.log(`Entered owner: ${owner}`); return { owners: [owner] }; } else { // We don't need to display a warning pop-up in this case, since the user just escaped out of the operation. diff --git a/extensions/ql-vscode/src/remote-queries/run-remote-query.ts b/extensions/ql-vscode/src/remote-queries/run-remote-query.ts index 6b85fac07..28ec9f023 100644 --- a/extensions/ql-vscode/src/remote-queries/run-remote-query.ts +++ b/extensions/ql-vscode/src/remote-queries/run-remote-query.ts @@ -12,7 +12,7 @@ import { } from "../helpers"; import { Credentials } from "../authentication"; import * as cli from "../cli"; -import { logger } from "../common"; +import { extLogger } from "../common"; import { getActionBranch, getRemoteControllerRepo, @@ -97,7 +97,7 @@ async function generateQueryPack( }), }); - void logger.log(`Copied ${copiedCount} files to ${queryPackDir}`); + void extLogger.log(`Copied ${copiedCount} files to ${queryPackDir}`); await fixPackFile(queryPackDir, packRelativePath); @@ -108,9 +108,9 @@ async function generateQueryPack( // copy only the query file to the query pack directory // and generate a synthetic query pack - void logger.log(`Copying ${queryFile} to ${queryPackDir}`); + void extLogger.log(`Copying ${queryFile} to ${queryPackDir}`); await fs.copy(queryFile, targetQueryFileName); - void logger.log("Generating synthetic query pack"); + void extLogger.log("Generating synthetic query pack"); const syntheticQueryPack = { name: QUERY_PACK_NAME, version: "0.0.0", @@ -144,7 +144,7 @@ async function generateQueryPack( } const bundlePath = await getPackedBundlePath(queryPackDir); - void logger.log( + void extLogger.log( `Compiling and bundling query pack from ${queryPackDir} to ${bundlePath}. (This may take a while.)`, ); await cliServer.packInstall(queryPackDir); @@ -359,7 +359,7 @@ export async function getControllerRepo( let controllerRepoNwo: string | undefined; controllerRepoNwo = getRemoteControllerRepo(); if (!controllerRepoNwo || !REPO_REGEX.test(controllerRepoNwo)) { - void logger.log( + void extLogger.log( controllerRepoNwo ? "Invalid controller repository name." : "No controller repository defined.", @@ -380,13 +380,13 @@ export async function getControllerRepo( "Invalid repository format. Must be a valid GitHub repository in the format /.", ); } - void logger.log( + void extLogger.log( `Setting the controller repository as: ${controllerRepoNwo}`, ); await setRemoteControllerRepo(controllerRepoNwo); } - void logger.log(`Using controller repository: ${controllerRepoNwo}`); + void extLogger.log(`Using controller repository: ${controllerRepoNwo}`); const [owner, repo] = controllerRepoNwo.split("/"); try { @@ -395,7 +395,7 @@ export async function getControllerRepo( owner, repo, ); - void logger.log(`Controller repository ID: ${controllerRepo.id}`); + void extLogger.log(`Controller repository ID: ${controllerRepo.id}`); return { id: controllerRepo.id, fullName: controllerRepo.full_name, diff --git a/extensions/ql-vscode/src/remote-queries/variant-analysis-view.ts b/extensions/ql-vscode/src/remote-queries/variant-analysis-view.ts index 1cad53299..da53201cc 100644 --- a/extensions/ql-vscode/src/remote-queries/variant-analysis-view.ts +++ b/extensions/ql-vscode/src/remote-queries/variant-analysis-view.ts @@ -8,7 +8,7 @@ import { } from "vscode"; import { URLSearchParams } from "url"; import { AbstractWebview, WebviewPanelConfig } from "../abstract-webview"; -import { logger } from "../common"; +import { extLogger } from "../common"; import { FromVariantAnalysisMessage, ToVariantAnalysisMessage, @@ -159,7 +159,7 @@ export class VariantAnalysisView protected async onWebViewLoaded() { super.onWebViewLoaded(); - void logger.log("Variant analysis view loaded"); + void extLogger.log("Variant analysis view loaded"); const variantAnalysis = await this.manager.getVariantAnalysis( this.variantAnalysisId, diff --git a/extensions/ql-vscode/src/run-queries-shared.ts b/extensions/ql-vscode/src/run-queries-shared.ts index c81449565..bed2ac301 100644 --- a/extensions/ql-vscode/src/run-queries-shared.ts +++ b/extensions/ql-vscode/src/run-queries-shared.ts @@ -25,7 +25,7 @@ import { CodeQLCliServer } from "./cli"; import { SELECT_QUERY_NAME } from "./contextual/locationFinder"; import { DatabaseManager } from "./databases"; import { DecodedBqrsChunk } from "./pure/bqrs-cli-types"; -import { logger } from "./common"; +import { extLogger } from "./common"; import { Logger } from "./common"; import { generateSummarySymbolsFile } from "./log-insights/summary-parser"; import { asError } from "./pure/helpers-pure"; @@ -143,7 +143,7 @@ export class QueryEvaluationInfo { */ canHaveInterpretedResults(): boolean { if (!this.databaseHasMetadataFile) { - void logger.log( + void extLogger.log( "Cannot produce interpreted results since the database does not have a .dbinfo or codeql-database.yml file.", ); return false; @@ -152,7 +152,7 @@ export class QueryEvaluationInfo { const kind = this.metadata?.kind; const hasKind = !!kind; if (!hasKind) { - void logger.log( + void extLogger.log( "Cannot produce interpreted results since the query does not have @kind metadata.", ); return false; diff --git a/extensions/ql-vscode/src/telemetry.ts b/extensions/ql-vscode/src/telemetry.ts index 54bdab469..0b86eb15a 100644 --- a/extensions/ql-vscode/src/telemetry.ts +++ b/extensions/ql-vscode/src/telemetry.ts @@ -14,7 +14,7 @@ import { isIntegrationTestMode, } from "./config"; import * as appInsights from "applicationinsights"; -import { logger } from "./common"; +import { extLogger } from "./common"; import { UserCancellationException } from "./commandRunner"; import { showBinaryChoiceWithUrlDialog } from "./helpers"; @@ -135,7 +135,7 @@ export class TelemetryListener extends ConfigListener { } if (LOG_TELEMETRY.getValue()) { - void logger.log(`Telemetry: ${JSON.stringify(envelope)}`); + void extLogger.log(`Telemetry: ${JSON.stringify(envelope)}`); } return true; }); diff --git a/extensions/ql-vscode/src/test-ui.ts b/extensions/ql-vscode/src/test-ui.ts index c0bcc99c4..3a1b933b7 100644 --- a/extensions/ql-vscode/src/test-ui.ts +++ b/extensions/ql-vscode/src/test-ui.ts @@ -16,7 +16,7 @@ import { TestTreeNode } from "./test-tree-node"; import { DisposableObject } from "./pure/disposable-object"; import { UIService } from "./vscode-utils/ui-service"; import { QLTestAdapter, getExpectedFile, getActualFile } from "./test-adapter"; -import { logger } from "./common"; +import { extLogger } from "./common"; type VSCodeTestEvent = | TestRunStartedEvent @@ -48,7 +48,7 @@ export class TestUIService extends UIService implements TestController { constructor(private readonly testHub: TestHub) { super(); - void logger.log("Registering CodeQL test panel commands."); + void extLogger.log("Registering CodeQL test panel commands."); this.registerCommand( "codeQLTests.showOutputDifferences", this.showOutputDifferences, diff --git a/extensions/ql-vscode/src/vscode-tests/cli-integration/legacy-query.test.ts b/extensions/ql-vscode/src/vscode-tests/cli-integration/legacy-query.test.ts index 35e257d38..8f0b74c41 100644 --- a/extensions/ql-vscode/src/vscode-tests/cli-integration/legacy-query.test.ts +++ b/extensions/ql-vscode/src/vscode-tests/cli-integration/legacy-query.test.ts @@ -11,7 +11,7 @@ import { extensions } from "vscode"; import { CodeQLExtensionInterface } from "../../extension"; import { describeWithCodeQL } from "../cli"; import { QueryServerClient } from "../../legacy-query-server/queryserver-client"; -import { logger, ProgressReporter } from "../../common"; +import { extLogger, ProgressReporter } from "../../common"; const baseDir = path.join(__dirname, "../../../test/data"); @@ -134,7 +134,7 @@ describeWithCodeQL()("using the legacy query server", () => { cliServer, { contextStoragePath: tmpDir.name, - logger, + logger: extLogger, }, (task) => task(nullProgressReporter, new CancellationTokenSource().token), diff --git a/extensions/ql-vscode/src/vscode-tests/cli-integration/new-query.test.ts b/extensions/ql-vscode/src/vscode-tests/cli-integration/new-query.test.ts index 456bce7b6..b1682d80e 100644 --- a/extensions/ql-vscode/src/vscode-tests/cli-integration/new-query.test.ts +++ b/extensions/ql-vscode/src/vscode-tests/cli-integration/new-query.test.ts @@ -9,7 +9,7 @@ import { extensions, Uri } from "vscode"; import { CodeQLExtensionInterface } from "../../extension"; import { describeWithCodeQL } from "../cli"; import { QueryServerClient } from "../../query-server/queryserver-client"; -import { logger, ProgressReporter } from "../../common"; +import { extLogger, ProgressReporter } from "../../common"; import { QueryResultType } from "../../pure/new-messages"; import { cleanDatabases, dbLoc, storagePath } from "./global.helper"; import { importArchiveDatabase } from "../../databaseFetcher"; @@ -135,7 +135,7 @@ describeWithCodeQL()("using the new query server", () => { cliServer, { contextStoragePath: tmpDir.name, - logger, + logger: extLogger, }, (task) => task(nullProgressReporter, new CancellationTokenSource().token), diff --git a/extensions/ql-vscode/src/vscode-tests/cli-integration/remote-queries/variant-analysis-manager.test.ts b/extensions/ql-vscode/src/vscode-tests/cli-integration/remote-queries/variant-analysis-manager.test.ts index 37d979ddb..71c52fa8e 100644 --- a/extensions/ql-vscode/src/vscode-tests/cli-integration/remote-queries/variant-analysis-manager.test.ts +++ b/extensions/ql-vscode/src/vscode-tests/cli-integration/remote-queries/variant-analysis-manager.test.ts @@ -8,7 +8,7 @@ import { window, } from "vscode"; import { CodeQLExtensionInterface } from "../../../extension"; -import { logger } from "../../../common"; +import { extLogger } from "../../../common"; import * as config from "../../../config"; import { setRemoteControllerRepo, @@ -75,7 +75,7 @@ describe("Variant Analysis Manager", () => { outputJsonStub = jest.spyOn(fs, "outputJson").mockReturnValue(undefined); writeFileStub = jest.spyOn(fs, "writeFile").mockReturnValue(undefined); - jest.spyOn(logger, "log").mockResolvedValue(undefined); + jest.spyOn(extLogger, "log").mockResolvedValue(undefined); jest .spyOn(config, "isVariantAnalysisLiveResultsEnabled") .mockReturnValue(false); @@ -97,7 +97,7 @@ describe("Variant Analysis Manager", () => { cli = extension.cliServer; variantAnalysisResultsManager = new VariantAnalysisResultsManager( cli, - logger, + extLogger, ); variantAnalysisManager = new VariantAnalysisManager( extension.ctx, diff --git a/extensions/ql-vscode/src/vscode-tests/cli-integration/remote-queries/variant-analysis-results-manager.test.ts b/extensions/ql-vscode/src/vscode-tests/cli-integration/remote-queries/variant-analysis-results-manager.test.ts index f77229f65..c122dd0d5 100644 --- a/extensions/ql-vscode/src/vscode-tests/cli-integration/remote-queries/variant-analysis-results-manager.test.ts +++ b/extensions/ql-vscode/src/vscode-tests/cli-integration/remote-queries/variant-analysis-results-manager.test.ts @@ -1,6 +1,6 @@ import { extensions } from "vscode"; import { CodeQLExtensionInterface } from "../../../extension"; -import { logger } from "../../../common"; +import { extLogger } from "../../../common"; import { Credentials } from "../../../authentication"; import * as fs from "fs-extra"; import * as path from "path"; @@ -21,7 +21,7 @@ describe(VariantAnalysisResultsManager.name, () => { let variantAnalysisResultsManager: VariantAnalysisResultsManager; beforeEach(async () => { - jest.spyOn(logger, "log").mockResolvedValue(undefined); + jest.spyOn(extLogger, "log").mockResolvedValue(undefined); jest.spyOn(fs, "mkdirSync").mockReturnValue(undefined); jest.spyOn(fs, "writeFile").mockReturnValue(undefined); @@ -35,7 +35,7 @@ describe(VariantAnalysisResultsManager.name, () => { cli = extension.cliServer; variantAnalysisResultsManager = new VariantAnalysisResultsManager( cli, - logger, + extLogger, ); }); diff --git a/extensions/ql-vscode/src/vscode-tests/no-workspace/distribution.test.ts b/extensions/ql-vscode/src/vscode-tests/no-workspace/distribution.test.ts index 25cc3a42c..2df5cfeae 100644 --- a/extensions/ql-vscode/src/vscode-tests/no-workspace/distribution.test.ts +++ b/extensions/ql-vscode/src/vscode-tests/no-workspace/distribution.test.ts @@ -3,7 +3,7 @@ import * as fetch from "node-fetch"; import * as semver from "semver"; import * as helpers from "../../helpers"; -import { logger } from "../../common"; +import { extLogger } from "../../common"; import * as fs from "fs-extra"; import * as os from "os"; import { @@ -199,7 +199,7 @@ describe("Launcher path", () => { let warnSpy: jest.SpiedFunction; let errorSpy: jest.SpiedFunction; - let logSpy: jest.SpiedFunction; + let logSpy: jest.SpiedFunction; let pathExistsSpy: jest.SpiedFunction; let launcherThatExists = ""; @@ -211,7 +211,7 @@ describe("Launcher path", () => { errorSpy = jest .spyOn(helpers, "showAndLogErrorMessage") .mockResolvedValue(undefined); - logSpy = jest.spyOn(logger, "log").mockResolvedValue(undefined); + logSpy = jest.spyOn(extLogger, "log").mockResolvedValue(undefined); pathExistsSpy = jest .spyOn(fs, "pathExists") .mockImplementation(async (path: string) => { diff --git a/extensions/ql-vscode/src/vscode-tests/no-workspace/query-history.test.ts b/extensions/ql-vscode/src/vscode-tests/no-workspace/query-history.test.ts index 48f010b14..7b31e0096 100644 --- a/extensions/ql-vscode/src/vscode-tests/no-workspace/query-history.test.ts +++ b/extensions/ql-vscode/src/vscode-tests/no-workspace/query-history.test.ts @@ -2,7 +2,7 @@ import * as fs from "fs-extra"; import * as path from "path"; import * as vscode from "vscode"; -import { logger } from "../../common"; +import { extLogger } from "../../common"; import { registerQueryHistoryScrubber } from "../../query-history-scrubber"; import { HistoryTreeDataProvider, @@ -88,7 +88,7 @@ describe("query-history", () => { .spyOn(vscode.commands, "executeCommand") .mockResolvedValue(undefined); - jest.spyOn(logger, "log").mockResolvedValue(undefined); + jest.spyOn(extLogger, "log").mockResolvedValue(undefined); tryOpenExternalFile = (QueryHistoryManager.prototype as any) .tryOpenExternalFile;