updateRootPubspecSync method
Updates the root pubspec.yaml to include a new package in the workspace.
Parameters:
packageName: the name of the new package to add.
Implementation
void updateRootPubspecSync({required String packageName}) {
log('đ Updating root pubspec.yaml to include "$packageName"...');
final file = fs.file('pubspec.yaml');
if (!file.existsSync()) {
throw Exception('â ī¸ Root pubspec.yaml not found.');
}
final content = file.readAsStringSync();
if (content.contains('- packages/*')) {
log('âšī¸ Wildcard "packages/*" detected. Skipping manual addition of "$packageName".');
return;
}
final packagePath = 'packages/$packageName';
if (content.contains('- $packagePath')) {
log('âšī¸ Package "$packageName" is already in the workspace.');
return;
}
final lines = content.split('\n');
final workspaceIndex = lines.indexWhere((line) => line.trim() == 'workspace:');
if (workspaceIndex == -1) {
throw Exception('â ī¸ "workspace:" section not found in root pubspec.yaml.');
}
// Find the end of the workspace list
int insertIndex = workspaceIndex + 1;
while (insertIndex < lines.length &&
(lines[insertIndex].trim().startsWith('-') ||
lines[insertIndex].trim().isEmpty ||
lines[insertIndex].trim().startsWith('#'))) {
insertIndex++;
}
lines.insert(insertIndex, ' - $packagePath');
file.writeAsStringSync(lines.join('\n'));
log('â
Root pubspec.yaml updated');
}