8

这是我所做的:

  1. 编码 8 小时的更改。
  2. git status显示我的所有更改。
  3. git add -A
  4. git commit -m "Foo". 预提交 git 钩子使用huskyand触发lint-staged
  5. 我记得有一个我未能修复的 TypeScript 输入错误,所以我按 Ctrl+C 取消。
  6. 心不在焉,我又跑git commit -m "Foo"了一次,立即取消。
  7. 变化消失了!文件被还原,git status干净,git log并且git reflog不显示新的提交。

为什么我的更改被还原了?我该如何恢复它们?

第1步 第2步

4

2 回答 2

17

好吧,这是lint-staged罪魁祸首。它隐藏了我的更改。

所以跑步git stash apply恢复了他们!


⚠ 不要尝试lint-staged在同一个 git repo 上并行运行多个实例(例如在 monorepo 中的每个项目上)。这将破坏您的更改,而无法恢复它们。

如果你在 monorepo 上工作,要么按顺序 lint 项目,要么放弃lint-staged并 lint 整个代码库,包括未暂存的文件。

于 2020-02-21T08:58:11.153 回答
3

对于你们所有人:TL;DR
-选项 1 - 你提到你已经做了:使用git reflog&& git reset
-选项 2 - 使用你的编辑器历史
-选项 3 - 如果你添加了这些文件,从暂存区抓取它们,你需要找到他们

# Find all dangling files
git fsck --all

## Now use git cat-file -p to print those hashes
git cat-p <SHA-1>


完整答案:

在回答之前,让我们添加一些背景,解释这HEAD是什么。

First of all what is HEAD?

HEAD只是对当前分支上的当前提交(最新)的引用。在任何给定时间
只能有一个(不包括)。HEADgit worktree

的内容HEAD存储在里面.git/HEAD,它包含当前提交的 40 字节 SHA-1。


detached HEAD

如果您不在最新的提交上 - 意思HEAD是指向历史上的先前提交,则称为detached HEAD.

在此处输入图像描述

在命令行上,它看起来像这样 - SHA-1 而不是分支名称,因为HEAD它没有指向当前分支的尖端:

在此处输入图像描述

在此处输入图像描述


关于如何从分离的 HEAD 中恢复的一些选项:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

这将签出指向所需提交的新分支。
此命令将检出给定的提交。
此时,您可以创建一个分支并从这一点开始工作。

# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# Create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

您也可以随时使用reflog
git reflog将显示更新的任何更改,HEAD并检查所需的 reflog 条目将设置HEAD回此提交。

每次修改 HEAD 都会在reflog

git reflog
git checkout HEAD@{...}

这将使您回到所需的提交

在此处输入图像描述


git reset --hard <commit_id>

将您的 HEAD “移动”回所需的提交。

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.

git revert <sha-1>

“撤消”给定的提交或提交范围。
重置命令将“撤消”在给定提交中所做的任何更改。
将提交带有撤消补丁的新提交,而原始提交也将保留在历史记录中。

# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>

这个模式说明了哪个命令做什么。
如您所见,reset && checkout修改HEAD.

在此处输入图像描述

于 2020-02-21T08:56:04.420 回答