如何使 git 维护包含选择信息的 git.properties 文件



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

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

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

<小时 />

编辑 2022:我做了一些工作,使用注释处理将此信息捕获为 Java 源代码,因此不需要属性文件。 有前途,但尚未达到生产质量。

注意(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");
  }
<小时 />

卢博在评论中建议:

要手动更新target/classes/git.properties文件:

mvn pl.project13.maven:git-commit-id-plugin:revision 

最新更新