在 dart 中使用 source_gen 为一系列已解析文件生成一个文件

2023-12-21

我有一个创建迷你反射系统所需的模型列表。
我分析了可序列化包并了解如何为每个文件创建一个生成的文件,但是,我找不到如何为大量文件创建一个文件。

那么,如何使用 source_gen 为一系列文件动态生成一个文件呢?

Example:
Files
用户.dart
类别.dart

生成:
info.dart(包含来自user.dart和category.dart的信息)


在 Gitter 人员的帮助下找到了如何做到这一点。
您必须有一个文件(即使是空的)才能调用生成器。在我的示例中,它是 lib/batch.dart。

来源生成:^0.5.8

这是工作代码:

工具/build.dart

import 'package:build_runner/build_runner.dart';
import 'package:raoni_global/phase.dart';

main() async {
  PhaseGroup pg = new PhaseGroup()
    ..addPhase(batchModelablePhase(const ['lib/batch.dart']));

  await build(pg,
      deleteFilesByDefault: true);
}

阶段:

batchModelablePhase([Iterable<String> globs =
const ['bin/**.dart', 'web/**.dart', 'lib/**.dart']]) {
  return new Phase()
    ..addAction(
        new GeneratorBuilder(const
        [const BatchGenerator()], isStandalone: true
        ),
        new InputSet(new PackageGraph.forThisPackage().root.name, globs));
}

发电机:

import 'dart:async';

import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'package:glob/glob.dart';
import 'package:build_runner/build_runner.dart';

class BatchGenerator extends Generator {
  final String path;

  const BatchGenerator({this.path: 'lib/models/*.dart'});

  @override
  Future<String> generate(Element element, BuildStep buildStep) async {
    // this makes sure we parse one time only
    if (element is! LibraryElement)
      return null;

    String libraryName = 'raoni_global', filePath = 'lib/src/model.dart';
    String className = 'Modelable';

    // find the files at the path designed
    var l = buildStep.findAssets(new Glob(path));

    // get the type of annotation that we will use to search classes
    var resolver = await buildStep.resolver;
    var assetWithAnnotationClass = new AssetId(libraryName, filePath);
    var annotationLibrary = resolver.getLibrary(assetWithAnnotationClass);
    var exposed = annotationLibrary.getType(className).type;

    // the caller library' name
    String libName = new PackageGraph.forThisPackage().root.name;

    await Future.forEach(l.toList(), (AssetId aid) async {
      LibraryElement lib;

      try {
        lib = resolver.getLibrary(aid);
      } catch (e) {}

      if (lib != null && Utils.isNotEmpty(lib.name)) {
        // all objects within the file
        lib.units.forEach((CompilationUnitElement unit) {
          // only the types, not methods
          unit.types.forEach((ClassElement el) {
            // only the ones annotated
            if (el.metadata.any((ElementAnnotation ea) =>
            ea.computeConstantValue().type == exposed)) {
              // use it
            }
          });
        });
      }
    });

    return '''
       $libName
    ''';
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 dart 中使用 source_gen 为一系列已解析文件生成一个文件 的相关文章

随机推荐