findUsedKeysInContent function

Set<String> findUsedKeysInContent(
  1. String content,
  2. Set<String> allKeys
)

Finds localization keys used in Dart source content.

Supports single-line and multi-line usage patterns (e.g., accessor and key split across lines).

Implementation

Set<String> findUsedKeysInContent(String content, Set<String> allKeys) {
  if (allKeys.isEmpty) return <String>{};

  final String keysPattern = allKeys.map(RegExp.escape).join('|');

  // Quick pre-check: skip if content doesn't contain any key substring
  if (!content.contains(RegExp(keysPattern))) return <String>{};

  final RegExp regex = RegExp(
    // ignore: prefer_interpolation_to_compose_strings
    r'(?:' // Start non-capturing group for all possible access patterns
        r'(?:[a-zA-Z0-9_]+(?:\?)?\s*\.\s*)+' // e.g., `_appLocalizations.`, `l10n?.` (null-aware)
        r'|'
        r'[a-zA-Z0-9_]+\.of\(\s*(?:context|Get\.context\!?|AppNavigation\.context|this\.context|BuildContext\s+\w+)[\s,]*\)\!?\s*\.\s*' // `of(context)!.key`, `of(Get.context!,\n)!.key`
        r'|'
        r'[A-Za-z_]\w*\.[A-Za-z_]\w*\(\s*\)\s*\.\s*' // `SomeClass.method().key`
        r')'
        r'\s*' // Allow whitespace/newlines between accessor and key (fixes multi-line usage)
        r'(' +
    keysPattern +
    r')(?:\b|\s*\()', // Key as getter or method (e.g., `key` or `key(param)`)
    multiLine: true,
    dotAll: true, // Makes `.` match newlines (crucial for multi-line cases)
  );

  final Set<String> usedKeys = <String>{};
  for (final Match match in regex.allMatches(content)) {
    usedKeys.add(match.group(1)!); // Capture only the key
  }
  return usedKeys;
}