How to remove file and commit from history in git(git中如何移除 commit 曆史紀錄)

來源:互聯網
上載者:User

假設我們的 commit tree 如下:

R–A–B–C–D–E–HEAD

準備工作:

 rm -rf .git test.txt

 touch test.txt && git init && git add .
 echo "R" >> test.txt && git ci -a -m "R"
 echo "A" >> test.txt && git ci -a -m "A"
 echo "B" >> test.txt && git ci -a -m "B"
 echo "C" >> test.txt && git ci -a -m "C"
 echo "D" >> test.txt && git ci -a -m "D"
 echo "E" >> test.txt && git ci -a -m "E"

接下來要移除 B 跟 C 的 commit tree,變成

R–A -- D–E–HEAD

這兒有兩種方法移除 B & C:

方法一:

# detach head and move to D commit
git checkout <SHA1-for-D>

# move HEAD to A, but leave the index and working tree as for D
git reset --soft <SHA1-for-A>

# Redo the D commit re-using the commit message, but now on top of A
git commit -C <SHA1-for-D>

在這兒,你可以增加,刪除(某些意外提交的臨時檔案)然後提交。

# Re-apply everything from the old D onwards onto this new place 
git rebase --onto HEAD <SHA1-for-D> master

# push it
git push --force

方法二:  利用 cherry-pick

git rereset --hard <SHA1 of A>
git cherry-pick <SHA1 of D>
git cherry-pick <SHA1 of E>

中間可能出現的問題

http://rwmj.wordpress.com/2010/05/14/git-cherry-pick-wins/


If it’s unable to apply the patch directly, then you’ll see a message

like this:

  Automatic cherry-pick failed.  After resolving the conflicts,
  mark the corrected paths with 'git add <paths>' or 'git rm <paths>' and commit the result.
  When commiting, use the option '-c 94e310d' to retain authorship and message.

This is fairly self-explanatory. Use “git status” to see which files
are problematic:

Edit the file to manually resolve the conflict, add the file, and then
commit with the “-c” option noted in the original message.

cherry-pick不好的地方在於,如果有D後面有多次提交的話,要多次執行該命令,而且可能有衝突需要手動解決。

這兩種方法都會直接忽略 B 跟 C 的 history,,但是B 和C 所做更改依然存在,只是把
commit history移出了而已。

詳細資料可以查詢 git help cherry-pick 或者是 git help rebase

參考:
Git: removing selected commits from repository
http://stackoverflow.com/questions/495345/git-removing-selected-commits-from-repository
Git: how to remove file and commit from history
http://bogdan.org.ua/2009/02/13/git-how-to-remove-file-commit-from-history.html
Re: ! [rejected] master -> master (non-fast forward)
http://kerneltrap.org/mailarchive/git/2007/11/18/425729

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.