Last active
June 5, 2021 20:42
-
-
Save simolus3/efc5f23f69a57ceae9004231e379f80f to your computer and use it in GitHub Desktop.
Analyze where dart:html came from
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:analyzer/dart/analysis/analysis_context_collection.dart'; | |
import 'package:analyzer/dart/analysis/results.dart'; | |
import 'package:analyzer/dart/element/element.dart'; | |
import 'package:path/path.dart'; | |
// Usage: dart tool/why_imported.dart path/to/entrypoint.dart | |
void main(List<String> args) async { | |
final collection = AnalysisContextCollection(includedPaths: [current]); | |
final entrypoint = args.single; | |
final session = collection.contextFor(absolute(entrypoint)).currentSession; | |
final lib = await session.getResolvedLibrary2(absolute(entrypoint)); | |
if (lib is! ResolvedLibraryResult) { | |
print('Could not analyze entrypoint'); | |
return; | |
} | |
final previous = <LibraryElement, LibraryElement>{}; | |
final pending = <LibraryElement>[lib.element!]; | |
LibraryElement? culprit; | |
while (pending.isNotEmpty && culprit == null) { | |
final now = pending.removeLast(); | |
for (final import | |
in now.importedLibraries.followedBy(now.exportedLibraries)) { | |
if (import.name?.contains('dart.dom') ?? false) { | |
culprit = now; | |
break; | |
} else if (!previous.containsKey(import) && !pending.contains(import)) { | |
previous[import] = now; | |
pending.add(import); | |
} | |
} | |
} | |
if (culprit == null) { | |
print('No dart:html import found'); | |
return; | |
} | |
final description = | |
StringBuffer('dart:html was imported by ${culprit.source.fullName}\n'); | |
do { | |
culprit = previous[culprit]; | |
if (culprit != null) { | |
description.writeln(' which was imported by ${culprit.source.fullName}'); | |
} | |
} while (culprit != null); | |
print(description); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment