getImportSummary method

Future<Map<String, List<String>>> getImportSummary(
  1. String projectPath,
  2. String packageName
)

Build a map of import URI -> [file paths] for a given packageName.

This lets callers see which specific sub-libraries are imported and from where.

Implementation

Future<Map<String, List<String>>> getImportSummary(
  String projectPath,
  String packageName,
) async {
  final files = await findFilesImporting(projectPath, packageName);
  final summary = <String, List<String>>{};

  final importPattern = RegExp(
    r'''import\s+['"](package:''' +
        RegExp.escape(packageName) +
        r'''[^'"]*)['"]\s*;''',
  );

  for (final filePath in files) {
    try {
      final content = await File(filePath).readAsString();
      final matches = importPattern.allMatches(content);
      for (final match in matches) {
        final importUri = match.group(1)!;
        summary.putIfAbsent(importUri, () => []).add(filePath);
      }
    } catch (e) {
      Logger.debug('Could not read $filePath for import summary: $e');
    }
  }

  return summary;
}