embedFile function
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 asBENCHMARK.md.target: the file to update, such asREADME.md.startMarker: the line after which the content goes.endMarker: the line before which the content ends.
Throws:
- FileSystemException if a file cannot be read or written.
- FormatException if a marker is missing from
target.
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;
}