簡體   English   中英

從git歷史記錄中刪除並完全刪除提交

[英]Delete and completely remove the commit from git history

我的git歷史中有一個提交

1.commit 4930da17d8dd23d650ed38435d8b421816a0c451
  Date:   Sat Dec 5 14:34:18 2015 +0530

2.commit e1ebbbb599ee20ebec3ca92c26266d9fd16e7ccc
  Date:   Sat Dec 5 13:22:20 2015 +0530

3.commit 1c4a11a80eb054d24dafec2efed0b0282188e687
  Date:   Sat Dec 5 12:11:50 2015 +0530

4.commit b4ab3c164a3a8d93e0a71a94b5c561cb5e20ebf6
  Date:   Sat Dec 5 12:09:56 2015 +0530

5.commit 167b1d10258381f09663ce61fa88ce3bbcd404c4
  Date:   Sat Dec 5 12:09:21 2015 +0530

6.commit c61bcadac673e1c83f4c14b66d56e23b12fa3198
  Date:   Sat Dec 5 12:07:58 2015 +0530

因為第3和第4次提交包含錯誤的代碼,但在不知不覺中我提交並推送。

3.commit 1c4a11a80eb054d24dafec2efed0b0282188e687
  Date:   Sat Dec 5 12:11:50 2015 +0530

4.commit b4ab3c164a3a8d93e0a71a94b5c561cb5e20ebf6
  Date:   Sat Dec 5 12:09:56 2015 +0530

但第5和第6次提交包含正確的代碼。 我需要這個提交才能工作。

5.commit 167b1d10258381f09663ce61fa88ce3bbcd404c4
  Date:   Sat Dec 5 12:09:21 2015 +0530

6.commit c61bcadac673e1c83f4c14b66d56e23b12fa3198
  Date:   Sat Dec 5 12:07:58 2015 +0530

現在我想完全刪除和刪除我在第3和第4次提交中更改的內容。

我想從git歷史中刪除第3和第4次提交。 但不是第5和第6。

這樣我的分支就會安全。

您可以使用git rebase -i以交互方式重寫歷史記錄:

git rebase HEAD~6 -i 

將打開您的編輯器並允許您將多個提交壓縮為一個,或者從歷史記錄中完全刪除它們(通過刪除編輯器中這些提交的行。)~6表示重寫最后6個提交,-i表示執行此操作交互。 在您的情況下,您將要刪除說“選擇1c4a11a”和“選擇b4ab3c”的行。

請注意,啟動的編輯器中最新的提交是最后一行,而不是第一行,並且由於您正在重寫歷史記錄並且您已經推送過,因此您還必須“git push --force”,不只是“git push”才能向上游發送您的更改。

您可以使用interactive rebase來返回提交歷史記錄並以不同方式執行操作。 對於使用交互式rebase,只需:

git rebase -i <commit_id>

<commit_id>是您要編輯的上次提交的父級。 執行此命令后,只需將ddrop放在提交之前,您將要刪除甚至刪除與該提交相對應的行。

運行此命令會在文本編輯器中為您提供一個類似於以下內容的提交列表:

pick f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added cat-file

# Rebase 710f0f8..a5f4a0d onto 710f0f8
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

交互式rebase為您提供了一個將要運行的腳本。 它將從您在命令行中指定的提交開始,並從上到下重放每個提交中引入的更改。 它列出了最老的,而不是最新的,因為這是它將重播的第一個。

但是,由於您已將分支推送到上游存儲庫,請將此歷史記錄重寫通知給可能的同事,正如git文檔所述

再次記住,這是一個重定位命令 - 無論您是否更改消息,該范圍中包含的每個提交都將被重寫。 不要包含您已經推送到中央服務器的任何提交 - 這樣做會通過提供相同更改的備用版本來混淆其他開發人員。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM