我曾经问过如何压缩git存储库中的前两次提交。

虽然这些解决方案相当有趣,而且不像git中的其他一些东西那样令人费解,但如果您需要在项目开发过程中多次重复这个过程,那么它们仍然是一个众所周知的伤害。

所以,我宁愿只经历一次痛苦,然后能够永远使用标准的交互式rebase。

那么,我想做的是有一个空的初始提交,它的存在仅仅是为了成为第一个。没有代码,什么都没有。只是占地方,这样就可以做地基了。

我的问题是,有了一个现有的存储库,我如何在第一个提交之前插入一个新的空提交,并将其他所有人向前移动?


当前回答

切换根提交。

首先,创建您想要作为第一个提交的提交。

其次,使用以下命令切换提交顺序:

Git rebase -i—root

在根节点提交之前,会出现一个编辑器,比如:

选择1234旧根消息

在中间提交

选择你想放在根目录下的5678提交

然后,您可以将您想要的提交放在第一行中。在这个例子中:

选择你想放在根目录下的5678提交

选择1234旧根消息

在中间提交

退出编辑器,提交顺序将会改变。

PS:要更改git使用的编辑器,运行:

Git配置——全局核心。编辑name_of_the_editor_program_you_want_to_use

其他回答

合并亚里士多德Pagaltzis和Uwe Kleine-König的答案和理查德布罗诺斯基的评论。

git symbolic-ref HEAD refs/heads/newroot
git rm --cached -r .
git clean -f -d
# touch .gitignore && git add .gitignore # if necessary
git commit --allow-empty -m 'initial'
git rebase --onto newroot --root master
git branch -d newroot

(只是为了把所有的东西放在一个地方)

启动一个新的存储库。

将日期设置为您想要的开始日期。

按照你希望的方式做每件事,调整系统时间以反映你希望那样做的时间。根据需要从现有存储库中提取文件,以避免大量不必要的输入。

当您到达今天时,交换存储库,您就完成了。

如果你只是一个疯狂的(成熟的)但相当聪明的人(很可能,因为你必须有一定的智慧才能想出像这样疯狂的想法),你将编写这个过程。

当你决定让过去的事情从现在开始以另一种方式发生时,这也会让事情变得更好。

我知道这篇文章很旧了,但当谷歌搜索“插入提交git”时,这个页面是第一个。

为什么要把简单的事情变得复杂?

你有A-B-C,你想要A-B-Z-C。

git rebase -i trunk(或B之前的任何东西) 更改pick在B行上编辑 进行更改:git add .. git commit (git commit - modify将编辑B而不创建Z)

[你可以在这里进行任意数量的git提交,以插入更多的提交。]当然,在第5步中您可能会遇到麻烦,但是使用git解决合并冲突是您应该具备的技能。如果没有,那就练习!]

Git rebase—继续

很简单,不是吗?

如果你理解git rebase,添加一个“根”提交应该不是问题。

玩得开心!

好吧,这是我想到的:

# Just setting variables on top for clarity.
# Set this to the path to your original repository.
ORIGINAL_REPO=/path/to/original/repository

# Create a new repository…
mkdir fun
cd fun
git init
# …and add an initial empty commit to it
git commit --allow-empty -m "The first evil."

# Add the original repository as a remote
git remote add previous $ORIGINAL_REPO
git fetch previous

# Get the hash for the first commit in the original repository
FIRST=`git log previous/master --pretty=format:%H  --reverse | head -1`
# Cherry-pick it
git cherry-pick $FIRST
# Then rebase the remainder of the original branch on top of the newly 
# cherry-picked, previously first commit, which is happily the second 
# on this branch, right after the empty one.
git rebase --onto master master previous/master

# rebase --onto leaves your head detached, I don't really know why)
# So now you overwrite your master branch with the newly rebased tree.
# You're now kinda done.
git branch -f master
git checkout master
# But do clean up: remove the remote, you don't need it anymore
git remote rm previous

如果你忘记在"git init"之后立即创建一个空提交,那么在存储库的开始添加一个空提交:

git rebase --root --onto $(git commit-tree -m 'Initial commit (empty)' 4b825dc642cb6eb9a060e54bf8d69288fbee4904)