Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions src/ctrace/WorkspaceScanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,17 @@ let _cacheFile: string | undefined;
* Loads the analysis cache persisted by a previous session. Call once on
* activation; without a storage directory the cache stays in memory only.
*/
export async function initAnalysisCache(storageDir: string | undefined): Promise<void> {
// The load and the writes in flight: clearCache() waits for them, so that
// none of them can bring back what it deletes.
let _loading: Promise<void> = Promise.resolve();
let _persisting: Promise<void> = Promise.resolve();

export function initAnalysisCache(storageDir: string | undefined): Promise<void> {
_loading = loadAnalysisCache(storageDir);
return _loading;
}

async function loadAnalysisCache(storageDir: string | undefined): Promise<void> {
_cacheFile = storageDir ? path.join(storageDir, CACHE_FILE_NAME) : undefined;
if (!_cacheFile) { return; }
try {
Expand All @@ -77,7 +87,12 @@ export async function initAnalysisCache(storageDir: string | undefined): Promise
}

/** Writes the analysis cache to disk, dropping entries for files that no longer exist. */
export async function persistAnalysisCache(): Promise<void> {
export function persistAnalysisCache(): Promise<void> {
_persisting = _persisting.then(writeAnalysisCache);
return _persisting;
}

async function writeAnalysisCache(): Promise<void> {
if (!_cacheFile) { return; }
for (const fsPath of [..._analysisCache.keys()]) {
if (!await fileExists(fsPath)) { _analysisCache.delete(fsPath); }
Expand All @@ -95,6 +110,8 @@ export function cacheFileAnalysis(file: WorkspaceFile, contextKey: string, analy
}

export async function clearCache(): Promise<void> {
await _loading;
await _persisting;
_fileCache.clear();
_analysisCache.clear();
if (_cacheFile) {
Expand Down
10 changes: 10 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -679,8 +679,18 @@ export function activate(context: vscode.ExtensionContext) {

context.subscriptions.push(
vscode.commands.registerCommand('ctrace.clearAnalysisCache', async () => {
// A running scan would write its results back right after.
if (isRunning) {
vscode.window.showWarningMessage('An analysis is running: cancel it or wait for it to finish, then clear the cache.');
return;
}
// Waits for the cache load at startup and for writes still in flight.
await clearCache();
StackManager.instance.clear();
// The ignore-list listener republishes these: they must go too.
lastSarifByFile = new Map();
republishPending = false;
clearDiagnostics(diagnosticCollection);
await findingsStore.clear();
sidebarProvider.postMessage({ type: 'clear-results' });
vscode.window.showInformationMessage('Ctrace analysis cache and saved results cleared.');
Expand Down
103 changes: 103 additions & 0 deletions src/test-workspace/clearCache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import * as assert from 'assert';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as vscode from 'vscode';
import * as AnalysisRunner from '../ctrace/AnalysisRunner';
import * as BinaryUpdater from '../ctrace/BinaryUpdater';
import { setMockWslAvailableForTesting } from '../ctrace/CommandBuilder';
import { IGNORE_FILE_NAME } from '../ctrace/FindingIgnoreList';
import { setScanDirectoryForTesting } from '../ctraceRunner';

/** Clear Analysis Cache, after a real Run Analysis whose ctrace reports one finding. */
suite('Clear Analysis Cache', function () {
this.timeout(60000);

const runner = AnalysisRunner as { runCommand: typeof AnalysisRunner.runCommand };
const updater = BinaryUpdater as { ensureBinary: typeof BinaryUpdater.ensureBinary };
const originalRunCommand = runner.runCommand;
const originalEnsureBinary = updater.ensureBinary;
let work = '';
let root = '';
let sample = '';
let ignoreFile = '';
let gate: Promise<void> | undefined;

const sarif = () => JSON.stringify({
$schema: 'https://json.schemastore.org/sarif-2.1.0.json',
version: '2.1.0',
runs: [{
tool: { driver: { name: 'cppcheck' } },
results: [{
ruleId: 'testRule', level: 'warning', message: { text: 'a finding to clear' },
locations: [{ physicalLocation: { artifactLocation: { uri: sample }, region: { startLine: 1 } } }],
}],
}],
});

const diagnostics = () => vscode.languages.getDiagnostics(vscode.Uri.file(sample))
.filter(d => d.source?.startsWith('CoreTrace'));
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const run = () => vscode.commands.executeCommand('ctrace.runAnalysis', {
filePath: sample,
uiState: { staticEnabled: false, staticTools: [], dynamicEnabled: false, dynamicTools: [] },
});

suiteSetup(async () => {
root = vscode.workspace.workspaceFolders![0].uri.fsPath;
sample = path.join(root, 'sample.c');
ignoreFile = path.join(root, IGNORE_FILE_NAME);
work = fs.mkdtempSync(path.join(os.tmpdir(), 'ctrace-clear-'));
const fakeBinary = path.join(work, 'ctrace');
fs.writeFileSync(fakeBinary, '#!/bin/sh\n', { mode: 0o755 });
updater.ensureBinary = async () => fakeBinary;
runner.runCommand = async (command: string) => {
if (gate) { await gate; }
// The stack pass gets nothing; the SARIF pass reports the finding.
return { stdout: command.includes('--sarif-format') ? sarif() : '', stderr: '', exitCode: 0 };
};
setMockWslAvailableForTesting(true);
setScanDirectoryForTesting(path.join(work, 'scan'));
await vscode.extensions.getExtension('CoreTrace.coretrace')!.activate();
});

suiteTeardown(() => {
runner.runCommand = originalRunCommand;
updater.ensureBinary = originalEnsureBinary;
setMockWslAvailableForTesting(null);
setScanDirectoryForTesting(undefined);
fs.rmSync(ignoreFile, { force: true });
fs.rmSync(work, { recursive: true, force: true });
});

test('the Problems panel is cleared, and an ignore-list change does not bring the findings back', async function () {
if (process.platform === 'win32') { this.skip(); }
await run();
assert.strictEqual(diagnostics().length, 1, 'the run should publish its finding');

await vscode.commands.executeCommand('ctrace.clearAnalysisCache');
assert.strictEqual(diagnostics().length, 0, 'Clear Analysis Cache must clear the Problems panel');

// Changing the ignore list republishes the last results: there must be none left.
fs.writeFileSync(ignoreFile, JSON.stringify({ version: 1, ignored: [{ fingerprint: 'abcdef123456' }] }));
await sleep(1500);
assert.strictEqual(diagnostics().length, 0, 'cleared findings came back after an ignore-list change');
});

test('clearing is refused while an analysis runs, so it cannot write its results back', async function () {
if (process.platform === 'win32') { this.skip(); }
await vscode.commands.executeCommand('ctrace.clearAnalysisCache');
let release!: () => void;
gate = new Promise(resolve => { release = resolve; });
const running = run();
await sleep(300);
await vscode.commands.executeCommand('ctrace.clearAnalysisCache');
release();
gate = undefined;
await running;
assert.strictEqual(diagnostics().length, 1, 'the run finished with its finding, the clear was refused');

await vscode.commands.executeCommand('ctrace.clearAnalysisCache');
assert.strictEqual(diagnostics().length, 0);
});
});
Loading