![](/img/trans.png)
[英]How to merge only one commit to master and not all commits of a branch?
[英]How can I rebase 3 commits with one merge of master into one commit?
當我遇到這種情況時,我似乎總是迷迷糊糊,完全弄亂了git commits。 我希望這次能避免這種情況。 這是我的情況。 我的PR中有以下4個提交:
Commit 1: Remove unused routes for the projects controller
Commit 2: Add PR request changes and modify similar_by_tags_route
Commit 3: Merge Master and resolve git merge conflicts
Commit 4: Reinsert rubocop disablement for project.rb
我需要將這些提交重新構建為一個提交。 現在,由於主控器的討厭合並,我不能只是重新設置rebase -i HEAD~4
。 有沒有一種方法我可以簡單地刪除提交3並僅合並提交1、2和4? 我真的希望對此有所幫助,因為在進行此類棘手的合並時,我似乎總是一團糟。
您可以嘗試對分支進行交互式的變基,而只需刪除包含合並提交的行即可。 運行git rebase -i HEAD~4
應該會顯示一系列提交,如下所示:
pick Commit 1: Remove unused routes for the projects controller
pick Commit 2: Add PR request changes and modify similar_by_tags_route
pick Commit 3: Merge Master and resolve git merge conflicts
pick Commit 4: Reinsert rubocop disablement for project.rb
刪除包含合並提交的行,剩下的就是:
pick Commit 1: Remove unused routes for the projects controller
pick Commit 2: Add PR request changes and modify similar_by_tags_route
pick Commit 4: Reinsert rubocop disablement for project.rb
現在將第2次和第4次提交更改為squash
,以告訴Git將這些提交合並為單個第一次提交:
pick Commit 1: Remove unused routes for the projects controller
squash Commit 2: Add PR request changes and modify similar_by_tags_route
squash Commit 4: Reinsert rubocop disablement for project.rb
完成變基,您應該隨心所欲。 請注意,像這樣重新定基礎意味着重寫分支的歷史記錄。 因此,如果此分支由其他人公開共享,則應采取預防措施。
假設您的4個提交位於分支B1上,這就是用於創建PR的分支的名稱。
將多個Git提交壓縮為一個提交
此注釋顯示了如何將具有多個臟WIP提交的丑陋功能分支作為一個漂亮的提交合並回主服務器。
簡易模式:將功能分支重置為主狀態
將功能分支中的多個提交轉換為單個提交的最簡單方法是重置主節點中的功能分支更改,然后再次提交所有內容。
# Switch to the master branch and make sure you are up to date.
git checkout master
git fetch # this may be necessary (depending on your git config) to receive updates on origin/master
git pull
# Merge the feature branch into the master branch.
git merge feature_branch
# Reset the master branch to origin's state.
git reset origin/master
# We can add these changes as one commit.
# Adding . will also add untracked files.
git add --all
git commit
請注意,這根本不涉及功能分支。 如果稍后將功能分支再次合並到母版中,則其所有提交將重新出現在日志中。
您也可以反過來進行操作(將master合並到分支中並重置為master狀態),但這會破壞您在feature分支中的提交,這意味着您無法將其推送到原始位置。
硬模式:壁球提交
此方法比使用上面的get reset方法更難。 另外,如果您先前將母版合並到功能分支中,則效果也不佳(您需要再次解決所有沖突)。
我們在這里描述的內容將破壞提交歷史,並且可能出錯。 因此,請在單獨的分支上進行壓縮:
git checkout -b squashed_feature
這樣,如果您搞砸了,則可以返回到原始分支,再創建另一個分支以進行壓縮,然后重試。
要壓縮自從master分支以來的所有提交,請執行
git rebase -i master
請注意,如果您在使用新功能時將母版合並到功能分支中,則無法使用母版重新建立基礎。 如果這樣做,您將需要找到原始分支點,並使用SHA1修訂版調用git rebase。
您的編輯器將打開一個類似
pick fda59df commit 1
pick x536897 commit 2
pick c01a668 commit 3
每行代表一次提交(按時間順序,最后一次提交將在底部)。
要將所有這些提交轉換為一個提交,請將文件更改為此:
pick fda59df commit 1
squash x536897 commit 2
squash c01a668 commit 3
這意味着,您進行第一次提交,然后壓縮下一次提交。 如果刪除一行,則實際上會丟失相應的提交。 不要理會更改提交消息,因為它們會被忽略。 保存了壁球設置后,編輯器將再次打開,以請求有關壁球提交的提交消息。
現在,您可以將功能作為一次提交合並到母版中:
git checkout master
git merge squashed_feature
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.