Skip to content

Commit df071f8

Browse files
committed
General refactoring and adding comments
There is no new behaviour added in this commit. Just some cleanup: - Move some shared constants to the `helpers` module - Add comments to some of the query related modules - Some general formatting and tidying
1 parent a7e014a commit df071f8

18 files changed

Lines changed: 155 additions & 100 deletions

extensions/ql-vscode/CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
- Fix a bug with importing large databases. Databases over 4GB can now be imported directly from LGTM or from a zip file. This functionality is only available when using CodeQL CLI version 2.6.0 or later. [#971](https://github.com/github/vscode-codeql/pull/971)
3636
- Replace certain control codes (`U+0000` - `U+001F`) with their corresponding control labels (`U+2400` - `U+241F`) in the results view. [#963](https://github.com/github/vscode-codeql/pull/963)
3737
- Allow case-insensitive project slugs for GitHub repositories when adding a CodeQL database from LGTM. [#978](https://github.com/github/vscode-codeql/pull/961)
38-
- Add a _CodeQL: Preview Query Help_ command to generate Markdown previews of `.qhelp` query help files. This command should only be run in trusted workspaces. See https://codeql.github.com/docs/codeql-cli/testing-query-help-files for more information about query help. [#988](https://github.com/github/vscode-codeql/pull/988)
38+
- Add a _CodeQL: Preview Query Help_ command to generate Markdown previews of `.qhelp` query help files. This command should only be run in trusted workspaces. See [the CodeQL CLI docs](https://codeql.github.com/docs/codeql-cli/testing-query-help-files) for more information about query help. [#988](https://github.com/github/vscode-codeql/pull/988)
3939
- Make "Open Referenced File" command accessible from the active editor menu. [#989](https://github.com/github/vscode-codeql/pull/989)
4040
- Fix a bug where result set names in the result set drop-down were disappearing when viewing a sorted table. [#1007](https://github.com/github/vscode-codeql/pull/1007)
4141
- Allow query result locations with 0 as the end column value. These are treated as the first column in the line. [#1002](https://github.com/github/vscode-codeql/pull/1002)

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
} from 'vscode';
99
import * as path from 'path';
1010

11-
import { tmpDir } from '../run-queries';
11+
import { tmpDir } from '../helpers';
1212
import {
1313
FromCompareViewMessage,
1414
ToCompareViewMessage,

extensions/ql-vscode/src/config.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@ import { DisposableObject } from './pure/disposable-object';
22
import { workspace, Event, EventEmitter, ConfigurationChangeEvent, ConfigurationTarget } from 'vscode';
33
import { DistributionManager } from './distribution';
44
import { logger } from './logging';
5-
6-
const ONE_DAY_IN_MS = 24 * 60 * 60 * 1000;
5+
import { ONE_DAY_IN_MS } from './pure/helpers-pure';
76

87
/** Helper class to look up a labelled (and possibly nested) setting. */
98
export class Setting {
@@ -258,7 +257,7 @@ export class QueryHistoryConfigListener extends ConfigListener implements QueryH
258257
}
259258

260259
/**
261-
* The configuration value is in days, but return the value in milliseconds.
260+
* The configuration value is in days, but return the value in milliseconds to make it easier to use.
262261
*/
263262
public get ttlInMillis(): number {
264263
return (QUERY_HISTORY_TTL.getValue<number>() || 30) * ONE_DAY_IN_MS;

extensions/ql-vscode/src/databaseFetcher.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import {
2020
ProgressCallback,
2121
} from './commandRunner';
2222
import { logger } from './logging';
23-
import { tmpDir } from './run-queries';
23+
import { tmpDir } from './helpers';
2424

2525
/**
2626
* Prompts a user to fetch a database from a remote location. Database is assumed to be an archive file.
@@ -434,7 +434,7 @@ function convertRawLgtmSlug(maybeSlug: string): string | undefined {
434434
}
435435
return;
436436
}
437-
437+
438438
function extractProjectSlug(lgtmUrl: string): string | undefined {
439439
// Only matches the '/g/' provider (github)
440440
const re = new RegExp('https://lgtm.com/projects/g/(.*[^/])');

extensions/ql-vscode/src/extension.ts

Lines changed: 31 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,15 @@ import {
5454
GithubApiError,
5555
GithubRateLimitedError
5656
} from './distribution';
57-
import * as helpers from './helpers';
57+
import {
58+
findLanguage,
59+
tmpDirDisposal,
60+
showBinaryChoiceDialog,
61+
showAndLogErrorMessage,
62+
showAndLogWarningMessage,
63+
showAndLogInformationMessage,
64+
showInformationMessageWithAction
65+
} from './helpers';
5866
import { assertNever } from './pure/helpers-pure';
5967
import { spawnIdeServer } from './ide-server';
6068
import { InterfaceManager } from './interface';
@@ -64,7 +72,7 @@ import { QueryHistoryManager } from './query-history';
6472
import { FullCompletedQueryInfo, FullQueryInfo } from './query-results';
6573
import * as qsClient from './queryserver-client';
6674
import { displayQuickQuery } from './quick-query';
67-
import { compileAndRunQueryAgainstDatabase, createInitialQueryInfo, tmpDirDisposal } from './run-queries';
75+
import { compileAndRunQueryAgainstDatabase, createInitialQueryInfo } from './run-queries';
6876
import { QLTestAdapterFactory } from './test-adapter';
6977
import { TestUIService } from './test-ui';
7078
import { CompareInterfaceManager } from './compare/compare-interface';
@@ -189,7 +197,7 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
189197
const shouldUpdateOnNextActivationKey = 'shouldUpdateOnNextActivation';
190198

191199
registerErrorStubs([checkForUpdatesCommand], command => (async () => {
192-
void helpers.showAndLogErrorMessage(`Can't execute ${command}: waiting to finish loading CodeQL CLI.`);
200+
void showAndLogErrorMessage(`Can't execute ${command}: waiting to finish loading CodeQL CLI.`);
193201
}));
194202

195203
interface DistributionUpdateConfig {
@@ -201,7 +209,7 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
201209
async function installOrUpdateDistributionWithProgressTitle(progressTitle: string, config: DistributionUpdateConfig): Promise<void> {
202210
const minSecondsSinceLastUpdateCheck = config.isUserInitiated ? 0 : 86400;
203211
const noUpdatesLoggingFunc = config.shouldDisplayMessageWhenNoUpdates ?
204-
helpers.showAndLogInformationMessage : async (message: string) => void logger.log(message);
212+
showAndLogInformationMessage : async (message: string) => void logger.log(message);
205213
const result = await distributionManager.checkForUpdatesToExtensionManagedDistribution(minSecondsSinceLastUpdateCheck);
206214

207215
// We do want to auto update if there is no distribution at all
@@ -223,7 +231,7 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
223231
const updateAvailableMessage = `Version "${result.updatedRelease.name}" of the CodeQL CLI is now available. ` +
224232
'Do you wish to upgrade?';
225233
await ctx.globalState.update(shouldUpdateOnNextActivationKey, true);
226-
if (await helpers.showInformationMessageWithAction(updateAvailableMessage, 'Restart and Upgrade')) {
234+
if (await showInformationMessageWithAction(updateAvailableMessage, 'Restart and Upgrade')) {
227235
await commands.executeCommand('workbench.action.reloadWindow');
228236
}
229237
} else {
@@ -236,7 +244,7 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
236244
distributionManager.installExtensionManagedDistributionRelease(result.updatedRelease, progress));
237245

238246
await ctx.globalState.update(shouldUpdateOnNextActivationKey, false);
239-
void helpers.showAndLogInformationMessage(`CodeQL CLI updated to version "${result.updatedRelease.name}".`);
247+
void showAndLogInformationMessage(`CodeQL CLI updated to version "${result.updatedRelease.name}".`);
240248
}
241249
break;
242250
default:
@@ -263,7 +271,7 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
263271
// Don't rethrow the exception, because if the config is changed, we want to be able to retry installing
264272
// or updating the distribution.
265273
const alertFunction = (codeQlInstalled && !config.isUserInitiated) ?
266-
helpers.showAndLogWarningMessage : helpers.showAndLogErrorMessage;
274+
showAndLogWarningMessage : showAndLogErrorMessage;
267275
const taskDescription = (willUpdateCodeQl ? 'update' :
268276
codeQlInstalled ? 'check for updates to' : 'install') + ' CodeQL CLI';
269277

@@ -298,20 +306,20 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
298306
}
299307
})();
300308

301-
void helpers.showAndLogWarningMessage(
309+
void showAndLogWarningMessage(
302310
`The current version of the CodeQL CLI (${result.version.raw}) ` +
303311
`is incompatible with this extension. ${fixGuidanceMessage}`
304312
);
305313
break;
306314
}
307315
case FindDistributionResultKind.UnknownCompatibilityDistribution:
308-
void helpers.showAndLogWarningMessage(
316+
void showAndLogWarningMessage(
309317
'Compatibility with the configured CodeQL CLI could not be determined. ' +
310318
'You may experience problems using the extension.'
311319
);
312320
break;
313321
case FindDistributionResultKind.NoDistribution:
314-
void helpers.showAndLogErrorMessage('The CodeQL CLI could not be found.');
322+
void showAndLogErrorMessage('The CodeQL CLI could not be found.');
315323
break;
316324
default:
317325
assertNever(result);
@@ -338,7 +346,7 @@ export async function activate(ctx: ExtensionContext): Promise<CodeQLExtensionIn
338346
} else if (distributionResult.kind === FindDistributionResultKind.NoDistribution) {
339347
registerErrorStubs([checkForUpdatesCommand], command => async () => {
340348
const installActionName = 'Install CodeQL CLI';
341-
const chosenAction = await void helpers.showAndLogErrorMessage(`Can't execute ${command}: missing CodeQL CLI.`, {
349+
const chosenAction = await void showAndLogErrorMessage(`Can't execute ${command}: missing CodeQL CLI.`, {
342350
items: [installActionName]
343351
});
344352
if (chosenAction === installActionName) {
@@ -477,7 +485,7 @@ async function activateWithInstalledDistribution(
477485
try {
478486
await cmpm.showResults(from, to);
479487
} catch (e) {
480-
void helpers.showAndLogErrorMessage(e.message);
488+
void showAndLogErrorMessage(e.message);
481489
}
482490
}
483491

@@ -559,7 +567,7 @@ async function activateWithInstalledDistribution(
559567
const errorMessage = err.message.includes('Generating qhelp in markdown') ? (
560568
`Could not generate markdown from ${pathToQhelp}: Bad formatting in .qhelp file.`
561569
) : `Could not open a preview of the generated file (${absolutePathToMd}).`;
562-
void helpers.showAndLogErrorMessage(errorMessage, { fullMessage: `${errorMessage}\n${err}` });
570+
void showAndLogErrorMessage(errorMessage, { fullMessage: `${errorMessage}\n${err}` });
563571
}
564572
}
565573

@@ -576,7 +584,7 @@ async function activateWithInstalledDistribution(
576584
const uri = Uri.file(resolved.resolvedPath);
577585
await window.showTextDocument(uri, { preview: false });
578586
} else {
579-
void helpers.showAndLogErrorMessage(
587+
void showAndLogErrorMessage(
580588
'Jumping from a .qlref file to the .ql file it references is not '
581589
+ 'supported with the CLI version you are running.\n'
582590
+ `Please upgrade your CLI to version ${CliVersionConstraint.CLI_VERSION_WITH_RESOLVE_QLREF
@@ -646,15 +654,15 @@ async function activateWithInstalledDistribution(
646654
) => {
647655
let filteredDBs = dbm.databaseItems;
648656
if (filteredDBs.length === 0) {
649-
void helpers.showAndLogErrorMessage('No databases found. Please add a suitable database to your workspace.');
657+
void showAndLogErrorMessage('No databases found. Please add a suitable database to your workspace.');
650658
return;
651659
}
652660
// If possible, only show databases with the right language (otherwise show all databases).
653-
const queryLanguage = await helpers.findLanguage(cliServer, uri);
661+
const queryLanguage = await findLanguage(cliServer, uri);
654662
if (queryLanguage) {
655663
filteredDBs = dbm.databaseItems.filter(db => db.language === queryLanguage);
656664
if (filteredDBs.length === 0) {
657-
void helpers.showAndLogErrorMessage(`No databases found for language ${queryLanguage}. Please add a suitable database to your workspace.`);
665+
void showAndLogErrorMessage(`No databases found for language ${queryLanguage}. Please add a suitable database to your workspace.`);
658666
return;
659667
}
660668
}
@@ -686,12 +694,12 @@ async function activateWithInstalledDistribution(
686694
}
687695
if (skippedDatabases.length > 0) {
688696
void logger.log(`Errors:\n${errors.join('\n')}`);
689-
void helpers.showAndLogWarningMessage(
697+
void showAndLogWarningMessage(
690698
`The following databases were skipped:\n${skippedDatabases.join('\n')}.\nFor details about the errors, see the logs.`
691699
);
692700
}
693701
} else {
694-
void helpers.showAndLogErrorMessage('No databases selected.');
702+
void showAndLogErrorMessage('No databases selected.');
695703
}
696704
},
697705
{
@@ -718,7 +726,7 @@ async function activateWithInstalledDistribution(
718726
// files may be hidden from the user.
719727
if (dirFound) {
720728
const fileString = files.map(file => path.basename(file)).join(', ');
721-
const res = await helpers.showBinaryChoiceDialog(
729+
const res = await showBinaryChoiceDialog(
722730
`You are about to run ${files.length} queries: ${fileString} Do you want to continue?`
723731
);
724732
if (!res) {
@@ -882,7 +890,7 @@ async function activateWithInstalledDistribution(
882890
token: CancellationToken
883891
) => {
884892
await qs.restartQueryServer(progress, token);
885-
void helpers.showAndLogInformationMessage('CodeQL Query Server restarted.', {
893+
void showAndLogInformationMessage('CodeQL Query Server restarted.', {
886894
outputLogger: queryServerLogger,
887895
});
888896
}, {
@@ -938,7 +946,7 @@ async function activateWithInstalledDistribution(
938946
commandRunner('codeQL.copyVersion', async () => {
939947
const text = `CodeQL extension version: ${extension?.packageJSON.version} \nCodeQL CLI version: ${await getCliVersion()} \nPlatform: ${os.platform()} ${os.arch()}`;
940948
await env.clipboard.writeText(text);
941-
void helpers.showAndLogInformationMessage(text);
949+
void showAndLogInformationMessage(text);
942950
}));
943951

944952
const getCliVersion = async () => {
@@ -960,7 +968,7 @@ async function activateWithInstalledDistribution(
960968
const credentials = await Credentials.initialize(ctx);
961969
const octokit = await credentials.getOctokit();
962970
const userInfo = await octokit.users.getAuthenticated();
963-
void helpers.showAndLogInformationMessage(`Authenticated to GitHub as user: ${userInfo.data.login}`);
971+
void showAndLogInformationMessage(`Authenticated to GitHub as user: ${userInfo.data.login}`);
964972
}
965973
}));
966974

extensions/ql-vscode/src/helpers.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as fs from 'fs-extra';
22
import * as glob from 'glob-promise';
33
import * as yaml from 'js-yaml';
44
import * as path from 'path';
5+
import * as tmp from 'tmp-promise';
56
import {
67
ExtensionContext,
78
Uri,
@@ -14,6 +15,17 @@ import { UserCancellationException } from './commandRunner';
1415
import { logger } from './logging';
1516
import { QueryMetadata } from './pure/interface-types';
1617

18+
// Shared temporary folder for the extension.
19+
export const tmpDir = tmp.dirSync({ prefix: 'queries_', keep: false, unsafeCleanup: true });
20+
export const upgradesTmpDir = path.join(tmpDir.name, 'upgrades');
21+
fs.ensureDirSync(upgradesTmpDir);
22+
23+
export const tmpDirDisposal = {
24+
dispose: () => {
25+
tmpDir.removeCallback();
26+
}
27+
};
28+
1729
/**
1830
* Show an error message and log it to the console
1931
*

extensions/ql-vscode/src/interface.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {
1414
import * as cli from './cli';
1515
import { CodeQLCliServer } from './cli';
1616
import { DatabaseEventKind, DatabaseItem, DatabaseManager } from './databases';
17-
import { showAndLogErrorMessage } from './helpers';
17+
import { showAndLogErrorMessage, tmpDir } from './helpers';
1818
import { assertNever } from './pure/helpers-pure';
1919
import {
2020
FromResultsViewMsg,
@@ -33,7 +33,7 @@ import { Logger } from './logging';
3333
import * as messages from './pure/messages';
3434
import { commandRunner } from './commandRunner';
3535
import { CompletedQueryInfo, interpretResults } from './query-results';
36-
import { QueryEvaluationInfo, tmpDir } from './run-queries';
36+
import { QueryEvaluationInfo } from './run-queries';
3737
import { parseSarifLocation, parseSarifPlainTextMessage } from './pure/sarif-utils';
3838
import {
3939
WebviewReveal,

extensions/ql-vscode/src/pure/helpers-pure.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,8 @@ export const asyncFilter = async function <T>(arr: T[], predicate: (arg0: T) =>
2929
const results = await Promise.all(arr.map(predicate));
3030
return arr.filter((_, index) => results[index]);
3131
};
32+
33+
export const ONE_DAY_IN_MS = 24 * 60 * 60 * 1000;
34+
export const ONE_HOUR_IN_MS = 1000 * 60 * 60;
35+
export const TWO_HOURS_IN_MS = 1000 * 60 * 60 * 2;
36+
export const THREE_HOURS_IN_MS = 1000 * 60 * 60 * 3;

extensions/ql-vscode/src/query-history.ts

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import { URLSearchParams } from 'url';
2828
import { QueryServerClient } from './queryserver-client';
2929
import { DisposableObject } from './pure/disposable-object';
3030
import { commandRunner } from './commandRunner';
31-
import { assertNever } from './pure/helpers-pure';
31+
import { assertNever, ONE_HOUR_IN_MS, TWO_HOURS_IN_MS } from './pure/helpers-pure';
3232
import { FullCompletedQueryInfo, FullQueryInfo, QueryStatus } from './query-results';
3333
import { DatabaseManager } from './databases';
3434
import { registerQueryHistoryScubber } from './query-history-scrubber';
@@ -83,8 +83,15 @@ export enum SortOrder {
8383
CountDesc = 'CountDesc',
8484
}
8585

86-
const ONE_HOUR_IN_MS = 1000 * 60 * 60;
87-
const TWO_HOURS_IN_MS = 1000 * 60 * 60 * 2;
86+
/**
87+
* Number of milliseconds two clicks have to arrive apart to be
88+
* considered a double-click.
89+
*/
90+
const DOUBLE_CLICK_TIME = 500;
91+
92+
const NO_QUERY_SELECTED = 'No query selected. Select a query history item you have already run and try again.';
93+
94+
const WORKSPACE_QUERY_HISTORY_FILE = 'workspace-query-history.json';
8895

8996
/**
9097
* Tree data provider for the query history view.
@@ -244,15 +251,6 @@ export class HistoryTreeDataProvider extends DisposableObject {
244251
}
245252
}
246253

247-
/**
248-
* Number of milliseconds two clicks have to arrive apart to be
249-
* considered a double-click.
250-
*/
251-
const DOUBLE_CLICK_TIME = 500;
252-
253-
const NO_QUERY_SELECTED = 'No query selected. Select a query history item you have already run and try again.';
254-
255-
const WORKSPACE_QUERY_HISTORY_FILE = 'workspace-query-history.json';
256254
export class QueryHistoryManager extends DisposableObject {
257255

258256
treeDataProvider: HistoryTreeDataProvider;
@@ -742,7 +740,7 @@ export class QueryHistoryManager extends DisposableObject {
742740
}
743741

744742
await this.tryOpenExternalFile(
745-
await finalSingleItem.completedQuery.query.ensureCsvProduced(this.qs, this.dbm)
743+
await finalSingleItem.completedQuery.query.ensureCsvAlerts(this.qs, this.dbm)
746744
);
747745
}
748746

extensions/ql-vscode/src/query-results.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,14 @@ import { DatabaseInfo } from './pure/interface-types';
1818
import { showAndLogErrorMessage } from './helpers';
1919
import { asyncFilter } from './pure/helpers-pure';
2020

21+
/**
22+
* query-results.ts
23+
* ----------------
24+
*
25+
* A collection of classes and functions that collectively
26+
* manage query results.
27+
*/
28+
2129
/**
2230
* A description of the information about a query
2331
* that is available before results are populated.

0 commit comments

Comments
 (0)