rewriteFile method

Future<String?> rewriteFile({
  1. required String filePath,
  2. required List<DetectedString> stringsToExtract,
  3. required bool dryRun,
})

Rewrite a single file

Implementation

Future<String?> rewriteFile({
  required String filePath,
  required List<DetectedString> stringsToExtract,
  required bool dryRun,
}) async {
  if (stringsToExtract.isEmpty) {
    return null;
  }

  _log('Rewriting: $filePath (${stringsToExtract.length} strings)');

  // Read the file
  final content = await File(filePath).readAsString();

  // Parse the file
  final parseResult = parseString(
    content: content,
    throwIfDiagnostics: false,
  );

  // Build the rewriter visitor
  final rewriter = _StringRewriterVisitor(
    stringsToExtract: stringsToExtract,
    config: config,
    verbose: verbose,
  );

  // Visit the AST to collect edits
  parseResult.unit.accept(rewriter);

  // Apply edits in reverse order (to maintain offsets)
  final edits = rewriter.edits..sort((a, b) => b.offset.compareTo(a.offset));

  String modifiedContent = content;
  for (final edit in edits) {
    modifiedContent = modifiedContent.replaceRange(
      edit.offset,
      edit.offset + edit.length,
      edit.replacement,
    );
  }

  // Write back to file
  if (!dryRun) {
    await File(filePath).writeAsString(modifiedContent);
    _log('✓ Rewrote: $filePath');
  } else {
    _log('Would rewrite: $filePath');
  }

  return modifiedContent;
}