4

我们需要在我们的 Maven 构建中使用 git 分支和提交哈希。

有没有一种简单的方法让 git 自动维护一个包含我们需要的信息的“git.properties”文件,以便它始终反映 git 的当前状态?

如果可能的话,我们希望这是一个与平台无关的解决方案

4

1 回答 1

2

注意(2016 年,但实际上创建于 2011 年 9 月),有一个 maven 插件专门用于在属性文件中捕获 Git 信息。
它是ktoso/maven-git-commit-id-plugin之一。

    <dependency>
        <groupId>pl.project13.maven</groupId>
        <artifactId>git-commit-id-plugin</artifactId>
        <version>2.2.1</version>
    </dependency>

然后:

    <plugins>
        <plugin>
            <groupId>pl.project13.maven</groupId>
            <artifactId>git-commit-id-plugin</artifactId>
            <version>2.2.1</version>
            <executions>
                <phase>initialize</phase>
                <execution>
                    <id>get-the-git-infos</id>
                    <goals>
                        <goal>revision</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <generateGitPropertiesFile>true</generateGitPropertiesFile>
            </configuration>
        </plugin>
    </plugins>

就您而言,由于您“在 Maven 构建过程的早期就需要此信息”,因此我添加了<phase>initialize</phase>以便在默认的 jar maven 生命周期中尽早触发它。

然后我在执行我的插件期间使用它,以打印与 Git 相关的调试数据,这有助于了解该插件的确切版本。

            Properties prop = new Properties();
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            InputStream stream = loader.getResourceAsStream("git.properties");
            if (stream != null) {
                prop.load(stream);
                String dirty = prop.getProperty("git.dirty");
                if (dirty.equals("false")) {
                    dirty = "";
                } else {
                    dirty = "(dirty)";
                }
                ver = ver + prop.getProperty("git.build.version")+dirty;
                ver = ver + " - " + prop.getProperty("git.commit.id.describe");
                ver = ver + " - " + prop.getProperty("git.build.time");
            } else {
                throw new MojoFailureException("Unable to find MyProject git.properties");
            }
于 2016-08-29T11:50:23.053 回答