| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- import 'package:analyzer/dart/element/element.dart';
- import 'package:router_gen/model/router.dart';
- import 'package:router_gen/util/utils.dart';
- import 'package:source_gen/source_gen.dart';
- /// find class path from argument
- class ModelImportGenerator extends Generator {
- const ModelImportGenerator();
- @override
- Future<String> generate(LibraryReader library, _) async {
- if (library.classes.isNotEmpty) {
- Map routerMap = router.routerMap;
- for (String key in routerMap.keys) {
- Page page = routerMap[key];
- for (Argument argument in page.arguments) {
- if (argument.isImported) continue;
- if (_isSpeciousType(argument.type)) {
- // 处理type
- List<String> type = getType(argument.type);
- type.removeWhere((element) => _isSpeciousType(element) == false);
- if (type.length == 0) {
- continue;
- }
- // 比较class name
- bool isInThisClass = false;
- for (ClassElement element in library.classes) {
- if (type.contains(element.displayName)) {
- isInThisClass = true;
- break;
- }
- }
- // 添加import
- if (isInThisClass) {
- argument.isImported = true;
- router.imports.add(getImportStr(_));
- }
- } else {
- argument.isImported = true;
- }
- }
- }
- }
- return null;
- }
- bool _isSpeciousType(String type) {
- if (type == "int" ||
- type == "double" ||
- type == "num" ||
- type == "Runes" ||
- type == "String" ||
- type == "bool" ||
- type == "dynamic") {
- return false;
- }
- return true;
- }
- /// Notice: not contain all situation
- /// 递归获取type
- List<String> getType(String type) {
- if (type.startsWith("List<") == false && type.startsWith("Map<") == false) {
- return [type];
- }
- List<String> results = [];
- if(type.startsWith("List<")) {
- String result = type.substring(type.indexOf("List<") + 5, type.lastIndexOf(">"));
- results.addAll(getType(result.trim()));
- }
- if (type.startsWith("Map<")) {
- List<String> splits = type.substring(type.indexOf("Map<") + 4, type.lastIndexOf(">")).split(",");
- results.addAll(getType(splits[0].trim()));
- results.addAll(getType(splits[1].trim()));
- }
- return results;
- }
- }
|