sortImports function
Read the given source code, and return the new contents after sorting the imports.
Implementation
String sortImports(String contents) {
final ParseStringResult parseResult = parseString(
content: contents,
featureSet: FeatureSet.fromEnableFlags2(
sdkLanguageVersion: FlutterInformation.instance.getDartSdkVersion(),
flags: <String>[],
),
);
final List<AnalysisError> errors = <AnalysisError>[];
final _ImportOrganizer organizer =
_ImportOrganizer(contents, parseResult.unit, errors);
final List<_SourceEdit> edits = organizer.organize();
// Sort edits in reverse order
edits.sort((_SourceEdit a, _SourceEdit b) {
return b.offset.compareTo(a.offset);
});
// Apply edits
for (final _SourceEdit edit in edits) {
contents = contents.replaceRange(edit.offset, edit.end, edit.replacement);
}
return contents;
}