How can I delete some old commits, but keep all other values ​​intact in git?

Suppose the commit structure is similar to the structure below:

B'---C' X' / \ / \ A---B---C---D---...---X---Y---Z(master) 

And now I need to clear all commits between A and X,

  X' / \ A---X---Y---Z 

AFAIK, there are at least two ways to achieve this:

  • git rebase -i A
  • git branch -f new_branch A; git rebase --onto master X

But there are always some conflicts that I need to handle manually.

Since I just wanted to clear all the commits after A and before X, and I don't need to change any git tracking results after each commit (for example, the newly created commits of X have the same contents as the old X commit), is there an easier way to do this?

+4
source share
3 answers

Note This solution will push out the commits that you want to “split” into X, so that the new X commit and all subsequent commits have their files in the same state as they are now. If this is not what you wanted, see my other answer .


 git checkout -b temp A git merge X --squash git commit -CX # Create new x commit git checkout master git rebase --preserve-merges --onto temp X # Rebase onto new X commit (should produce no conflicts) git -d temp 
+1
source

I would try something like:

 git checkout -b new_X X git rebase -i A # set everything to 'squash' git checkout master git rebase --preserve-merges --onto new_X X 

This, I hope, should keep the commit of changes the same, so conflicts will arise. If this fails, I would probably resort to low-level commands like git commit-tree and some script to create a new structure from the source trees.

0
source

Change This solution will remove old commits from the repository (including any changes made to them). This is clearly not what the op was asking, but I will still leave the answer here for future readers.


 git checkout master git rebase --onto AX~ 

I cannot guarantee that there will be no conflicts, but if you click on them, you can resolve them manually, git add conflict files, and then enter git rebase --continue .

Alternatively, you can force git rebase automatically resolve any conflicts by applying more recent changes at the top of any conflicting changes made to (or before):

 git checkout master git branch backup # Just to be safe git rebase -s theirs --onto AX~ git branch -D backup # When you're sure master has everything you need 
0
source

Source: https://habr.com/ru/post/1487293/


All Articles