Remove commits before specific commit

前端 未结 2 1788
眼角桃花
眼角桃花 2021-02-01 05:04

Is there a way to remove all commits before a specified commit and use that commit as the initial?

相关标签:
2条回答
  • 2021-02-01 05:45

    The more easier solution would be, Consider originally your branch has commit main and you did a commit first, now you also did a commit second on top of first. So you have something like:

    main->first->second
    

    Now you want to have second on top of main rather than on top of first. Something like:

    main->second->first or main->second
    

    You can simply do,

    git rebase -i main
    

    This will give you an interactive shell where you can rearrange the order of commits or remove any commit of your choice.

    0 讨论(0)
  • 2021-02-01 05:54

    Let's say the new oldest commit's hash is X and we can use "oldroot" and "newroot" temporarily:

    git checkout -b oldroot X
    TREE=`git write-tree`
    COMMIT=`echo "Killed history" | git commit-tree "$TREE"`
    git checkout -b newroot "$COMMIT"
    git rebase --onto newroot oldroot master
    # repeat for other branches than master that should use the new initial commit
    git checkout master
    git branch -D oldroot
    git branch -D newroot
    git gc # WARNING: if everything's done right, this will actually delete your history from the repo!
    

    That will create a 'newroot' commit with the same contents as the 'oldroot' commit, but without any parents. Then, it rebases all the other branches onto the new root, which should be in the history of all of them.

    EDIT: tested and fixed; slightly later, refined a bit

    0 讨论(0)
提交回复
热议问题