开发者用Git提交时间戳实现Maven可复现构建
来源标题:Git commit based reproducible builds with Maven
一位开发者通过git-commit-id-plugin将Git提交时间戳设为Maven构建的输出时间戳,使构建产物字节级可复现,并让应用内可获取该时间戳与提交哈希。Maven官方文档仅提及该插件可行但未说明具体配置,作者通过阅读插件源码才弄清细节。
以下正文由 AI 翻译自 Hacker News 最新(原文版权归原站所有),可能存在偏差,重要内容请以原文为准。
我一直在努力让我的 Maven 构建实现逐字节可复现。这通常很简单,Maven 网站上也有文档说明。简而言之,你需要在 POM 中指定一个输出时间戳,这样 Maven 就会使用那个固定时间点作为构件中文件的创建/修改时间戳。如果没有固定时间戳,每次构建都会不同,即使文件内容没有变化,因为时间戳会被包含在构件中。
出于与本文无关的原因,我不想在 POM 中使用硬编码的输出时间戳。我想改用 git commit 的时间戳,并且希望能在应用程序内部获取该时间戳和 git commit 哈希。
Maven 文档提到可以通过 git-commit-id 插件来实现,但没有说明具体怎么做。结果发现这相当直接,但我不得不阅读插件的源代码来弄清楚一些细节。也许将来我会提交一个 PR 来改进文档?
POM 需要知道 git-commit-id-plugin,并且需要有一个 project.build.outputTimestamp 属性。
<properties> <!-- This ppt tells maven we want reproducible builds --> <!-- The timestamp will be taken from the currently checked out commit --> <project.build.outputTimestamp>${git.commit.time}</project.build.outputTimestamp> </properties> <plugins> <plugin> <groupId>io.github.git-commit-id</groupId> <artifactId>git-commit-id-maven-plugin</artifactId> <version>10.0.1</version> <configuration> <generateGitPropertiesFile>true</generateGitPropertiesFile> <generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename> <dateFormatTimeZone>UTC</dateFormatTimeZone> <commitIdGenerationMode>full</commitIdGenerationMode> <includeOnlyProperties> <includeOnlyProperty>^git.commit.time$</includeOnlyProperty> <includeOnlyProperty>^git.commit.id.full$</includeOnlyProperty> </includeOnlyProperties> </configuration> <executions> <execution> <id>git-info</id> <goals> <goal>revision</goal> </goals> <phase>initialize</phase> </execution> </executions> </plugin> <!-- ... --> </plugins>运行时访问 commit 信息
git 插件被设置为将信息写入 git.properties。我们可以在运行时使用 getResourceAsStream() 来访问它。
try (InputStream is = App.class.getResourceAsStream("/git.properties")) Properties gitProps = new Properties(); gitProps.load(is); String commitTime = gitProps.getProperty("git.commit.time"); String commitId = gitProps.getProperty("git.commit.id.full"); // ... Do stuff!
请注意,该插件还可以向此文件写入许多其他属性,这些属性可能对你有用,也可能没用。例如,你可以包含 git.dirty 标志,并在应用程序从脏源代码树构建时拒绝启动。或者,当 git.commit.user.name 与同事的名字匹配时,你可以通过捣鼓应用来恶作剧他们。咳咳。
仅仅添加这一个属性并不能保证构建完全可复现。其他事情也可能出错:
至少你会想要运行 mvn artifact:check-buildplan 来检查任何明显的配置错误。你还会想要进行两次本地构建并比较它们的输出。Maven 有一种还算方便的方法来做这件事:mvn clean install && sleep 5 && mvn clean verify artifact:compare。
最后,你会想要在多台机器上运行构建(或者请你的同事这样做)并比较它们的输出。
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。