|
| 1 | +import * as vscode from 'vscode' |
| 2 | +import { LSPClient } from '../lsp/lsp' |
| 3 | + |
| 4 | +export const controller = vscode.tests.createTestController( |
| 5 | + 'sqlmeshTests', |
| 6 | + 'SQLMesh Tests', |
| 7 | +) |
| 8 | + |
| 9 | +export const setupTestController = (lsp: LSPClient) => { |
| 10 | + // First, create the `resolveHandler`. This may initially be called with |
| 11 | + // "undefined" to ask for all tests in the workspace to be discovered, usually |
| 12 | + // when the user opens the Test Explorer for the first time. |
| 13 | + controller.resolveHandler = async test => { |
| 14 | + if (!test) { |
| 15 | + await discoverAllFilesInWorkspace() |
| 16 | + } else { |
| 17 | + await parseTestsInFileContents(test) |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + // When text documents are open, parse tests in them. |
| 22 | + vscode.workspace.onDidOpenTextDocument(parseTestsInDocument) |
| 23 | + // We could also listen to document changes to re-parse unsaved changes: |
| 24 | + vscode.workspace.onDidChangeTextDocument(e => |
| 25 | + parseTestsInDocument(e.document), |
| 26 | + ) |
| 27 | + |
| 28 | + // In this function, we'll get the file TestItem if we've already found it, |
| 29 | + // otherwise we'll create it with `canResolveChildren = true` to indicate it |
| 30 | + // can be passed to the `controller.resolveHandler` to gets its children. |
| 31 | + function getOrCreateFile(uri: vscode.Uri) { |
| 32 | + const existing = controller.items.get(uri.toString()) |
| 33 | + if (existing) { |
| 34 | + return existing |
| 35 | + } |
| 36 | + |
| 37 | + const file = controller.createTestItem( |
| 38 | + uri.toString(), |
| 39 | + uri.path.split('/').pop()!, |
| 40 | + uri, |
| 41 | + ) |
| 42 | + file.canResolveChildren = true |
| 43 | + return file |
| 44 | + } |
| 45 | + |
| 46 | + function parseTestsInDocument(e: vscode.TextDocument) { |
| 47 | + if (e.uri.scheme === 'file' && e.uri.path.endsWith('.md')) { |
| 48 | + parseTestsInFileContents(getOrCreateFile(e.uri), e.getText()) |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + async function parseTestsInFileContents( |
| 53 | + file: vscode.TestItem, |
| 54 | + contents?: string, |
| 55 | + ) { |
| 56 | + // If a document is open, VS Code already knows its contents. If this is being |
| 57 | + // called from the resolveHandler when a document isn't open, we'll need to |
| 58 | + // read them from disk ourselves. |
| 59 | + if (contents === undefined) { |
| 60 | + const rawContent = await vscode.workspace.fs.readFile(file.uri) |
| 61 | + contents = new TextDecoder().decode(rawContent) |
| 62 | + } |
| 63 | + |
| 64 | + // some custom logic to fill in test.children from the contents... |
| 65 | + } |
| 66 | +} |
0 commit comments