addDependency method

Future<void> addDependency(
  1. String packageName,
  2. String version, {
  3. bool isDev = false,
})

Adds a dependency to pubspec.yaml

Implementation

Future<void> addDependency(String packageName, String version,
    {bool isDev = false}) async {
  final pubspec = await _loadPubspec();
  final targetBlock = isDev ? 'dev_dependencies' : 'dependencies';

  final deps = pubspec[targetBlock] as Map<String, dynamic>? ?? {};

  // Conflict detection
  if (deps.containsKey(packageName)) {
    final currentVersion = deps[packageName];
    if (currentVersion != version && currentVersion != 'any') {
      throw ConflictException(
        'Package $packageName is already installed with version $currentVersion, but $version was requested.',
      );
    }
    // Already installed with the same version
    return;
  }

  // String manipulation to insert
  final file = File(pubspecPath);
  final lines = await file.readAsLines();

  final blockIndex =
      lines.indexWhere((line) => line.trim() == '$targetBlock:');

  if (blockIndex == -1) {
    // Block doesn't exist, append it
    lines.add('');
    lines.add('$targetBlock:');
    lines.add('  $packageName: $version');
  } else {
    // Insert after the block header, alphabetically or just right after
    lines.insert(blockIndex + 1, '  $packageName: $version');
  }

  await file.writeAsString(lines.join('\n') + '\n');
}