getCodeContext method

Map<String, String> getCodeContext(
  1. String filePath,
  2. int errorLine
)

Reads a file at filePath and returns a map containing lines around the errorLine as code context. Returns a map of the form: { 'lineNumber': 'line content', ... }

Implementation

Map<String, String> getCodeContext(String filePath, int errorLine) {
  try {
    final resolvedPath = resolveFilePath(filePath);
    final file = File(resolvedPath);
    if (!file.existsSync()) {
      throw FileSystemException("File does not exist", resolvedPath);
    }
    final lines = file.readAsLinesSync();
    const contextRadius = 5;
    final totalLines = lines.length;

    // Convert errorLine (1-indexed) to 0-index.
    final startIndex = (errorLine - contextRadius - 1).clamp(0, totalLines - 1);
    final endIndex = (errorLine + contextRadius - 1).clamp(0, totalLines - 1);

    final context = <String, String>{};
    for (int i = startIndex; i <= endIndex; i++) {
      context[(i + 1).toString()] = lines[i];
    }
    return context;
  } catch (e) {
    return {
      'hint': 'Unable to read file for context: $e'
    };
  }
}