是否有自动更新源文件中元数据的工具?

Is there a tool that automatically updates metadata in source files?

我有一个 git 存储库,其中包含大约一百个 .cpp 和 .h 文件。每个文件都有一个简短的 header,包括许可证数据。我想用几行元数据来扩展这部分,以显示上次创建和修改特定文件的日期。

在不与 git 冲突的情况下,是否有自动管理此问题的良好做法?

这可以通过 git 挂钩来完成。

假设您的所有文件都遵循一个模板。例如:

/**
 * Some license information
 *
 * Last update: Thu, Jun 28, 2018  8:19:47 PM
 */
// Code comes here...

创建一个 可执行文件 文件 .git/hooks/pre-commit 用一个简单的脚本来替换 "Last update:" 行:

#!/bin/sh
d=$(date)
git diff --cached --name-only --diff-filter=ACM | \
    xargs sed -i "s/\* Last update:.*/* Last update: $d/"

使用 git 过滤器。 Git 书中有一个例子可以做到这一点。请参阅 https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes,从 "Another interesting example gets $Date$ keyword expansion, RCS style." 开始。

有两种过滤器,一种用于在将数据添加到提交之前过滤数据(清理过滤器),另一种用于从提交到工作树中检出文件(涂抹过滤器)。获取脚本并配置过滤器:

$ git config filter.dater.clean clean_date
$ git config filter.dater.smudge expand_date