preserve static method

String preserve(
  1. String text,
  2. CompactionPolicy policy
)

Marks identifiers in text for preservation based on the given policy.

Returns text with matched sections wrapped in <preserve>...</preserve>.

Implementation

static String preserve(String text, CompactionPolicy policy) {
  if (text.isEmpty) return text;

  final patterns = <RegExp>[];

  switch (policy) {
    case CompactionPolicy.strict:
      patterns.addAll([_filePathRegex, _uuidRegex]);
      break;
    case CompactionPolicy.lenient:
    case CompactionPolicy.custom:
      patterns.addAll([_filePathRegex, _toolNameRegex, _uuidRegex, _urlRegex]);
      break;
  }

  var result = text;
  for (final pattern in patterns) {
    result = result.replaceAllMapped(pattern, (match) {
      final matched = match.group(0)!;
      // Avoid double-wrapping.
      if (_isAlreadyPreserved(result, match.start)) return matched;
      return '<preserve>$matched</preserve>';
    });
  }

  return result;
}