addDependency method

void addDependency(
  1. String pubspecPath,
  2. String name,
  3. String version, {
  4. bool isDev = false,
})

Adds a dependency to pubspec.yaml.

Implementation

void addDependency(String pubspecPath, String name, String version, {bool isDev = false}) {
  final file = File(pubspecPath);
  if (!file.existsSync()) {
    throw CliException('pubspec.yaml not found at $pubspecPath');
  }

  final lines = file.readAsLinesSync();
  final targetSection = isDev ? 'dev_dependencies:' : 'dependencies:';

  int sectionIndex = -1;
  // Find the correct section starting at root level (no leading spaces)
  for (int i = 0; i < lines.length; i++) {
    if (lines[i].trim() == targetSection && !lines[i].startsWith(' ')) {
      sectionIndex = i;
      break;
    }
  }

  if (sectionIndex == -1) {
    // If the section doesn't exist, append it
    lines.add('');
    lines.add(targetSection);
    lines.add('  $name: $version');
    file.writeAsStringSync(lines.join('\n'));
    return;
  }

  // Check if dependency already exists under this section
  bool exists = false;
  for (int i = sectionIndex + 1; i < lines.length; i++) {
    final line = lines[i];
    // If we hit another root-level declaration, we finished the section
    if (line.isNotEmpty && !line.startsWith(' ') && !line.startsWith('#')) {
      break;
    }

    final trimmed = line.trim();
    if (trimmed.startsWith('$name:')) {
      exists = true;
      // Update version in-place
      lines[i] = '  $name: $version';
      break;
    }
  }

  if (!exists) {
    // Insert dependency right after the section header
    lines.insert(sectionIndex + 1, '  $name: $version');
  }

  file.writeAsStringSync(lines.join('\n'));
}