【问题标题】:Squashing history from a range: from the initial commit to another从一个范围内压缩历史:从最初的提交到另一个
【发布时间】:2017-03-23 20:18:45
【问题描述】:

我正在尝试找出如何从一系列提交中压缩 Git 中的提交。我的具体情况是我分叉了一个存储库并在其上添加了几个工作提交;但是我想将所有分叉的 repo 提交压缩为一个提交以保持历史记录干净。

示例

7e8d7f7 - (HEAD) My commit
809fc8b - My commit
e04692c - Forked repo's commit          \
2674323 - Forked repo's commit           > Turn these into a single commit
4e79731 - Forked repo's initial commit  /

这是我尝试过的方法

  1. 通过git rev-list --max-parents=0 HEAD 获取初始提交的SHA,以获得我想要压缩的范围的下限 (Source)
  2. 通过git checkout <upper bound commit> 将 HEAD 分离到范围的上限
  3. 软重置到下限并提交(替代git rebase -i):git reset --soft <lower bound commit> && git commit (Source)
  4. 合并到master:git merge --no-ff master

我最终以这种方式得到了大量的合并冲突。我觉得通过我遇到的命令可以实现我想要实现的目标,但是我不知道如何将它们串在一起以使其工作。

【问题讨论】:

  • 这听起来像是一个特别不明智的解决方案。您是否尝试复制并粘贴代码并在那里创建一个新的 git 存储库?因为它具有相同的效果。
  • 请解释您为什么要这样做?很明显,您会遇到合并冲突。如果您更改以前的提交,那么您将创建一个全新的存储库。提供的所有答案都会给您合并冲突。你想要“保持历史干净”的内在动机是什么?
  • @Unapiedra 我分叉了一个样板项目并在它之上做了一些工作,但我没有在开始工作之前删除.git 文件夹,而是继续致力于分叉的回购。是的,我理解大家的顾虑;除非您知道自己在做什么,否则请不要尝试这样做。

标签: git github merge


【解决方案1】:

首先,我会避免这样做。

Git 历史是一件美妙的事情,你的 repo 的未来用户可能想知道你在哪里分叉。

或者您可能希望稍后从远程拉取额外的提交,如果您不特意弄乱共享历史记录,那可能会更容易。

也就是说,这应该适合你:

git checkout e04692c -b squashing_branch

git reset --soft $(git rev-list --max-parents=0 HEAD)
git commit --amend -m "Forked repo as one big commit"

git cherry-pick e04692c..master

【讨论】:

【解决方案2】:
  1. 不要这样做。
  2. 您可以只创建一个新的存储库。因为这与在开始工作之前压缩所有提交完全相同。 # Get the original git repository somehow $ git clone URL # Delete the old repo $ cd your-repo; rm -rf .git/ $ git init # create new repo. $ git add -a $ git commit -m 'Forked repo from X and squashed all commits' # Now start working. # Again, I think this whole undertaking is misguided.
  3. 您创建一个没有父级的新提交作为“压缩”提交。 让我们假设真实的历史记录在一个名为“long_history”的分支上。

    git checkout master  # assuming on master is the complete history.
    # Create a new branch without any history. A new root so to speak.
    git checkout --orphan squashed_master 
    # All the files from the original 'master' will be already added
    # to the index. 
    git commit -m 'Squashed all of the previous history as cloned from X'.
    # Delete the master branch and create it again
    git branch -D master
    git branch master
    git push --force -u origin master  # Assuming that 'origin' is the remote of your fork and not the original repository. Change accordingly...
    
  4. 我还是觉得你不应该这样做。

最后说明:我认为子树可能是一种选择。我尝试使用git subtree,但这不适用于--prefix=.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2022-07-21
    • 2017-08-06
    • 2021-11-14
    • 1970-01-01
    • 2011-01-19
    • 2014-03-14
    相关资源
    最近更新 更多