generateDiff function

String generateDiff({
  1. required String oldContent,
  2. required String newContent,
  3. String oldPath = 'a/file',
  4. String newPath = 'b/file',
  5. int contextLines = 3,
})

Generate a simple unified diff from old and new content.

Implementation

String generateDiff({
  required String oldContent,
  required String newContent,
  String oldPath = 'a/file',
  String newPath = 'b/file',
  int contextLines = 3,
}) {
  final oldLines = oldContent.split('\n');
  final newLines = newContent.split('\n');

  // Simple LCS-based diff
  final lcs = _longestCommonSubsequence(oldLines, newLines);
  final hunks = _buildHunks(oldLines, newLines, lcs, contextLines);

  if (hunks.isEmpty) return '';

  final buf = StringBuffer()
    ..writeln('--- $oldPath')
    ..writeln('+++ $newPath');

  for (final hunk in hunks) {
    buf.writeln(
      '@@ -${hunk.oldStart},${hunk.oldLines} '
      '+${hunk.newStart},${hunk.newLines} @@',
    );
    for (final line in hunk.lines) {
      switch (line.type) {
        case DiffLineType.addition:
          buf.writeln('+${line.content}');
        case DiffLineType.removal:
          buf.writeln('-${line.content}');
        case DiffLineType.context:
          buf.writeln(' ${line.content}');
        case DiffLineType.header:
          buf.writeln(line.content);
      }
    }
  }

  return buf.toString();
}