findAndReplace static method
Replaces searchString with replacement on every line that contains it.
Set warnIfMissing for anchor-critical calls (where the search string is
a code anchor that must exist): if no line matches — which can happen if
dart format wrapped the anchor across lines — it prints an error instead
of silently doing nothing, so the failure is visible rather than producing
broken generated code. Leave it false for best-effort replacements that
legitimately may not match (e.g. expanding empty {} bodies).
Implementation
static Future<void> findAndReplace({
required String filePath,
required String searchString,
required String replacement,
bool warnIfMissing = false,
}) async {
try {
final file = File(filePath);
List<String> lines = await file.readAsLines();
bool matched = false;
for (int i = 0; i < lines.length; i++) {
if (lines[i].contains(searchString)) {
lines[i] = lines[i].replaceAll(searchString, replacement);
matched = true;
}
}
if (!matched && warnIfMissing) {
Utility.errorPrinter(
text: '$kError anchor "$searchString" not found in $filePath; '
'no replacement made.',
);
}
await file.writeAsString(lines.join('\n'));
} catch (e) {
Utility.errorPrinter(text: '$kError $e');
}
}