embedFile function

bool embedFile({
  1. String source = 'BENCHMARK.md',
  2. String target = 'README.md',
  3. String? startMarker,
  4. String? endMarker,
})

Replaces everything between two marker lines of target with the content of source, and returns whether target changed.

The markers default to <!-- file: SOURCE --> and <!-- end SOURCE -->, where SOURCE is source as given. Marker lines are matched after trimming whitespace and are kept. target keeps its own line endings (CRLF or LF), and is not rewritten when nothing changes.

Parameters:

  • source: the file to embed, such as BENCHMARK.md.
  • target: the file to update, such as README.md.
  • startMarker: the line after which the content goes.
  • endMarker: the line before which the content ends.

Throws:

Implementation

bool embedFile({
  String source = 'BENCHMARK.md',
  String target = 'README.md',
  String? startMarker,
  String? endMarker,
}) {
  final start = startMarker ?? '<!-- file: $source -->';
  final end = endMarker ?? '<!-- end $source -->';
  final body = File(source).readAsLinesSync();
  final targetFile = File(target);
  final original = targetFile.readAsStringSync();
  final eol = original.contains('\r\n') ? '\r\n' : '\n';

  final output = <String>[];
  var inside = false;
  var found = false;
  for (final line in original.split(eol)) {
    final marker = line.trim();
    if (!inside && marker == start) {
      output
        ..add(line)
        ..addAll(body);
      inside = true;
      found = true;
    } else if (inside && marker == end) {
      output.add(line);
      inside = false;
    } else if (!inside) {
      output.add(line);
    }
  }
  if (!found) {
    throw FormatException('Start marker "$start" not found in $target');
  }
  if (inside) {
    throw FormatException('End marker "$end" not found in $target');
  }

  final updated = output.join(eol);
  if (updated == original) return false;
  targetFile.writeAsStringSync(updated);
  return true;
}