How to remove commits from git history but otherwise keep the graph exactly the same, including merges?

后端 未结 5 984
礼貌的吻别
礼貌的吻别 2021-01-14 12:25

What I have:

---A----B-----C-----D--------*-----E-------> (master)
                     \\      /
                      1----2 (foo)
         


        
5条回答
  •  死守一世寂寞
    2021-01-14 13:08

    While what I am proposing will give you a clean, linear history; that's what rebase is supposed to do essentially. However, am hoping this gives you a way to remove B and B' from the commit history. Here goes the explanation:

    Repo recreation output:
    ---A----B-----B'-----C--------D-------> (master)
                          \      /
                           1----2 (foo)
    
    git log --graph --all --oneline --decorate #initial view the git commit graph
    * dfa0f63 (HEAD -> master) add E
    *   843612e Merge branch 'foo'
    |\  
    | * 3fd261f (foo) add 2
    | * ed338bb add 1
    |/  
    * bf79650 add C
    * ff94039 modify B
    * 583110a add B
    * cd8f6cd add A
    
    git rebase -i HEAD~5 #here you drop 583110a/add B and ff94039/modify B from
    foo branch.
    
    git log --graph --all --oneline --decorate
    $ git rebase -i HEAD~5
    * 701d9e7 (HEAD -> master) add E
    * 5a4be4f add 2
    * 75b43d5 add 1
    * 151742d add C
    | * 3fd261f (foo) add 2
    | * ed338bb add 1
    | * bf79650 add C
    | * ff94039 modify B
    | * 583110a add B
    |/  
    * cd8f6cd add A
    
    $ git rebase -i master foo #drop 583110a/add B and ff94039/modify B again
    
    $ git log --graph --all --oneline --decorate #view the git commit graph
    
    * 701d9e7 (HEAD -> foo, master) add E
    * 5a4be4f add 2
    * 75b43d5 add 1
    * 151742d add C
    * cd8f6cd add A
    

    Lastly, the final out might not be in the order you'd expected A--C--1---2---E. However, you can re-arrange the order within the interactive mode again. Try git rebase -i HEAD~n.

    Note: It's best to avoid changing commit/publishing history. I am a newbie and exploring git, hopefully the above solution should stick. That said am sure there are tonnes of other easier solutions available online. I found this article quite helpful, for future reference for all.

提交回复
热议问题