formatSideBySide method

String formatSideBySide(
  1. FileDiff diff, {
  2. int width = 120,
})

Format a FileDiff as a side-by-side comparison.

width controls the total character width of the output (default 120).

Implementation

String formatSideBySide(FileDiff diff, {int width = 120}) {
  final colWidth = (width - 3) ~/ 2; // 3 = " | " separator
  final buf = StringBuffer();

  for (final hunk in diff.hunks) {
    // Collect old/new columns.
    final oldCol = <String>[];
    final newCol = <String>[];

    for (final line in hunk.lines) {
      switch (line.type) {
        case DiffLineType.context:
          oldCol.add(line.content);
          newCol.add(line.content);
          break;
        case DiffLineType.remove:
          oldCol.add(line.content);
          newCol.add('');
          break;
        case DiffLineType.add:
          oldCol.add('');
          newCol.add(line.content);
          break;
      }
    }

    final rows = math.max(oldCol.length, newCol.length);
    for (var i = 0; i < rows; i++) {
      final left = i < oldCol.length ? oldCol[i] : '';
      final right = i < newCol.length ? newCol[i] : '';
      buf.write(_pad(left, colWidth));
      buf.write(' | ');
      buf.writeln(_pad(right, colWidth));
    }
  }
  return buf.toString();
}