generateForAnnotatedElement method

  1. @override
dynamic generateForAnnotatedElement(
  1. Element element,
  2. ConstantReader annotation,
  3. BuildStep buildStep
)

This method is called for each source that has @microPackage annotation. The goal is to add a part file to the root injection.config.dart file This part file will call the registration of micro module dependencies. It searches for micro.json files, which are the work of InjectableMicroPackagesScout This generator will fail if a micro_packages.json file is not found in the lib/ folder TODO: this script only works if injection.dart has the imports for the modules... this doesn't make much sense.

Implementation

@override
generateForAnnotatedElement(
    Element element, ConstantReader annotation, BuildStep buildStep) async {
  log.fine("generateForAnnotatedElement");

  var microPackageNames = await _getMicroPackageConfig(path.join("lib","micro_packages.json"), buildStep);
  var generatedCode = '';

  for (var package in microPackageNames) {
    log.fine('generating for package $package');
    generatedCode += " ${package.moduleClassName}.${package.methodName}(getIt); \n";
  }

  var microPackagesImportDirectives = microPackageNames
      .map((microPackageNames) =>
          Directive.import(microPackageNames.moduleFileLocation!))
      .toSet();

  final clazz = Library(
    (lib) => lib
      ..directives.addAll(microPackagesImportDirectives)
      ..body.add(
        Class((clazz) => clazz
          ..name = 'MicroPackagesConfig'
          ..methods.addAll([
            Method((m) => m
              ..name = 'registerMicroModules'
              ..static = true
              //..docs.add("This method calls registerModuleDependencies in known micro packages")
              ..requiredParameters.addAll([
                Parameter((p) => p
                  ..type = refer('GetIt', 'package:get_it/get_it.dart')
                  ..name = 'getIt')
              ])
              ..body = Code(generatedCode))
          ])),
      ),
  );

  final emitter = DartEmitter(allocator: Allocator.simplePrefixing());
  return DartFormatter().format('${clazz.accept(emitter)}');
}