[英]Configure Gradle Plugin inside Gradle plugin
我想創建一個自定義 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
中手動完成。 但是在這種情況下,其他應用該插件的項目將不會默認定義此配置(我測試過)。
我設法用ChecktyleExtension
配置了checkstyle
插件。
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
會在當前項目目錄而不是插件目錄中搜索它。 有可能克服這個問題嗎? 我不希望該插件的用戶將任何其他文件放入他們的項目中。
我將配置文件放入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)
Java 由於某種原因無法從jar
存檔中讀取文件。 有什么方法可以克服這個錯誤?
您需要將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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.