model_import_generator.dart 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import 'package:analyzer/dart/element/element.dart';
  2. import 'package:router_gen/model/router.dart';
  3. import 'package:router_gen/util/utils.dart';
  4. import 'package:source_gen/source_gen.dart';
  5. /// find class path from argument
  6. class ModelImportGenerator extends Generator {
  7. static List<String> modelImports = [];
  8. const ModelImportGenerator();
  9. @override
  10. Future<String> generate(LibraryReader library, _) async {
  11. if (library.classes.isNotEmpty) {
  12. Map routerMap = router.routerMap;
  13. for (String key in routerMap.keys) {
  14. Page page = routerMap[key];
  15. for (Argument argument in page.arguments) {
  16. if (argument.isImported) continue;
  17. if (_isSpeciousType(argument.type)) {
  18. // 处理type
  19. List<String> type = getType(argument.type);
  20. type.removeWhere((element) => _isSpeciousType(element) == false);
  21. if (type.length == 0) {
  22. continue;
  23. }
  24. // 比较class name
  25. bool isInThisClass = false;
  26. for (ClassElement element in library.classes) {
  27. if (type.contains(element.displayName)) {
  28. isInThisClass = true;
  29. break;
  30. }
  31. }
  32. // 添加import
  33. if (isInThisClass) {
  34. argument.isImported = true;
  35. router.imports.add(getImportStr(_));
  36. }
  37. } else {
  38. argument.isImported = true;
  39. }
  40. }
  41. }
  42. }
  43. return null;
  44. }
  45. bool _isSpeciousType(String type) {
  46. if (type == "int" ||
  47. type == "double" ||
  48. type == "num" ||
  49. type == "Runes" ||
  50. type == "String" ||
  51. type == "bool" ||
  52. type == "dynamic") {
  53. return false;
  54. }
  55. return true;
  56. }
  57. /// Notice: not contain all situation
  58. /// 递归获取type
  59. List<String> getType(String type) {
  60. if (type.startsWith("List<") == false && type.startsWith("Map<") == false) {
  61. return [type];
  62. }
  63. List<String> results = [];
  64. if(type.startsWith("List<")) {
  65. String result = type.substring(type.indexOf("List<") + 5, type.lastIndexOf(">"));
  66. results.addAll(getType(result.trim()));
  67. }
  68. if (type.startsWith("Map<")) {
  69. List<String> splits = type.substring(type.indexOf("Map<") + 4, type.lastIndexOf(">")).split(",");
  70. results.addAll(getType(splits[0].trim()));
  71. results.addAll(getType(splits[1].trim()));
  72. }
  73. return results;
  74. }
  75. }