首页 > 解决方案 > 通过 git commit time 将 X 个最新的文件保存在一个文件夹中

问题描述

我将来自基准测试的 JSON 结果文件存储到一个特定文件夹中,该文件夹最多可容纳 X 个文件,一旦该文件夹达到 X 个 JSON 文件,它应该删除最近添加的最少的 JSON 文件(最旧的文件)一次最多在文件夹中包含 X 个 JSON 文件。

我目前已经实施了一个类似于从这个SO post接受的答案的解决方案。问题是ls没有返回具有我期望的修改时间的文件。

当我运行以下 find 命令时,我看到修改时间都非常接近。我没有更改文件,所以它必须与我运行的 git pull 有关,并注意我将在 Jenkins 上运行它,因此它会在每次构建时创建一个新的工作区。

$ find -type f -printf '%T+ %p\n' | sort
2021-08-03+10:49:13.8291325000 ./benchmark-result-4.7.2-10.json
2021-08-03+10:49:13.8391335000 ./benchmark-result-4.7.2-11.json
2021-08-03+10:49:13.8481332000 ./benchmark-result-4.7.2-12.json
2021-08-03+10:49:13.8591340000 ./benchmark-result-4.7.2-3.json
2021-08-03+10:49:13.8681350000 ./benchmark-result-4.7.2-4.json
2021-08-03+10:49:13.8751338000 ./benchmark-result-4.7.2-5.json
2021-08-03+10:49:13.8811401000 ./benchmark-result-4.7.2-6.json
2021-08-03+10:49:13.8891411000 ./benchmark-result-4.7.2-7.json

但我希望顺序如下,因为第一个提交的是 4.7.2-3 结果文件。

./benchmark-result-4.7.2-3.json
./benchmark-result-4.7.2-4.json
./benchmark-result-4.7.2-5.json
./benchmark-result-4.7.2-6.json
./benchmark-result-4.7.2-7.json
./benchmark-result-4.7.2-10.json
./benchmark-result-4.7.2-11.json
./benchmark-result-4.7.2-12.json

我试过这个命令

$ git log --no-merges --first-parent --name-only --diff-filter=A --pretty=format: <branch_name> <directory_to_delete_from> | grep ".json"
benchmark-result-4.7.2-13.json
benchmark-result-4.7.2-12.json
benchmark-result-4.7.2-11.json
benchmark-result-4.7.2-10.json
benchmark-result-4.7.2-9.json
benchmark-result-4.7.2-8.json
benchmark-result-4.7.2-7.json
benchmark-result-4.7.2-6.json
benchmark-result-4.7.2-5.json
benchmark-result-4.7.2-4.json
benchmark-result-4.7.2-3.json
---------------------------- <- manually inserted
benchmark-result-4.7.2-17.json
benchmark-result-4.7.2-14.json
benchmark-result-4.7.2-13.json
benchmark-result-4.7.2-12.json
benchmark-result-4.7.2-11.json
benchmark-result-4.7.2-10.json
benchmark-result-4.7.2-9.json
benchmark-result-4.7.2-8.json
benchmark-result-4.7.2-7.json
benchmark-result-4.7.2-6.json
benchmark-result-4.7.2-5.json
benchmark-result-4.7.2-4.json
benchmark-result-4.7.2-3.json

虽然它确实给了我一个按提交时间排序的列表,但“----”下面的所有基准测试结果都不再存在于目录中,因为它们之前已被删除。我可以反转列表,然后从顶部删除,直到我们只剩下 10 个,但我不喜欢该解决方案,因为这是基准结果文件具有相同名称的机会。

有没有一种方法可以更改上面的 git log 以仅返回存储库中存在的文件?还是有其他命令可以解决我的问题?

请注意,解决方案可以是 bash 脚本,不需要存在于单行中。

标签: bashgitunixscripting

解决方案


看起来您已经用数字序列号命名它们,以便按照您要查找的序列进行排序sort -Vgit ls-files \*.json | sort -V.

如果您不能依赖名称,则必须对日志进行后处理以获取最新信息:

git log --pretty= --name-status -- \*.json \
| awk -F$'\t' '!seen[$2]++ && $1!="D"'

并且历史悠久,您会想要添加一些“我完成了吗?” 逻辑。


推荐阅读