我的 git 仓库里保存了一个小补丁。 我用 git stash apply
把它应用到了我的工作拷贝。 现在,我想通过反向应用补丁(有点像 git revert
所做的,但针对的是储藏库)来撤销这些改动。
有人知道怎么做吗?
说明: 我的工作副本中还有其他改动。 我的具体情况很难描述,但你可以想象一些调试或实验代码,它们都在储藏库中。 现在,我的工作副本中混入了这些代码和其他改动,我想看看这些改动与不改动时的效果。
目前看来 stash 并不支持这个功能,但如果有一个 git stash apply --reverse
功能就更好了。
根据git-stash手册,"储藏库表示为一个提交,其树状结构记录了工作目录的状态,它的第一个父提交是创建储藏库时位于HEAD
的提交,"而git stash show -p
则以储藏库状态与原始父提交之间的差值来显示储藏库中记录的更改。
要保持其他改动不变,请使用 git stash show -p | patch --reverse
,如下所示:
$ git init
Initialized empty Git repository in /tmp/repo/.git/
$ echo Hello, world >messages
$ git add messages
$ git commit -am 'Initial commit'
[master (root-commit)]: created 1ff2478: "Initial commit"
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 messages
$ echo Hello again >>messages
$ git stash
$ git status
# On branch master
nothing to commit (working directory clean)
$ git stash apply
# On branch master
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: messages
#
no changes added to commit (use "git add" and/or "git commit -a")
$ echo Howdy all >>messages
$ git diff
diff --git a/messages b/messages
index a5c1966..eade523 100644
--- a/messages
+++ b/messages
@@ -1 +1,3 @@
Hello, world
+Hello again
+Howdy all
$ git stash show -p | patch --reverse
patching file messages
Hunk #1 succeeded at 1 with fuzz 1.
$ git diff
diff --git a/messages b/messages
index a5c1966..364fc91 100644
--- a/messages
+++ b/messages
@@ -1 +1,2 @@
Hello, world
+Howdy all
编辑:
一个小改进是用 git apply
代替 patch:
git stash show -p | git apply --reverse
或者,也可以使用 git apply -R
作为 git apply --reverse
的简写。
我最近发现这真的很方便...
git stash`[save]
会将工作目录状态和索引状态保存起来,并将索引和工作区设置为 HEAD
版本。
git stash apply
会恢复这些更改,因此 git reset --hard
会再次删除它们。
git stash pop
会带回这些改动,并移除顶层存储的改动,因此在这种情况下,git stash [save]
会返回到先前(pop 之前)的状态。
这个问题早就该解决了,但如果我的理解正确的话,我已经找到了一个简单的解决方案,注意,这是用我自己的术语解释的:
git stash [save]` 会保存当前更改,并将当前分支设置为 "干净状态";
git stash list
会给出类似的信息:stash@{0}:On develop: saved testing-stuff
git apply stash@{0}
会将当前分支设置为 before stash [save]
git checkout .
会将当前分支设置为afterstash[save]
。
保存在 stash 中的代码不会丢失,可以通过 git apply stash@{0}
再次找到。
总之,这个方法很有效!