|
| 1 | +import * as vscode from 'vscode' |
| 2 | +import { parentPort } from './common' |
| 3 | + |
| 4 | +export function activateCodeLens(context: vscode.ExtensionContext) { |
| 5 | + // Register the CodeLens provider for YAML files |
| 6 | + const codelensProvider = new CodelensProvider() |
| 7 | + context.subscriptions.push( |
| 8 | + vscode.languages.registerCodeLensProvider( |
| 9 | + { language: 'yaml', pattern: '**/*.yml' }, // Only trigger for YAML files |
| 10 | + codelensProvider, |
| 11 | + ), |
| 12 | + ) |
| 13 | + |
| 14 | + // Register the command that the CodeLens will execute |
| 15 | + const runRuleCommand = vscode.commands.registerCommand( |
| 16 | + 'ast-grep.runRule', |
| 17 | + (ruleId: string, text: string) => { |
| 18 | + parentPort.postMessage('searchByYAML', { |
| 19 | + text, |
| 20 | + }) |
| 21 | + }, |
| 22 | + ) |
| 23 | + |
| 24 | + context.subscriptions.push(runRuleCommand) |
| 25 | +} |
| 26 | + |
| 27 | +class CodelensProvider implements vscode.CodeLensProvider { |
| 28 | + provideCodeLenses( |
| 29 | + document: vscode.TextDocument, |
| 30 | + _token: vscode.CancellationToken, |
| 31 | + ): vscode.CodeLens[] { |
| 32 | + const codeLenses: vscode.CodeLens[] = [] |
| 33 | + const text = document.getText() |
| 34 | + |
| 35 | + // Look for rule definitions in YAML files (sgconfig.yml) |
| 36 | + const ruleMatches = text.matchAll(/^(\s*)id:\s*(.+)$/gm) |
| 37 | + |
| 38 | + for (const match of ruleMatches) { |
| 39 | + const ruleId = match[2].trim() |
| 40 | + const line = document.positionAt(match.index!).line |
| 41 | + const range = new vscode.Range(line, 0, line, 0) |
| 42 | + |
| 43 | + const command: vscode.Command = { |
| 44 | + title: `Run rule: ${ruleId}`, |
| 45 | + command: 'ast-grep.runRule', |
| 46 | + arguments: [ruleId, text], |
| 47 | + } |
| 48 | + |
| 49 | + codeLenses.push(new vscode.CodeLens(range, command)) |
| 50 | + } |
| 51 | + |
| 52 | + return codeLenses |
| 53 | + } |
| 54 | + |
| 55 | + resolveCodeLens(codeLens: vscode.CodeLens, _token: vscode.CancellationToken): vscode.CodeLens { |
| 56 | + return codeLens |
| 57 | + } |
| 58 | +} |
0 commit comments