如何将整个存储库压缩到第一次提交?

我可以将base转换为第一次提交,但这将留给我2次提交。 有没有办法在第一个提交之前引用这个提交?


当前回答

假设你有这些从06年到10年的提交。

您希望将06年后的提交合并为一个提交Id。

commit 10
commit 09  
commit 08  
commit 07  
commit 06

你可以软复位git。

git reset --soft "06"

然后,运行下面的命令将这些更改推送到远程分支。

git push origin HEAD --force

现在,您之前所做的所有提交都应该作为您的本地更改可用,您可以将所有这些提交合并到单个提交中。

现在,新的提交结构应该如下所示:

commit <new_commit_containing_all_7_8_9_10>
commit 06

其他回答

最简单的方法是使用'plumbing'命令update-ref删除当前分支。

你不能使用git branch -D,因为它有一个安全阀来阻止你删除当前的分支。

这会让你回到“初始提交”状态,在那里你可以开始一个新的初始提交。

git update-ref -d refs/heads/master
git commit -m "New initial commit"

这个答案改进了上面的几个(请投票),假设除了创建一个提交(no-parents - no-history),你还想保留该提交的所有提交数据:

作者(姓名及邮箱) 撰写日期 提交人(姓名及邮箱) 提交日期 提交日志消息

当然,新的/single提交的commit- sha会改变,因为它代表了一个新的(非)历史,变成了一个无父/根提交。

这可以通过读取git日志并为git提交树设置一些变量来实现。假设你想在一个新的分支one-commit中从master创建一个单独的提交,保留上面的commit-data:

git checkout -b one-commit master ## create new branch to reset
git reset --hard \
$(eval "$(git log master -n1 --format='\
COMMIT_MESSAGE="%B" \
GIT_AUTHOR_NAME="%an" \
GIT_AUTHOR_EMAIL="%ae" \
GIT_AUTHOR_DATE="%ad" \
GIT_COMMITTER_NAME="%cn" \
GIT_COMMITTER_EMAIL="%ce" \
GIT_COMMITTER_DATE="%cd"')" 'git commit-tree master^{tree} <<COMMITMESSAGE
$COMMIT_MESSAGE
COMMITMESSAGE
')

当我从git存储库恢复模板时,我通常会压缩整个树,以获得更干净的历史记录,并确保合法合规。我的工作流程是这样的:

git clone https://git.invalid/my-awesome-template.git my-awesome-foo
cd !$
git branch -M master my-awesome-template/master
git checkout --orphan master
git rm -rf /
git commit --allow-empty --allow-empty-message -m 'Initial commit'
git merge --squash --allow-unrelated-histories my-awesome-template/master
git commit
git branch -D my-awesome-template/master
# you can now `drop' that "Initial commit":
git rebase -i --root

这将把整个历史记录压缩到一个大的提交消息中。

在这个例子中:

Master是工作分支 My-awesome-template /master是一个中间分支

首先,使用git rebase -interactive将所有提交压缩成一个提交。现在就剩下两个壁球提交了。要做到这一点,请阅读任何一本

如何合并Git存储库的前两次提交? Git:如何压缩前两次提交?

从git 1.6.2开始,你可以使用git rebase——root -i

对于除第一次提交外的每个提交,将pick更改为squash。