addClassIfMissing static method
Safely adds a class to the file if it doesn't already exist. If the file does not exist, it will create it.
Implementation
static void addClassIfMissing(String filePath, String className, String classTemplate) {
final file = File(filePath);
if (!file.existsSync()) {
file.createSync(recursive: true);
file.writeAsStringSync(classTemplate);
print('â
Created file and added class: $className');
return;
}
final content = file.readAsStringSync();
final classRegex = RegExp(r'\bclass\s+' + className + r'\b');
if (!classRegex.hasMatch(content)) {
file.writeAsStringSync('$content\n\n$classTemplate');
print('â
Added class $className to $filePath');
} else {
print('âšī¸ Class $className already exists in $filePath. Skipping class creation.');
}
}