spotless-maven-plugin配合p3c-eclipse-formatter使用

最近在弄公司的框架,其中有一部分内容是规范治理。规范治理的工具在之前的文章中有介绍。

其中需要关注的一个问题就是如何配置file选项,特别是在项目是多模块的情况下,引用公司框架时。

查看源码

spotless的源码分层很清晰,可以轻松找到对应的源码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Eclipse implements FormatterStepFactory {
@Parameter
private String file;

@Parameter
private String version;

@Override
public FormatterStep newFormatterStep(FormatterStepConfig stepConfig) {
EquoBasedStepBuilder eclipseConfig = EclipseJdtFormatterStep.createBuilder(stepConfig.getProvisioner());
eclipseConfig.setVersion(version == null ? EclipseJdtFormatterStep.defaultVersion() : version);
if (null != file) {
// 这里加载文件
File settingsFile = stepConfig.getFileLocator().locateFile(file);
eclipseConfig.setPreferences(Arrays.asList(settingsFile));
}
return eclipseConfig.build();
}
}

找到locateFile的具体实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public File locateFile(String path) {
if (isNullOrEmpty(path)) {
return null;
}

// 加载本地文件
File localFile = new File(path);
if (localFile.exists() && localFile.isFile()) {
return localFile;
}

String outputFile = tmpOutputFileName(path);
try {
// 加载外部文件
return resourceManager.getResourceAsFile(path, outputFile);
} catch (ResourceNotFoundException e) {
throw new RuntimeException("Unable to locate file with path: " + path, e);
} catch (FileResourceCreationException e) {
throw new RuntimeException("Unable to create temporary file '" + outputFile + "' in the output directory",
e);
}
}

代码表明了可以加载本地和非本地文件,并且非常清晰易懂。

1
2
3
4
<!-- 本地文件,每个项目都可以访问到,基本上不太会用 -->
<file>
/mnt/p3c-eclipse-formatter.xml
</file>

我们看到非本地文件是通过resourceManager.getResourceAsFile加载的,resourceManager的全路径为org.codehaus.plexus.resource.ResourceManager。

codehaus-plexus / plexus-resources

Codehaus Plexus 是一组开源的Java组件,提供了大量的通用工具和框架,可以帮助您构建可扩展的、健壮的和高性能的Java应用程序。

Plexus-resources是Codehaus Plexus中的一个插件,用于在Maven中对项目资源文件进行处理。

Plexus-resources插件提供了一种简便的机制,以便将非Java源文件复制到输出目录中,从而构成类似于Java包的目录结构。它还支持配置文件过滤,根据需要在目标文件中替换Maven属性占位符。

可以加载哪些文件

Plexus-resources插件可以用来加载任何类型的资源文件,包括但不限于以下类型:

  1. Java源代码文件
  2. 配置文件
  3. 图像文件或其他多媒体资源
  4. 静态网页/模板文件
  5. 读写文件
  6. 数据集/文本文件
  7. 属性文件
  8. XML文件
  9. 工具脚本/批处理文件
  10. 样式表文件等等

此外,Plexus-resources插件还可以配置从源目录中复制哪些文件、排除哪些文件、以及如何过滤源文件。这使得它可以轻松地集成到几乎任何类型的Maven项目中,并为项目中的任何类型资源文件提供支持。

加载文件

加载jar包中的文件

1
2
3
<file>
jar:${basedir}/lib/mylib.jar!/config
</file>

加载私仓中jar包中的文件

1
2
3
<file>
jar:http://192.168.0.2:8080/repository/maven-public/com/xx/xx/xx/2.0.0-SNAPSHOT/xx-2.0.0-20220817.040829-2.jar!/p3c-eclipse-formatter.xml
</file>

加载url

1
2
3
<file>
https://xx.oss-cn-shanghai.aliyuncs.com/ecf/p3c-eclipse-formatter.xml
</file>

最佳实践

因为eclipse code formatter文件一般不会改动巨大,选用url是最好的方式。

如果文件有变化,可以通过cicd将文件上传至服务器,也可以手动上传。