addImportIfMissing static method
Safely adds an import statement to the top of the file if it doesn't already exist.
Implementation
static void addImportIfMissing(String filePath, String importLine) {
final file = File(filePath);
if (!file.existsSync()) {
file.createSync(recursive: true);
file.writeAsStringSync('$importLine\n');
print('â
Created file and added import: $importLine');
return;
}
final content = file.readAsStringSync();
// Normalize spaces and quotes to check for existence
final normalizedImport = importLine.replaceAll("'", '"').replaceAll(' ', '');
final normalizedContent = content.replaceAll("'", '"').replaceAll(' ', '');
if (!normalizedContent.contains(normalizedImport)) {
file.writeAsStringSync('$importLine\n$content');
print('â
Added import to $filePath: $importLine');
} else {
print('âšī¸ Import already exists in $filePath: $importLine');
}
}