All files / src file-utils.ts

5.55% Statements 2/36
100% Branches 0/0
0% Functions 0/2
5.55% Lines 2/36

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 461x 1x                                                                                        
import * as vscode from "vscode";
import { Logger } from "./logger";
 
export async function readLineZeroBased(
    filePath: string,
    codeLine: number
): Promise<string | undefined> {
    const uri = vscode.Uri.file(filePath);
 
    // First, try to find the document if it's already open
    const openDocument = vscode.workspace.textDocuments.find(
        (doc) => doc.uri.fsPath === uri.fsPath
    );
 
    if (openDocument) {
        return getLineFromDocument(openDocument, codeLine);
    }
 
    // If not open, open it (without showing it in the editor)
    try {
        const document = await vscode.workspace.openTextDocument(uri);
        return getLineFromDocument(document, codeLine);
    } catch (error) {
        const logger = Logger.getInstance();
        // Log warning instead of silently failing - helps debug highlight positioning issues
        logger.warn(
            `Failed to read line ${codeLine} from file "${filePath}": ${error instanceof Error ? error.message : error}`
        );
        return undefined;
    }
}
 
function getLineFromDocument(
    document: vscode.TextDocument,
    codeLine: number
): string | undefined {
    if (0 <= codeLine && codeLine < document.lineCount) {
        return document.lineAt(codeLine).text.trim();
    }
    // Log debug message if line number is out of range
    Logger.tryGetInstance()?.debug(
        `Line ${codeLine} is out of range for file with ${document.lineCount} lines`
    );
    return undefined;
}