markCatalogDependencies function

String markCatalogDependencies(
  1. String pubspec,
  2. Set<String> managed
)

Adds catalogMarker to every block-style dependency entry whose package is in managed, and removes it from the others. An existing inline comment on a managed entry is replaced by the marker.

Implementation

String markCatalogDependencies(String pubspec, Set<String> managed) {
  final YamlNode document;
  try {
    document = loadYamlNode(pubspec);
  } on YamlException {
    return pubspec;
  }
  if (document is! YamlMap) {
    return pubspec;
  }

  final lines = pubspec.split('\n');
  for (final section in const [
    'dependencies',
    'dev_dependencies',
    'dependency_overrides',
  ]) {
    final node = document.nodes[section];
    if (node is! YamlMap || node.style == CollectionStyle.FLOW) {
      continue;
    }
    for (final key in node.nodes.keys.whereType<YamlScalar>()) {
      final name = key.value;
      if (name is! String) {
        continue;
      }
      final lineIndex = key.span.start.line;
      final line = lines[lineIndex];
      final comment = inlineCommentStart(line);
      final withoutComment = comment == null
          ? line.trimRight()
          : line.substring(0, comment).trimRight();
      final hasMarker =
          comment != null && line.substring(comment).trim() == catalogMarker;

      if (managed.contains(name)) {
        lines[lineIndex] = '$withoutComment $catalogMarker';
      } else if (hasMarker) {
        lines[lineIndex] = withoutComment;
      }
    }
  }
  return lines.join('\n');
}