updateWorkspaceDependency static method

Future<void> updateWorkspaceDependency(
  1. File pubspec,
  2. String packageName,
  3. Version newVersion
)

Updates a workspace dependency version while maintaining constraint format Updates both dependencies and dev_dependencies sections

Implementation

static Future<void> updateWorkspaceDependency(
  File pubspec,
  String packageName,
  Version newVersion,
) async {
  final pubspecEditor = await _getPubspec(pubspec.path);
  final pubspecContent = await pubspec.readAsString();
  final pubspecYaml = loadYaml(pubspecContent) as Map;

  // Helper function to update dependency in a section
  void updateDependencyInSection(String sectionName) {
    final section = pubspecYaml[sectionName];
    if (section == null || section is! Map) {
      return;
    }

    final dependency = section[packageName];
    if (dependency == null) {
      return;
    }

    if (dependency is String) {
      final newConstraint = _createConstraint(dependency, newVersion);
      pubspecEditor.update([sectionName, packageName], newConstraint);
    } else if (dependency is Map) {
      // For path dependencies or other complex formats, update version if present
      if (dependency.containsKey('version')) {
        final oldVersion = dependency['version'];
        if (oldVersion is String) {
          final newConstraint = _createConstraint(oldVersion, newVersion);
          pubspecEditor.update([sectionName, packageName, 'version'], newConstraint);
        }
      }
    } else {
      // Default to ^ constraint
      final newConstraint = '^${newVersion.toString()}';
      pubspecEditor.update([sectionName, packageName], newConstraint);
    }
  }

  // Update in dependencies section
  updateDependencyInSection('dependencies');

  // Update in dev_dependencies section
  updateDependencyInSection('dev_dependencies');

  await pubspec.writeAsString(pubspecEditor.toString());
}