findPreset function

Map<String, dynamic> findPreset(
  1. YamlMap config,
  2. List<String> commandPath,
  3. String presetName
)

Looks up a preset by presetName for the given commandPath.

The commandPath is a list of command segments, e.g. ['report'] or ['run', 'flutter-test-coverage-workaround']. The function walks the nested YAML structure under the commands key to find the preset.

Returns the preset as a Map<String, dynamic> (without the name key), or throws a FormatException with a descriptive error if the preset or command is not found.

Implementation

Map<String, dynamic> findPreset(
  YamlMap config,
  List<String> commandPath,
  String presetName,
) {
  final commandLabel = commandPath.join(' ');

  // Navigate to `commands`
  final commands = config['commands'];
  if (commands is! YamlMap) {
    throw const FormatException(
      "buggy.yaml is missing the 'commands' key.",
    );
  }

  // Walk the nested command path
  dynamic current = commands;
  for (final segment in commandPath) {
    if (current is! YamlMap || current[segment] == null) {
      throw FormatException(
        "No configuration found for command '$commandLabel' in buggy.yaml.",
      );
    }
    current = current[segment];
  }

  if (current is! YamlMap) {
    throw FormatException(
      "No configuration found for command '$commandLabel' in buggy.yaml.",
    );
  }

  // Find presets list
  final presets = current['presets'];
  if (presets is! YamlList) {
    throw FormatException(
      "No presets defined for command '$commandLabel' in buggy.yaml.",
    );
  }

  // Search for the named preset
  final availableNames = <String>[];
  for (final preset in presets) {
    if (preset is! YamlMap) continue;
    final name = preset['name'];
    if (name is String) {
      availableNames.add(name);
      if (name == presetName) {
        final result = <String, dynamic>{};
        for (final key in preset.keys) {
          if (key == 'name') continue;
          final value = preset[key];
          if (value is YamlList) {
            result[key as String] = value.toList();
          } else {
            result[key as String] = value;
          }
        }
        return result;
      }
    }
  }

  throw FormatException(
    "Preset '$presetName' not found for command '$commandLabel'. "
    'Available presets: ${availableNames.join(', ')}',
  );
}