Git:如何忘记非常旧的提交

Git: How to forget very old commits

场景:我有一个不时更改的目录结构。我想要备份它曾经处于的所有状态。为此,我只是将它设置为 git 存储库,并让 cron 作业每天执行一次 git commit -m 'croncommit'。这工作正常,使我能够查看历史目录结构的任何状态。

但是 git 存储库在增长,即使目录结构没有增长。如果我曾经在短时间内有一个巨大的文件,它会一直保留在存储库中。当然,从 git 的角度来看,这很好而且正确,但由于对我来说这只是一个备份工具,所以只保留最近的状态是有意义的,比如上个月。

我正在寻找一种方法来从给定存储库中删除超过特定持续时间(例如一个月)的状态(提交)。我认为这可以通过将所有早于特定年龄的提交合并为一个来完成。

但是我找不到适合该任务的正确命令和语法。

我该怎么做?

使用 git log--since 选项找到历史的新起点,并使用 git commit-tree 创建新的无父提交,重用其树状态。之后,将任何 children 变基到新的根并将您的分支引用移动到新的 HEAD。

#! /usr/bin/env perl

use strict;
use warnings;

my $MAX_AGE = 30;
my $BRANCH  = "master";

# assumes linear history
my($new_start,$rebase) = `git log --reverse --since="$MAX_AGE days ago" --format=%H`;
die "[=10=]: failed to determine new root commit"
  unless defined($new_start) && $? == 0;

chomp $new_start;

my $new_base = `echo Forget old commits | git commit-tree "$new_start^{tree}"`;
die "[=10=]: failed to orphan $new_start" unless $? == 0;
chomp $new_base;

# don't assume multiple commits more recent than $MAX_AGE
if (defined $rebase) {
  system("git rebase --onto $new_base $new_start HEAD") == 0
    or die "[=10=]: git rebase failed";
}

system("git branch -f $BRANCH HEAD") == 0
  or die "[=10=]: failed to move $BRANCH";

system("git reflog expire --expire=now --all && git gc --prune=now") == 0
  or die "[=10=]: cleanup failed";

例如:

$ git lol --name-status
* 186d2e5 (HEAD, master) C
| A     new-data
* 66b4a19 B
| D     huge-file
* 5e89273 A
  A     huge-file

$ git lol --since='30 days ago'
* 186d2e5 (HEAD, master) C
* 66b4a19 B

$ ../forget-old 
First, rewinding head to replay your work on top of it...
Applying: C
Counting objects: 5, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (5/5), done.
Total 5 (delta 1), reused 0 (delta 0)

$ git lol --name-status
* b882852 (HEAD, master) C
| A     new-data
* 63bb958 Forget old commits

请注意 git lol 是非标准的,但 highly useful alias 等同于

git log --graph --decorate --pretty=oneline --abbrev-commit

OP 添加:这是上面 Perl 脚本的 bash 版本:

#!/bin/bash -xe

MAX_AGE=${MAX_AGE:-30}
BRANCH=${BRANCH:-master}

# assumes linear history
{
  read new_start
  read rebase
} < <(git log --reverse --since="$MAX_AGE days ago" --format=%H)
[ -n "$new_start" ]  # assertion

read new_base < <(
  echo "Forget old commits" | git commit-tree "$new_start^{tree}"
)

# don't assume multiple commits more recent than $MAX_AGE
[ -n "$rebase" ] && git rebase --onto $new_base $new_start HEAD

git branch -f "$BRANCH" HEAD

git reflog expire --expire=now --all
git gc --prune=now

git checkout "$BRANCH"  # avoid ending on "no branch"