removePackages function
Removes the specified packages from the 'dependencies' section of pubspec.yaml.
Creates a backup of the original pubspec.yaml before modifying.
Implementation
Future<void> removePackages(String pubspecPath, List<String> packagesToRemove) async {
final pubspecFile = File(pubspecPath);
final pubspecContent = await pubspecFile.readAsString();
// Create a backup
await pubspecFile.copy('$pubspecPath.bak');
try {
final editor = YamlEditor(pubspecContent);
// Remove each package individually instead of replacing the entire dependencies section
for (final package in packagesToRemove) {
try {
editor.remove(['dependencies', package]);
print('Removed package: $package');
} catch (e) {
print('Could not remove package $package: ${e.toString()}');
}
}
// Write the modified content back to pubspec.yaml
await pubspecFile.writeAsString(editor.toString());
print('Successfully updated pubspec.yaml');
} catch (e) {
// If there was an error, restore the backup
final backupFile = File('$pubspecPath.bak');
if (await backupFile.exists()) {
await backupFile.copy(pubspecPath);
print('Error occurred: ${e.toString()}');
print('Restored pubspec.yaml from backup');
}
rethrow;
}
}