Yeoman Generator用于动态添加代码

时间:2017-04-14 10:10:19

标签: android yeoman yeoman-generator

我正在尝试为Android构建一个Yeoman项目生成器,它可以从用户获取参数并相应地更新已存在的文件。就像它可以将一些样板代码放入文件中或在运行时在build.gradle等中添加依赖项。

例如 我提示用户是否要为Fabric添加库依赖项,如果他按yes然后是该库的依赖项

compile('com.crashlytics.sdk.android:crashlytics:2.6.6@aar') { transitive = true; }

应该在build.gradle中添加,并且应该添加代码需要在必要的文件中设置这个库,比如Application类onCreate方法应该包含

Fabric.with(this, new Crashlytics());

和Android.Manifest应包含

<meta-data android:name="io.fabric.ApiKey" android:value="your key">

实现这一目标的最佳方法是什么?

由于

1 个答案:

答案 0 :(得分:1)

理想情况下,您希望从源文件中解析和修改AST。但我不知道你是否会为java代码找到AST解析器(对于XML代码,它应该很容易)。

const source = this.fs.read(this.destinationPath('file-to-modify.xml'));
const manifest = parseXML(source); // any XML parser will work here

// Here you write the code to modify the XML source

this.fs.write(
  this.destinationPath('file-to-modify.xml'),
  serializeXML(manifest) // with whichever XML serializer you want to use
);

对于Java代码,如果没有正确的AST解析器,您可以始终依赖正则表达式以与xml示例类似的方式在代码字符串中注入新行。

相关问题