formatCommandListing function

String formatCommandListing(
  1. Iterable<CommandListingEntry> entries, {
  2. required String namespaceSeparator,
  3. String styleNamespace(
    1. String text
    )?,
  4. String styleCommand(
    1. String text
    )?,
})

Formats a list of commands for display, grouping by namespace.

Commands are grouped by their namespace prefix (e.g., ui:task belongs to the ui namespace). Ungrouped commands appear first.

final output = formatCommandListing(
  entries,
  namespaceSeparator: ':',
  styleNamespace: style.heading,
  styleCommand: style.command,
);

Implementation

String formatCommandListing(
  Iterable<CommandListingEntry> entries, {
  required String namespaceSeparator,
  String Function(String text)? styleNamespace,
  String Function(String text)? styleCommand,
}) {
  final list = entries.toList(growable: false);
  if (list.isEmpty) return '';

  final unnamed = <CommandListingEntry>[];
  final grouped = <String, List<CommandListingEntry>>{};

  for (final entry in list) {
    final ns = _namespaceFor(entry.name, namespaceSeparator);
    if (ns == null) {
      unnamed.add(entry);
      continue;
    }
    grouped.putIfAbsent(ns, () => []).add(entry);
  }

  unnamed.sort((a, b) => a.name.compareTo(b.name));
  for (final group in grouped.values) {
    group.sort((a, b) => a.name.compareTo(b.name));
  }

  final maxName = list
      .map((e) => e.name.length)
      .fold<int>(0, (m, v) => v > m ? v : m);

  final buffer = StringBuffer();

  for (final entry in unnamed) {
    buffer.writeln(
      _formatCommandLine(entry, nameWidth: maxName, styleCommand: styleCommand),
    );
  }

  final namespaces = grouped.keys.toList()..sort();
  if (unnamed.isNotEmpty && namespaces.isNotEmpty) {
    buffer.writeln();
  }
  for (final ns in namespaces) {
    buffer.writeln(styleNamespace == null ? ns : styleNamespace(ns));
    for (final entry in grouped[ns]!) {
      buffer.writeln(
        _formatCommandLine(
          entry,
          nameWidth: maxName,
          styleCommand: styleCommand,
        ),
      );
    }
    if (ns != namespaces.last) {
      buffer.writeln();
    }
  }

  return buffer.toString().trimRight();
}