手动运行OpenRewrite配方

本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转载自夜明的孤行灯

本文链接地址: https://www.huangyunkun.com/2024/01/16/run-openrewrite-recipes-by-code/



OpenRewrite提供了Maven插件,可以方便运行在Maven管理的项目上,如果需要在其他环境运行,比如自定义的CLI等,就需要手动运行了。

概念

先明确下OpenRewrite相关的几个概念

配方:需要执行的变更,配方可以是内置的,也可以是第三方社区的,更进一步是自定义的。配方的指定主要通过全名完成,比如org.openrewrite.java.OrderImports

目标项目:要执行变更的项目,一般通过路径表示,也可以通过是远程文件,也可以通过扩展SourceFile适配更多情况

运行环境:配方执行的基础,提供配方运行、消息处理等,可以扩展ExecutionContext,也可以使用InMemoryExecutionContext

环境:用于支持运行环境,提供配方管理、资源加载器等,关键类:Environment

运行流程

  • 一般按照如下流程进行:
  • 初始化环境
  • 激活配方并验证配方
  • 初始化运行环境
  • 解析目标项目,获取源文件集合
  • 运行配方获取变更
  • 根据变更修改项目

关键代码

//运行环境准备
Environment env = Environment.builder().scanRuntimeClasspath().scanUserHome().build();
ExecutionContext executionContext = initExecutionContext();
MavenParser.Builder mavenParserBuilder = initMavenRelatedConfig(executionContext);

//指定配方
Recipe recipe = env.activateRecipes("org.openrewrite.java.RandomizeId");
Collection<Validated<Object>> validateds = recipe.validateAll();
//验证配方
 for (Validated<Object> validated : validateds) {
      if (validated instanceof Validated.Invalid) {
        logger.error("recipe validate failed: {}", validated);
         return;
     }
}
LargeSourceSet largeSourceSet = new InMemoryLargeSourceSet(sourceFiles);


//运行配方
RecipeRun run = recipe.run(largeSourceSet, executionContext);
logger.info("Run:{}", run);

for (Result result : run.getChangeset().getAllResults()) {
     logger.info("Result:{}", result);
}

//写入变更,目前只处理了变更
for (Result result : run.getChangeset().getAllResults()) {
     if (result.getBefore() != null && result.getAfter() != null) {
         try (final BufferedWriter sourceFileWriter = Files.newBufferedWriter(result.getAfter().getSourcePath())) {
                    sourceFileWriter.write(result.getAfter().printAll());
         }
     }
}



本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转载自夜明的孤行灯

本文链接地址: https://www.huangyunkun.com/2024/01/16/run-openrewrite-recipes-by-code/

发表评论