Skip to content

Instantly share code, notes, and snippets.

@kasperpeulen
Last active August 29, 2015 14:25
Show Gist options
  • Save kasperpeulen/d086078ed00429d5a335 to your computer and use it in GitHub Desktop.
Save kasperpeulen/d086078ed00429d5a335 to your computer and use it in GitHub Desktop.
How to extract the used libraries in a dart file using the `analyzer` package.

#analyzer:analyzer example

How to extract the used libraries in a dart file using the analyzer package.

Main library: analyzer:analyzer
Main elements: parseCompilationUnit CompilationUnit.directives ImportDirective.uri
Gist: https://gist.github.com/kasperpeulen/d086078ed00429d5a335
Tags: #server

import 'package:analyzer/analyzer.dart';
const dartFile = '''
import 'dart:collection';
import 'dart:io' as io;
import 'package:path/path.dart' as path;
import 'package:analyzer/src/analyzer.dart';
void main() {}
''';
main() {
List<String> libraries = findLibraries(dartFile);
// prints [dart:collection, dart:io, path:path, analyzer:src.analyzer]
print(libraries);
}
List<String> findLibraries(String dartFile) {
// Parse the dart string
CompilationUnit compilationUnit = parseCompilationUnit(dartFile);
// directive ::= [ExportDirective] | [ImportDirective] | [LibraryDirective] |
// [PartDirective] | [PartOfDirective]
List<Directive> directives = compilationUnit.directives;
// Only retain the imports.
directives.retainWhere((directive) => directive is ImportDirective);
// Convert the ImportDirective object to a good looking string.
List<String> libraries = directives.map(_beautifyImportDirective).toList();
return libraries;
}
String _beautifyImportDirective(ImportDirective import) {
String uri = import.uri.stringValue;
if (uri.startsWith('dart'))
return uri;
if (uri.startsWith('package:'))
return uri
.replaceAll('package:', '')
.replaceFirst('/', ':')
.replaceAll('/', '.')
.replaceAll('.dart', '');
if (uri.startsWith('packages/'))
return uri
.replaceAll('packages/', '')
.replaceFirst('/', ':')
.replaceAll('/', '.')
.replaceAll('.dart', '');
throw 'Oh noes! I could not extract the library from $uri... My bad!';
}
name: analyzer.analyzer_parseCompilationUnit_CompilationUnit.directives_ImportDirective.uri_'server'
description: |
How to extract the used libraries in a dart file using the `analyzer` package.
homepage: https://gist.github.com/kasperpeulen/d086078ed00429d5a335
homepage: https://gist.github.com/kasperpeulen/d086078ed00429d5a335
environment:
sdk: '>=1.0.0 <2.0.0'
dependencies:
analyzer: '>=0.25.2 <0.26.0'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment