applyPatch method

String applyPatch(
  1. String original,
  2. List<DiffHunk> hunks
)

Apply a list of hunks to original text and return the result.

Implementation

String applyPatch(String original, List<DiffHunk> hunks) {
  final lines = original.isEmpty ? <String>[] : original.split('\n');
  var offset = 0;

  for (final hunk in hunks) {
    final start = hunk.oldStart - 1 + offset;
    final toRemove = <int>[];
    final toInsert = <String>[];
    var idx = start;

    for (final line in hunk.lines) {
      switch (line.type) {
        case DiffLineType.context:
          idx++;
          break;
        case DiffLineType.remove:
          toRemove.add(idx);
          idx++;
          break;
        case DiffLineType.add:
          toInsert.add(line.content);
          break;
      }
    }

    // Remove lines in reverse order to keep indices stable.
    for (final i in toRemove.reversed) {
      if (i < lines.length) lines.removeAt(i);
    }
    // Insert at the position of the first removal (or current index).
    final insertAt = toRemove.isEmpty ? start : toRemove.first;
    for (var i = 0; i < toInsert.length; i++) {
      lines.insert(insertAt + i, toInsert[i]);
    }

    offset += toInsert.length - toRemove.length;
  }

  return lines.join('\n');
}