sortPubspec function

String sortPubspec(
  1. String content
)

Sorts pubspec.yaml content into the standard key order and sorts the packages inside dependency sections alphabetically.

The sorter works on the source text: it finds where each top-level key and each dependency entry starts from the YAML node spans, then reorders whole blocks of lines. Every line is copied verbatim, so comments, quoting, block scalars, anchors, and null values survive. Only blank lines between top-level groups and between dependency entries change.

Returns content unchanged when it is empty, is not valid YAML, its root is not a block mapping, or the sorted text would not parse to the same data.

Implementation

String sortPubspec(String content) {
  final usesCrlf = content.contains('\r\n');
  final text = usesCrlf ? content.replaceAll('\r\n', '\n') : content;
  if (text.trim().isEmpty || text.contains('\r')) {
    return content;
  }

  final root = _parseBlockMap(text);
  if (root == null) {
    return content;
  }

  // Sorting dependency entries can move an alias above its anchor. When the
  // result does not parse to the same data, retry with only the top-level
  // keys reordered, and give up if that fails too.
  for (final sortDependencies in [true, false]) {
    final sorted = _sortText(text, root, sortDependencies: sortDependencies);
    if (sorted == null) {
      continue;
    }
    if (sorted == text) {
      return content;
    }
    if (_isSafeRewrite(text, root, sorted)) {
      return usesCrlf ? sorted.replaceAll('\n', '\r\n') : sorted;
    }
  }
  return content;
}