addDependenciesEfficiently function

Future<void> addDependenciesEfficiently(
  1. List<Map<String, dynamic>> deps, {
  2. required bool isDev,
})

Implementation

Future<void> addDependenciesEfficiently(
  List<Map<String, dynamic>> deps, {
  required bool isDev,
}) async {
  final file = File('pubspec.yaml');

  if (!file.existsSync()) {
    throw Exception("❌ pubspec.yaml not found");
  }

  final content = file.readAsStringSync();
  final yaml = loadYaml(content) as Map;
  final editor = YamlEditor(content);

  final section = isDev ? 'dev_dependencies' : 'dependencies';

  // 1) إذا القسم غير موجود → أنشئه كـ Map {}
  if (!yaml.containsKey(section)) {
    editor.update([section], {});
  } else {
    // 2) إذا القسم موجود لكنه ليس Map → أجبره أن يكون Map {}
    final value = yaml[section];
    if (value == null || value is! Map) {
      editor.update([section], {});
    }
  }

  // تحديث الـ YAML بعد الإصلاح
  final updatedYaml = loadYaml(editor.toString()) as Map;
  final existingSection = updatedYaml[section] as Map;

  // 3) إضافة المكتبات داخل القسم
  for (final dep in deps) {
    final name = dep['name'] as String;
    final version = dep['version'] as String;
    if (!existingSection.containsKey(name)) {
      editor.update([section, name], version);
    }
  }

  // 4) كتابة الملف بصيغة multiline للوضوح
  String updatedContent = editor.toString();

  // تحويل inline map {key: value, ...} إلى multiline
  updatedContent = updatedContent.replaceAllMapped(
    RegExp('$section:\\s*\\{([^}]*)\\}'),
    (match) {
      final entries = match[1]!
          .split(',')
          .map((e) => e.trim())
          .where((e) => e.isNotEmpty)
          .join('\n  ');
      return '$section:\n  $entries';
    },
  );

  file.writeAsStringSync(updatedContent);

  print("✅ Added ${deps.length} packages to $section");
}