如何从 git 上丢失的提交中恢复代码?

zac*_*ode 3 git

我使用 回滚到之前的提交git checkout "commit number1"。然后我没有意识到我正在提交而不是在任何分支上,所以我在这里进行了更改并将代码提交到"commit number1". 现在我切换到功能分支。feature/branch1我没有看到任何代码。如果我切换回"commit Number1",我也看不到那里的代码。我是否脱离了任何事物?

$ git checkout 49da8b4d431

Note: checking out '49da8b4d431'.

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
Run Code Online (Sandbox Code Playgroud)

我怎样才能恢复代码?我的代码去哪儿了?

Tim*_*sen 6

输入git reflog它将显示所有最近提交的列表。找到消息为 的提交"commit number1",然后记录该提交的 SHA-1 哈希值(看起来像 7 个字符的随机字母数字字符串,例如s73nd9a)。

要将此提交引入您的功能分支,一种选择是使用git cherry-pick. 请尝试以下操作:

git checkout feature/branch1
git cherry-pick s73nd9a
Run Code Online (Sandbox Code Playgroud)

这将应用您在分离头状态下所做的单个提交。请记住,樱桃选择本质上是一次提交的合并,因此您可能会遇到冲突。