apply method

  1. @override
Future<String> apply(
  1. String original
)
override

Returns original, the content of file, with this change applied.

Implementation

@override
Future<String> apply(String original) async {
  final parsed = parseString(content: original);
  final unit = parsed.unit;

  final edits = <_Edit>[];
  unit.visitChildren(
    MatchWidgetVisitor(
      targetWidget: widgetName,
      onMatch: (node) => edits.addAll(_editsFor(node)),
    ),
  );

  // An edit inside another one, such as in a nested widget passed as an
  // argument that is removed or replaced, goes away with that argument.
  // Of two edits that start together, the wider one comes first, so that
  // the argument that starts with `const` goes rather than the `const`.
  edits.sort(
    (a, b) => a.offset != b.offset
        ? a.offset.compareTo(b.offset)
        : b.end.compareTo(a.end),
  );
  final applied = <_Edit>[];
  for (final edit in edits) {
    if (applied.isEmpty || edit.offset >= applied.last.end) {
      applied.add(edit);
    }
  }

  // Edit from the end so the offsets of the earlier edits stay valid.
  var result = original;
  for (final edit in applied.reversed) {
    result = result.replaceRange(edit.offset, edit.end, edit.text);
  }

  return dartFormater.format(result);
}