collectKeyStack function

List<ApiKeyCredential> collectKeyStack(
  1. Map<String, String> secrets,
  2. String baseName
)

Collects a key stack for baseName from secrets: the bare name first, then _2, _3, ... in numeric order. Returns an empty list when the base name is absent.

Implementation

List<ApiKeyCredential> collectKeyStack(
  Map<String, String> secrets,
  String baseName,
) {
  final suffixPattern = RegExp('^${RegExp.escape(baseName)}_(\\d+)\$');
  final numbered = <int, String>{};
  for (final entry in secrets.entries) {
    final match = suffixPattern.firstMatch(entry.key);
    if (match != null && entry.value.isNotEmpty) {
      numbered[int.parse(match[1]!)] = entry.value;
    }
  }
  final stack = <ApiKeyCredential>[];
  final base = secrets[baseName];
  if (base != null && base.isNotEmpty) {
    stack.add(ApiKeyCredential(baseName, base));
  }
  for (final index in numbered.keys.toList()..sort()) {
    stack.add(ApiKeyCredential('${baseName}_$index', numbered[index]!));
  }
  return stack;
}