updateRootPubspecSync method

void updateRootPubspecSync({
  1. required String packageName,
})

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');
}