updateDependencies method
Updates pubspec.yaml and returns a summary of changes made.
Implementation
Future<DependencyUpdateResult> updateDependencies() async {
final pubspecFile = File('$projectPath/pubspec.yaml');
if (!pubspecFile.existsSync()) {
return const DependencyUpdateResult(added: [], commented: []);
}
String content = pubspecFile.readAsStringSync();
final added = <String>[];
final commented = <String>[];
// Ensure dev_dependencies section exists before inserting into it.
if (!content.contains('dev_dependencies:')) {
content = '$content\ndev_dependencies:\n';
}
for (final entry in _riverpodDeps.entries) {
if (!_hasDep(content, entry.key)) {
content = _addDependency(content, entry.key, entry.value);
added.add(entry.key);
}
}
for (final entry in _riverpodDevDeps.entries) {
if (!_hasDep(content, entry.key)) {
content = _addDevDependency(content, entry.key, entry.value);
added.add(entry.key);
}
}
// Comment out legacy deps using replaceAllMapped so capture groups work.
for (final pkg in _legacyDeps) {
final pattern = RegExp(
'^(\\s+)(${RegExp.escape(pkg)}:)',
multiLine: true,
);
if (pattern.hasMatch(content)) {
content = content.replaceAllMapped(
pattern,
(m) => '${m.group(1)}# ${m.group(2)}',
);
commented.add(pkg);
}
}
pubspecFile.writeAsStringSync(content);
// Run `flutter pub get` so the project compiles immediately after migration.
bool pubGetOk = false;
if (added.isNotEmpty || commented.isNotEmpty) {
try {
final result = await Process.run(
'flutter',
['pub', 'get'],
workingDirectory: projectPath,
);
pubGetOk = result.exitCode == 0;
if (!pubGetOk) {
stderr.writeln(
'[Migrator] WARNING: flutter pub get failed '
'(exit ${result.exitCode}). Run it manually.\n'
'${result.stderr}',
);
}
} catch (e) {
stderr.writeln('[Migrator] WARNING: Could not run flutter pub get: $e');
}
}
return DependencyUpdateResult(
added: added,
commented: commented,
pubGetSucceeded: pubGetOk,
);
}