insertBeforeClosingBrace method
Insert code before the closing brace of the last class in a file Useful for adding methods to a class
Implementation
Future<void> insertBeforeClosingBrace(String filePath, String code) async {
if (!fileExists(filePath)) {
error('File not found: $filePath');
return;
}
String content = await readFile(filePath);
// Find the last class declaration and track its closing brace
final classMatches = RegExp(r'class\s+\w+').allMatches(content).toList();
if (classMatches.isNotEmpty) {
final lastClassStart = classMatches.last.start;
int braceCount = 0;
int? classBraceIndex;
for (int i = lastClassStart; i < content.length; i++) {
if (content[i] == '{') braceCount++;
if (content[i] == '}') {
braceCount--;
if (braceCount == 0) {
classBraceIndex = i;
break;
}
}
}
if (classBraceIndex != null) {
content = content.substring(0, classBraceIndex) +
'\n$code\n' +
content.substring(classBraceIndex);
await writeFile(filePath, content);
}
}
}