Maven 项目获取 git 分支、提交等信息

git-commit-id-plugin 是一个 Maven 插件,用于在 Maven 项目的构建过程中自动获取 git 仓库的信息,如最后一次提交的 ID、分支名称、构建时间等,并将这些信息注入到项目的属性文件中。这对于跟踪项目版本和构建状态非常有用。

以下是如何在 Maven 项目中使用 git-commit-id-plugin 的基本步骤:

  1. 添加插件到 pom.xml 文件中:

    在你的 Maven 项目的 pom.xml 文件中,添加 git-commit-id-plugin<plugins> 部分。

    xml 复制代码
    <build>
        <plugins>
            <plugin>
                <groupId>pl.project13.maven</groupId>
                <artifactId>git-commit-id-plugin</artifactId>
                <version>4.0.5</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>revision</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <!-- 配置选项 -->
                </configuration>
            </plugin>
        </plugins>
    </build>
  2. 配置插件:

    <configuration> 标签中,你可以配置多种选项,例如生成的属性文件的位置、包含哪些 git 属性等。默认情况下,插件会生成一个 git.properties 文件在 target/classes 目录下。

    xml 复制代码
    <configuration>
        <dotGitDirectory>${project.basedir}/.git</dotGitDirectory>
        <generateGitPropertiesFile>true</generateGitPropertiesFile>
        <generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename>
        <format>properties</format>
    </configuration>
  3. 构建项目:

    使用 Maven 命令构建项目,例如 mvn clean install。在构建过程中,git-commit-id-plugin 插件会自动运行,并在指定的位置生成包含 git 信息的 git.properties 文件。

  4. 查看 git.properties 文件:

    打开生成的 git.properties 文件,你将看到类似以下的内容,其中包含了提交时间、提交记录、分支等信息:

    git.branch=main
    git.commit.id=abcdef1234567890
    git.commit.id.abbrev=abcdef1
    git.commit.time=2021-05-20T12:34:56Z
    git.commit.message.full=Initial commit
    git.commit.message.short=Initial commit
    git.commit.user.name=Your Name
    git.commit.user.email=your.email@example.com
    
  5. 在应用中使用这些信息:

    你可以在应用程序中读取 git.properties 文件,并使用这些信息,例如显示当前版本的 Git 分支和提交 ID。

通过这种方式,你可以利用 git-commit-id-plugin 插件来自动获取和使用 Git 的提交时间、提交记录、分支等信息,从而帮助跟踪和管理你的项目版本。

相关推荐
用户611881615196229 分钟前
Java基础面试题
java
DavidSoCool1 小时前
Elasticsearch Java API Client [8.17] 使用
java·大数据·elasticsearch
无世世1 小时前
【Java从入门到起飞】面向对象编程(高级)
java·开发语言
Vic101011 小时前
Mac如何查看 IDEA 的日志文件
java·macos·intellij-idea
陈逸轩*^_^*1 小时前
idea打不开,idea打不开,Error occurred during initialization of VM
java·ide·intellij-idea
=PNZ=BeijingL1 小时前
使用Mockito实现单元测试
java
eggcode1 小时前
IDEA与Maven使用-学习记录(持续补充...)
学习·maven·intellij-idea
yuren_xia1 小时前
在 IntelliJ IDEA(2024) 中创建 JAR 包步骤
java·intellij-idea·jar