addMethodIfMissing static method

void addMethodIfMissing(
  1. String filePath,
  2. String className,
  3. String methodName,
  4. String methodTemplate,
)

Safely adds a method to a specific class in the file if it doesn't already exist.

Implementation

static void addMethodIfMissing(String filePath, String className, String methodName, String methodTemplate) {
  final file = File(filePath);
  if (!file.existsSync()) {
    print('❌ File does not exist: $filePath. Cannot add method $methodName to class $className.');
    return;
  }

  final content = file.readAsStringSync();

  // 1. Check if the class exists in the file
  final classRegex = RegExp(r'\bclass\s+' + className + r'\b');
  final classMatch = classRegex.firstMatch(content);
  if (classMatch == null) {
    print('❌ Class $className not found in $filePath. Cannot add method $methodName.');
    return;
  }

  // 2. Check if the method already exists in the file (matching declaration, not calls)
  final methodDeclRegex = RegExp(r'\b' + methodName + r'\s*\([^)]*\)\s*(?:async\s*)?(?:{|\b=>)');
  if (methodDeclRegex.hasMatch(content)) {
    print('ℹ️ Method $methodName already exists in $filePath. Skipping method creation.');
    return;
  }

  // 3. Find the closing brace of the class to insert the method
  final classIndex = classMatch.start;
  final closingBraceIndex = _findClassClosingBraceIndex(content, classIndex);

  if (closingBraceIndex == -1) {
    print('❌ Could not find closing brace for class $className in $filePath.');
    return;
  }

  final before = content.substring(0, closingBraceIndex);
  final after = content.substring(closingBraceIndex);

  // Format the method to make sure it has proper indentation
  final formattedMethod = '\n  $methodTemplate\n';

  file.writeAsStringSync('$before$formattedMethod$after');
  print('✅ Added method $methodName to class $className in $filePath');
}