Dart Transformer无法覆盖资产

时间:2016-02-14 22:50:19

标签: dart dart-pub

我编写了一个AggregateTransformer,它应该用更新版本覆盖main.dart文件(更改导入)。

Asset mainAsset = await _getFileAsset(transform, "main.dart");
Asset updatedMainAsset = await _replaceDefaultImport(mainAsset, transform.package, "default.dart", newLibFileName);

//overwrite mainAsset because mainAsset and updatedMainAsset have the same id
transform.addOutput(updatedMainAsset);

(在添加新版本之前首先删除资产并不会改变任何内容:)

transform.consumePrimary(mainAsset.id);
transform.addOutput(updatedMainAsset);

但更新版本消失得无影无踪。尝试通过id检索它会产生原始内容:

Asset updatedMainAssetRetrieved = await transform.getInput(updatedMainAsset.id);

变换器输出mainAsset和updatedMainAsset的内容,以便您可以检查updatedMainAsset的内容是否确实已更新。通过调用 pub run main.dart 来调用转换器。

完整的代码/伪代码如下所示:

class ReplacePackageTransformer extends AggregateTransformer {
  ReplacePackageTransformer.asPlugin();

  @override
  String classifyPrimary(AssetId id) => id.toString().endsWith(".dart") ? "dart-files" : null;

  @override
  apply(AggregateTransform transform) {
    //capture the whole execution to allow better stacktraces if an error occurs
    Chain.capture(() async {
      //create a file lib/replacement.dart that defines the same method as lib/default.dart
      final newLibFileName = "replacement.dart";
      final newLibAsset = _createReplacementAsset(...);
      //add this new asset
      transform.addOutput(newLibAsset);

      //rewrite main.dart to import replacement.dart instead of default.dart. To that end:
      //1) retrieve the asset for main.dart
      Asset mainAsset = await _getFileAsset(transform, "main.dart");
      //2) create a new asset with the same id as mainAsset but with updated content
      Asset updatedMainAsset = await _replaceDefaultImport(mainAsset, ...);
      //3) adding this asset should overwrite/replace the original main.dart-asset because they use the same id
      transform.addOutput(updatedMainAsset);
    });
  }

  //helper methods ...
}

您可以找到整个变压器(以及项目的其余部分)here

更新/溶液

Dennis Kaselow是对的!我的变压器的apply-method必须返回一个Future(以便后续的变压器可以等待它完成)!在调用Chain.capture之前添加 return 就足够了(因为我捕获的回调有一个异步体,因此返回一个捕获将转发/返回的Future。)

如此改变

apply(AggregateTransform transform) {
  Chain.capture(() async {...});
  //no return statement so void is returned
}

Future apply(AggregateTransform transform) {
  return Chain.capture(() async {...});
  //() async {...} returns a Future that Chain.capture and apply forward/return
}

解决了我的问题!

1 个答案:

答案 0 :(得分:2)

解决方案非常简单:只需在Handlers前添加return

Chain.capture的dartdoc说:

  

如果这是异步工作,它应该返回一个完成后完成的[Future]。

如果在转换后访问输入,则输入仍将是原始输入。您也无需致电apply