解决pom.xml中Git分支名配置Sonar扫描的exec插件报错问题
解决Git分支名配置到Sonar扫描的问题
你遇到的outputProperty参数报错,是因为exec-maven-plugin的exec目标根本没有这个参数,换下面几种方法就能解决:
方法一:结合exec-maven-plugin和properties-maven-plugin
先把Git分支名输出到临时文件,再读取文件内容到Maven属性:
- 配置exec-maven-plugin将分支名写入临时文件:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.3.0</version> <executions> <execution> <id>get-git-branch-name</id> <phase>initialize</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>git</executable> <arguments> <argument>rev-parse</argument> <argument>--abbrev-ref</argument> <argument>HEAD</argument> </arguments> <outputFile>${project.build.directory}/git-branch.txt</outputFile> </configuration> </execution> </executions> </plugin>
- 配置properties-maven-plugin读取文件内容到
branch.name属性:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>properties-maven-plugin</artifactId> <version>1.1.0</version> <executions> <execution> <id>load-git-branch-property</id> <phase>initialize</phase> <goals> <goal>read-project-properties</goal> </goals> <configuration> <files> <file>${project.build.directory}/git-branch.txt</file> </files> <properties> <property> <name>branch.name</name> <value>@file-content@</value> </property> </properties> </configuration> </execution> </executions> </plugin>
- 之后就能正常在properties里引用:
<properties> <sonar.branch.name>${branch.name}</sonar.branch.name> </properties>
方法二:用git-commit-id-plugin(更推荐)
这个插件专门用来获取Git元数据,不用自己写exec命令,配置更简单:
<plugin> <groupId>pl.project13.maven</groupId> <artifactId>git-commit-id-plugin</artifactId> <version>4.9.10</version> <executions> <execution> <id>get-git-branch</id> <phase>initialize</phase> <goals> <goal>revision</goal> </goals> </execution> </executions> <configuration> <injectAllReactorProjects>true</injectAllReactorProjects> <includeBranchName>true</includeBranchName> </configuration> </plugin>
配置完直接用插件提供的git.branch属性:
<properties> <sonar.branch.name>${git.branch}</sonar.branch.name> </properties>
方法三:命令行直接传参(适合CI/CD场景)
如果是在命令行或者CI环境执行Maven命令,直接把分支名作为参数传入:
mvn sonar:sonar -Dsonar.branch.name=$(git rev-parse --abbrev-ref HEAD)
这样不用修改pom.xml,直接动态传入分支名。
内容的提问来源于stack exchange,提问作者Nishu
相关产品推荐
相关产品推荐

