updatePubspecAssets method

Future<void> updatePubspecAssets({
  1. required String clientAssetPath,
  2. required List<String> requiredExtraAssets,
})

Specifically handles the complex 'assets' list in pubspec.yaml

Implementation

Future<void> updatePubspecAssets({
  required String clientAssetPath,
  required List<String> requiredExtraAssets,
}) async {
  final file = File(p.join(projectDir, 'pubspec.yaml'));
  if (!file.existsSync()) {
    throw BuildException(
      'pubspec.yaml not found at project root.',
      fix:
          'Ensure you are running the command from a valid Flutter project root.',
    );
  }

  try {
    final content = await file.readAsString();
    final editor = YamlEditor(content);

    final yaml = loadYaml(content);
    final currentAssets =
        (yaml['flutter']?['assets'] as YamlList?)?.toList() ?? [];

    // Filter out old branding paths and specific env paths
    final newAssets = currentAssets.where((a) {
      final s = a.toString();
      return !s.contains('assets/branding/') && !s.contains('.env');
    }).toList();

    // Add new entries
    newAssets.add('assets/branding/$clientAssetPath/');
    for (var asset in requiredExtraAssets) {
      if (!newAssets.contains(asset)) newAssets.add(asset);
    }

    editor.update(['flutter', 'assets'], newAssets);
    await file.writeAsString(editor.toString());
  } catch (e, s) {
    throw BuildException(
      'Failed to update assets in pubspec.yaml',
      fix:
          'Check if pubspec.yaml has valid syntax and a "flutter:" key defined.',
      originalStackTrace: s,
    );
  }
}