我想創建一個自定義 Gradle 插件來封裝 Checkstyle 和 PMD 配置。因此,其他專案可以只應用一個自定義插件,而無需擔心任何額外的配置。
我應用checkstyle了插件。
plugins {
id 'java-gradle-plugin'
id 'checkstyle'
}
然后我將它應用到我的自定義插件中。
public class CustomPlugin implements Plugin<Project> {
public void apply(Project project) {
project.getPluginManager().apply(CheckstylePlugin.class);
}
}
當我嘗試構建專案時,出現錯誤。
Unable to find: config/checkstyle/checkstyle.xml
如何覆寫其他插件的屬性?例如,我想更改默認checkstyle.xml路徑。我可以build.gradle在插件專案本身內部手動完成。但在這種情況下,其他應用該插件的專案默認不會定義此配置(我測驗過)。
編輯1:
我設法checkstyle用ChecktyleExtension.
public class MetricCodingRulesGradlePluginPlugin implements Plugin<Project> {
public void apply(Project project) {
project.getPluginManager().apply("checkstyle");
project.getExtensions().configure(CheckstyleExtension.class, checkstyleExtension -> {
checkstyleExtension.setConfigFile(new File("style/checkstyle.xml"));
});
}
}
checkstyle.xml放在插件專案中。當我嘗試在任何其他專案中應用它時,checkstyle在當前專案目錄中搜索它,而不是插件的目錄。有可能克服這個問題嗎?我不希望該插件的用戶將任何其他檔案放入他們的專案中。
編輯2:
我將組態檔放入檔案resources夾并嘗試讀取內容。
public class MetricCodingRulesGradlePluginPlugin implements Plugin<Project> {
public void apply(Project project) {
project.getPluginManager().apply("checkstyle");
project.getExtensions().configure(CheckstyleExtension.class, checkstyleExtension -> {
URL url = getClass().getClassLoader().getResource("style/checkstyle.xml");
System.out.println("URL: " url);
try {
checkstyleExtension.setConfigFile(
Paths.get(url.toURI())
.toFile()
);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
});
}
}
當我將插件應用到另一個專案時,我收到以下錯誤:
URL: jar:file:/Users/user/.gradle/caches/jars-9/8f4176a8ae146bf601f1214b287eb805/my-plugin-0.0.1-SNAPSHOT.jar!/style/checkstyle.xml
Caused by: java.nio.file.FileSystemNotFoundException
at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171)
at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
jar由于某種原因,Java 無法從存檔中讀取檔案。有什么方法可以克服這個錯誤?
uj5u.com熱心網友回復:
您需要將其捆綁checkstyle.xml在插件的resources檔案夾中,因此當您發布它時,您始終可以從插件代碼中訪問它。
基本上,您需要將配置放在src/main/resources/checkstyle.xml插件下,然后像這樣訪問它:
URL resourceURL = getClass().getClassLoader().getResource("checkstyle.xml");
if (resourceURL != null) {
File resourceFile = File(resourceURL.getFile());
checkstyleExtension.setConfigFile(resourceFile);
}
.jar另請記住,如果您將插件作為checkstyle.xml. 大致:
File temp = File.createTempFile(".checkstyle", ".xml")
try (FileOutputStream out = new FileOutputStream(temp)) {
try (InputStream resourceStream = getClass().getClassLoader().getResourceAsStream("checkstyle.xml")) {
byte[] buffer = new byte[1024];
int bytes = resourceStream.read(buffer);
while (bytes >= 0) {
out.write(buffer, 0, bytes);
bytes = resourceStream.read(buffer);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/429722.html
上一篇:如何在Intellij中遠程除錯作為docker容器運行的java應用程式
下一篇:正則運算式匹配破折號后的所有文本
