在這篇文章中,我將展示有時如何在命令列上使用 git 恢復編碼專案中的錯誤變更(提交)。

我為什麼要這樣做?

在我的論文中,我正在研究一個在一個環境中開發的專案,然後在另一個由多個虛擬機器組成的環境中進行測試。所以我所做的每一個重要的改變都可能對專案的功能產生重大影響。有時候,我所做的改變可能沒有達到我預期的結果。然後我必須查看更改並分析上次提交前後專案的行為。

你如何看待最後一次提交?

要測試特定提交,您需要哈希值。要取得哈希值,您可以執行“git log”,然後您將獲得以下輸出:

root@debian:/home/debian/test-project# git log
commit <last commit hash>
Author: Isabel Costa <[email protected]>
Date:   Sun Feb 4 21:57:40 2018 +0000

<commit message>

commit <before last commit hash>
Author: Isabel Costa <[email protected]>
Date:   Sun Feb 4 21:42:26 2018 +0000

<commit message>

(...)

您也可以執行“git log --oneline”來簡化輸出:

root@debian:/home/debian/test-project# git log --oneline
<last commit hash> <commit message>
cdb76bf Added another feature
d425161 Added one feature

(...)

若要測試您認為具有最後工作版本的特定提交(例如:「」),您可以輸入以下內容:

git checkout <commit hash>

這將使工作儲存庫與此確切提交的狀態相符。

執行此操作後,您將得到以下輸出:

root@debian:/home/debian/test-project# git checkout <commit hash>
Note: checking out '<commit hash>'.

You are in 'detached HEAD' state. You can look around, make experimental changes
and commit them, and you can discard any commits you make in this state without
impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may do so
(now or later) by using -b with the checkout command again. Example:

git checkout -b new_branch_name

HEAD is now at <commit hash>... <commit message>

分析特定提交後,如果您決定保持該提交狀態,則可以撤銷上次提交。

如何撤銷此提交?

如果您希望撤銷/復原上次提交,您可以使用從「git log」指令取得的提交雜湊執行下列操作:

git revert <commit hash>

此命令將建立一個新的提交,並在訊息開頭包含“Revert”一詞。之後,如果您檢查儲存庫狀態,您會發現 HEAD 在先前測試的提交處已分離。

root@debian:/home/debian/test-project# git status
HEAD detached at 69d885e

(...)

您不想看到此訊息,因此要修復此問題並附回 HEAD到您的工作儲存庫,您應該簽出您正在處理的分支:

git checkout <current branch>

在撰寫這篇文章的過程中,我發現了Atlassian 的教程 — 撤消提交和更改 — ,它很好地描述了這個問題。

概括

  • 如果你想測試之前的提交,只需執行git checkout <test commit hash>;然後您可以測試專案的最後一個工作版本。

  • 如果你想恢復最後一次提交,只需執行「git revert 」;然後你可以推送這個新的提交,這會撤銷你先前的提交。

  • 若要修復分離的頭,請執行「git checkout <目前分支>」。


您可以在TwitterLinkedInGithub 上找到我/isabelcosta)、Medium我的個人網站


原文出處:https://dev.to/isabelcmdcosta/how-to-undo-the-last-commit--31mg


共有 0 則留言