updatePubspecAssets method

Future<void> updatePubspecAssets({
  1. required String clientAssetPath,
  2. required List<String> requiredExtraAssets,
  3. bool keepDefaultEnv = true,
})

Rewrites the flutter.assets list in pubspec.yaml so that exactly one branding folder (the active client's) and the runtime env file are registered. The default client's fallback env entry is preserved.

With keepDefaultEnv false (generated app config), no env file stays registered at all, including the default client's.

Implementation

Future<void> updatePubspecAssets({
  required String clientAssetPath,
  required List<String> requiredExtraAssets,
  bool keepDefaultEnv = true,
}) 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() ?? [];

    final newAssets = currentAssets
        .map((a) => a.toString())
        .where(
            (asset) => !isManagedAsset(asset, keepDefaultEnv: keepDefaultEnv))
        .toList();

    final branding = 'assets/branding/$clientAssetPath/';
    if (!newAssets.contains(branding)) newAssets.add(branding);
    for (final 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,
    );
  }
}