model_import_generator.dart 2.4 KB

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