packageImportsUnder function

Map<String, List<String>> packageImportsUnder(
  1. String directory
)

Every package: import appearing anywhere under directory, mapped to the files that carry it.

Unlike externalImportsOf this walks files rather than the reachable closure — which is the stricter question, and the one that matters for a rule about what a package may touch: a barrel walk only proves that nothing exported today reaches the banned dependency, and says nothing about a file that is clean by accident because no one has exported it yet.

Implementation

Map<String, List<String>> packageImportsUnder(String directory) {
  final byPackage = <String, List<String>>{};
  final dir = Directory(directory);
  if (!dir.existsSync()) return byPackage;
  for (final entity in dir.listSync(recursive: true).whereType<File>()) {
    if (!entity.path.endsWith('.dart')) continue;
    for (final line in const LineSplitter().convert(
      entity.readAsStringSync(),
    )) {
      final match = directiveLinePattern.firstMatch(line);
      if (match == null) continue;
      final uri = match.group(1)!;
      if (!uri.startsWith('package:')) continue;
      byPackage.putIfAbsent(packageOf(uri), () => []).add(entity.path);
    }
  }
  return byPackage;
}