超级面板
文章目录
最新文章
最近更新
文章分类
标签列表
文章归档

Git restore - 撤销操作

在开发中,通常会使用 git checkout 进行分支切换和变更撤销,checkout 是一个比较复杂的命令,承载了很多功能有点臃肿,因此引入了两个新的命令 git switchgit restore 用来拆分 git checkout 命令,本文介绍如何使用 git restore 进行变更撤销。

介绍

git restore 命令会将指定文件的变更给撤销,先来看下面的示例:

在 git 仓库里有三个文件变更 restore.mdrestore2.mdrestore3.mdrestore.md 的变更已经通过 git add 加入暂存区,restore2.md 变更未加入暂存区,restore3.md 是新建的文件还未被 git 追踪:

$ git status

On branch restore
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: restore.md

Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: restore2.md

Untracked files:
(use "git add <file>..." to include in what will be committed)
restore3.md

通过 git status 可以看到很明显的提示,对于已经加入暂存区的变更(上面的restore.md),可以通过 git restore --staged <file>... 进行撤销变更,对于未加入暂存区的文件变更(上面的restore2.mdgit restore <file>... ,对于未追踪的文件,没有 git 操作提示,直接删除即可。

分别进行上面说的操作来看看:

$ git restore --staged restore.md
$ git restore restore2.md
$ rm restore.md
$ git status

On branch restore
nothing to commit, working tree clean

可以看到工作区的所有变更已经被撤销。

默认情况下,它们都是回滚到最新的提交状态,如果需要回滚到指定提交的内容,可以使用 --source=<tree>

首先来创造一个变更的提交:

$ cat restore.md

test retore.

$ echo test retore2 > restore.md

$ cat restore.md

test retore2

回滚内容到历史最开始的状态:

$ git log --oneline

50980a7 (HEAD -> restore) init

$ git restore --source=50980a7 --worktree restore.md

$ cat restore.md

test retore.

上面的是操作都是针对没有提交的情况,如果某个变更已经被提交了,也可以使用 git restore --source=<tree> <pathspec>…​ 进行内容回滚:

$ git log --oneline

7dc813a (HEAD -> restore) test2 # test restore2
50980a7 init # test restore

$ cat restore.md
test retore2

$ git restore -s 50980a7 restore.md

$ cat restore.md

test retore

注意,这个回滚只是内容回滚,相当于把上次内容写到文件里,仍然需要重新提交才能应用,而且错误的提交依然存在

$ git log --oneline

7dc813a (HEAD -> restore) error
50980a7 init

$ git status
On branch restore
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: restore.md

no changes added to commit (use "git add" and/or "git commit -a")

总结

这里对它们使用做个总结:

  • git restore --staged <file>...:撤销已经加入暂存区的变更;
  • git restore [--worktree|-w] <file>...:撤销未加入暂存区的变更;
  • git restore [--source|-s] tree <file>...:回退到指定的提交历史。

参考