簡體   English   中英

Maven Enforcer:如何從 beanshell 規則訪問 maven 屬性

[英]Maven Enforcer: How to access maven properties from beanshell rule

我使用 maven-enforcer-plugin 成功創建了一個 evaluateBeanshell 規則,該規則掃描工作區中的文件以查找常見錯誤。

使用硬編碼路徑,規則可以正常工作。 當我想使用周圍 pom 中的 ${project.basedir} 變量時,腳本在我的 Windows 機器上中斷。

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>${maven-enforcer-plugin.version}</version>
<executions>
    <execution>
        <id>enforce-banned-dependencies</id>
        <inherited>true</inherited>
        <goals>
            <goal>enforce</goal>
        </goals>
        <configuration>
            <rules>
                <evaluateBeanshell>
                    <condition>
                        import scanner.MyScanner;
                        scanner = new MyScanner();

                        //hack to read root dir
                        //project.basedir  crashes beanshell with its backslashes
                        rootPath = new File("");
                        root = new File(rootPath.getAbsolutePath());
                        print("Scanning in: " + root);
                        print("${project.artifactId}"); // works fine
                        print("${project.basedir}");    // breaks the code
                        
                        scanner.loopThroughProjects(root);

                        return everythingIsFine;
                    </condition>
                </evaluateBeanshell>
            </rules>
            <fail>true</fail>
        </configuration>
    </execution>
</executions>                           

在調試 output 行中:

print("${project.basedir}");

被替換為:

print("D:\code\my-maven-project");

是否有另一個 maven 屬性帶有經過清理的斜杠,或者是否有另一種訪問 ${project.basedir} 的方法? 代碼示例中概述的 hack 是可行的,但我不喜歡強迫我發表評論的 hack。

您可以嘗試${project.baseUri}

參見https://maven.apache.org/ref/3.8.5/maven-model-builder/#Model_Interpolation

在我的 Windows 10 機器上,帶有 Java 8 和 Maven 3 pom.xml 中的以下測試屬性:

<test>${project.baseUri}</test>
<test2>${project.basedir}</test2>

成為'effective-pom'中的以下內容(通過Intellij IDEA maven插件)

<test>file:/D:/test/path/</test>
<test2>D:\test\path</test2>

這只是一個概念證明,用於顯示路徑分隔符更改,並作為 Java 字符串變得有效。

然后,您可以在 beanshell 腳本中將 URI 轉換為您需要的文件,如下所示:

uri = java.net.URI.create("${project.baseUri}");
root = new java.io.File(uri);

通過https://docs.oracle.com/javase/8/docs/api/java/io/File.html#File-java.net.URI-

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM