scanDiagnosticsToJson function

Map<String, Object> scanDiagnosticsToJson(
  1. List<ScanDiagnostic> diagnostics, {
  2. Map<String, Object>? failOn,
})

Serializes diagnostics to the same JSON structure used by dart run saropa_lints scan --format json.

Schema:

  • version: 1 (int)
  • diagnostics: list of objects with: filePath, line, column, endLine, endColumn, ruleName, severity, problemMessage, correctionMessage (opt)
  • summary: object with totalCount, byFile (map filePath -> count), byRule (map ruleName -> count)
  • failOn (optional): object with threshold and thresholdMet when --fail-on is active — explains why exit code may differ from the diagnostic list contents.

Implementation

Map<String, Object> scanDiagnosticsToJson(
  List<ScanDiagnostic> diagnostics, {
  Map<String, Object>? failOn,
}) {
  final list = diagnostics
      .map(
        (d) => <String, Object?>{
          'filePath': d.filePath,
          'line': d.line,
          'column': d.column,
          'endLine': d.endLine,
          'endColumn': d.endColumn,
          'ruleName': d.ruleName,
          'severity': d.severity,
          // Rule-declared impact when available (null for non-saropa rules).
          'impact': d.impact,
          'problemMessage': d.problemMessage,
          'correctionMessage': d.correctionMessage,
        },
      )
      .toList();

  final byFile = <String, int>{};
  final byRule = <String, int>{};
  for (final d in diagnostics) {
    byFile[d.filePath] = (byFile[d.filePath] ?? 0) + 1;
    byRule[d.ruleName] = (byRule[d.ruleName] ?? 0) + 1;
  }

  return <String, Object>{
    kScanJsonVersion: 1,
    kScanJsonDiagnostics: list,
    kScanJsonSummary: <String, Object>{
      kScanJsonTotalCount: diagnostics.length,
      kScanJsonByFile: byFile,
      kScanJsonByRule: byRule,
    },
    // Inject --fail-on metadata when present so JSON consumers understand
    // why the exit code may disagree with an empty diagnostics array.
    if (failOn != null) 'failOn': failOn,
  };
}