updateDi static method
Updates the Dependency Injection (DI) file at diPath to register a new usecase.
Implementation
static void updateDi(String diPath, String name, String feature) {
final file = File(diPath);
if (!file.existsSync()) {
print('DI file not found at $diPath. Skipping DI registration.');
return;
}
final content = file.readAsStringSync();
final pascal = Utils.pascal(name);
// Add import
final importLine = "import '../domain/usecases/${name}_usecase.dart';\n";
if (content.contains(importLine)) return;
// Find the last import and insert after it
final lastImportIndex = content.lastIndexOf('import ');
final endOfImports = content.indexOf('\n', lastImportIndex) + 1;
var newContent =
content.substring(0, endOfImports) +
importLine +
content.substring(endOfImports);
// Add registration
final registrationLine =
" sl.registerLazySingleton(() => ${pascal}UseCase(sl()));\n";
if (newContent.contains(registrationLine)) return;
// Find // Usecases or // Repository and insert before/after
if (newContent.contains('// Usecases')) {
newContent = newContent.replaceFirst(
'// Usecases',
'// Usecases\n$registrationLine',
);
} else {
// Fallback: insert before the last closing brace
final lastBrace = newContent.lastIndexOf('}');
newContent =
newContent.substring(0, lastBrace) +
registrationLine +
newContent.substring(lastBrace);
}
file.writeAsStringSync(newContent);
}