Created
August 4, 2015 01:06
-
-
Save kasperpeulen/fe291b3a5254086cf49f to your computer and use it in GitHub Desktop.
get dart doc information
This file contains hidden or 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/analyzer.dart'; | |
| import 'package:analyzer/src/string_source.dart'; | |
| import 'package:analyzer/src/generated/element.dart'; | |
| import 'package:analyzer/src/generated/engine.dart'; | |
| import 'package:analyzer/src/generated/sdk_io.dart'; | |
| import 'package:analyzer/src/generated/source.dart'; | |
| main() { | |
| String doc = dartDoc("main() => print('hello world');", 10); | |
| print(doc); | |
| } | |
| String dartDoc(String dartString, int offset) { | |
| var sdk = DirectoryBasedDartSdk.defaultSdk; | |
| AnalysisContext context = AnalysisEngine.instance.createAnalysisContext() | |
| ..sourceFactory = new SourceFactory([new DartUriResolver(sdk)]); | |
| StringSource source = new StringSource(dartString, "main.dart"); | |
| LibraryElement library = context.computeLibraryElement(source); | |
| CompilationUnit unit = context.resolveCompilationUnit(source, library); | |
| AstNode node = new NodeLocator(offset).searchWithin(unit); | |
| Element element = ElementLocator.locateWithOffset(node, offset); | |
| String rawDartDoc = element?.computeDocumentationComment(); | |
| return prettifyDartDoc(rawDartDoc); | |
| } | |
| String prettifyDartDoc(rawDartDoc) => rawDartDoc | |
| ?.split('\n') | |
| ?.map((s) => s.trim().replaceAll(commentChars, '').isEmpty | |
| ? '' | |
| : s.trim().replaceAll(commentChars, '').substring(1)) | |
| ?.join('\n'); | |
| RegExp commentChars = new RegExp(r'[\&*|\*/|\/\*\*|///]'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment