如何在指定文件不存在时跳过Maven插件的执行?
如何在目标目录不存在时跳过build-helper-maven-plugin的执行?
当然有可行的办法!针对你用的build-helper-maven-plugin,我给你整理了几种实用的方案,帮你实现「目标目录不存在时跳过插件执行」的需求:
方案一:利用Maven Profile自动激活配置
Maven的Profile支持基于文件/目录是否存在来自动激活,我们可以把插件配置放在一个专属Profile里,只有当${customFolder}目录存在时才触发执行。
配置示例:
<profiles> <profile> <id>has-custom-test-sources</id> <activation> <file> <exists>${customFolder}</exists> </file> </activation> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.8</version> <executions> <execution> <id>add-test-source</id> <phase>generate-test-sources</phase> <goals> <goal>add-test-source</goal> </goals> <configuration> <sources> <source>${customFolder}</source> </sources> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles>
说明:这个Profile会自动检测${customFolder}指定的路径,只要目录存在就会激活,插件随之执行;如果目录不存在,Profile不会生效,插件也就不会运行了。
方案二:结合maven-enforcer-plugin做条件判断
如果不想用Profile,也可以先用maven-enforcer-plugin检查目录状态,生成一个控制属性,再用这个属性来开关build-helper插件的执行。
第一步:添加enforcer插件检查目录
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-enforcer-plugin</artifactId> <version>3.3.0</version> <executions> <execution> <id>check-custom-folder</id> <phase>validate</phase> <goals> <goal>enforce</goal> </goals> <configuration> <rules> <requireFilesExist> <files> <file>${customFolder}</file> </files> <fail>false</fail> <!-- 只检查不强制失败 --> </requireFilesExist> </rules> <properties> <property> <name>customFolderExists</name> <value>${file.exists(${customFolder})}</value> </property> </properties> </configuration> </execution> </executions> </plugin>
第二步:修改build-helper插件配置
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.8</version> <executions> <execution> <id>add-test-source</id> <phase>generate-test-sources</phase> <goals> <goal>add-test-source</goal> </goals> <configuration> <skip>${!customFolderExists}</skip> <!-- 目录不存在时跳过 --> <sources> <source>${customFolder}</source> </sources> </configuration> </execution> </executions> </plugin>
说明:enforcer插件在validate阶段检查目录是否存在,把结果存入customFolderExists属性;build-helper通过skip参数判断,当目录不存在时自动跳过执行。
方案三:直接用Maven内置表达式控制(最简洁)
如果你的Maven版本在3.2及以上,可以直接用Maven的内置file.exists()表达式来控制插件的skip参数,不需要额外插件或Profile。
配置示例:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.8</version> <executions> <execution> <id>add-test-source</id> <phase>generate-test-sources</phase> <goals> <goal>add-test-source</goal> </goals> <configuration> <skip>${!file.exists(${customFolder})}</skip> <sources> <source>${customFolder}</source> </sources> </configuration> </execution> </executions> </plugin>
说明:这个配置非常简洁,${!file.exists(${customFolder})}表示“当目录不存在时”,此时skip值为true,插件就会跳过执行。
内容的提问来源于stack exchange,提问作者Chaitra_daddolu
相关产品推荐
相关产品推荐

