All files / utilities/vscode diagnostic.ts

100% Statements 16/16
100% Branches 8/8
100% Functions 2/2
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57                            6x   6x                     16x   16x 14x 1x     13x   13x 6x   6x 5x     6x       7x   7x 6x       16x    
import * as vscode from 'vscode';
 
export type PrefixDiagnosticCode = 'UndefinedNamespacePrefixError' | 'UnusedNamespacePrefixHint' | string;
 
/**
 * Extract the prefix name from a line of text associated with an 'UnusedNamespacePrefixHint' diagnostic.
 * @param lineText The text to analyze.
 * @returns The extracted prefix name, or `undefined` if no prefix is found.
 */
function extractPrefixFromUnusedPrefixLine(lineText: string): string | undefined {
	// Range for unused prefix diagnostics is the whole line. Support both Turtle and SPARQL styles.
	// Examples:
	//   @prefix ex: <http://example/> .
	//   PREFIX ex: <http://example/>
	const match = lineText.match(/\b(?:@prefix|prefix|PREFIX)\s+([^\s:]+)\s*:/);
 
	return match?.[1];
}
 
/**
 * Extract prefixes from diagnostics emitted by the Mentor language server.
 * @param document The document associated with the diagnostics.
 * @param diagnostics The diagnostics to analyze.
 * @param errorCode The specific diagnostic code to filter by (e.g., 'UndefinedNamespacePrefixError').
 * @returns An array of prefix names associated with the specified diagnostic code.
 */
export function getPrefixesWithErrorCode(document: vscode.TextDocument, diagnostics: Iterable<vscode.Diagnostic>, errorCode: PrefixDiagnosticCode): string[] {
	const result = new Set<string>();
 
	for (const diagnostic of diagnostics) {
		if (diagnostic.code !== errorCode) {
			continue;
		}
 
		const text = document.getText(diagnostic.range);
 
		if (errorCode === 'UnusedNamespacePrefixHint') {
			const prefix = extractPrefixFromUnusedPrefixLine(text);
 
			if (prefix) {
				result.add(prefix);
			}
 
			continue;
		}
 
		// Default: assume diagnostic range includes a pname-like token.
		const prefix = text.split(':')[0];
 
		if (prefix) {
			result.add(prefix);
		}
	}
 
	return Array.from(result);
}