我想从旧提交中记录的文件中恢复几行。我可以通过运行
来查看这些行git log -p
作为最后的手段,我准备简单地从该日志的输出中复制这些行,但这会伤害我的纯粹主义者的心脏,而且看起来相当不专业。
我不想要简单地运行git checkout <file>
,因为这会丢弃自问题提交以来对<file>
所做的本地更改。相反,我想仅使用纯Git命令将工作树中来自该提交的更改合并到<file>
。
我该怎么做?
答案 0 :(得分:17)
以下git-checkout
语法,
git checkout --patch <tree-ish> -- <paths>
或等同地
git checkout -p <tree-ish> -- <paths>
允许您以交互方式检查<paths>
中列出的<tree-ish>
中列出的一个或多个文件中的数据库(最常见的是提交)。
有关详细信息,请参阅git-checkout
man page。
为了解决问题,这里有一个玩具示例(省略了无关的stdout):
# set things up
$ mkdir test
$ cd test
$ git init
# create some content and commit
$ printf "Hello, world.\n" > README.md
$ printf "foo\nbar\nbaz\n" > test.txt
$ git add .
$ git commit -m "initial commit"
# modify the working tree
$ printf "another line\n" >> README.md
$ printf "foo\nfoo\n" > test.txt
# now restore stuff from test.txt as recorded in master's tip
$ git checkout -p master -- test.txt
diff --git b/test.txt a/test.txt
index 0d55bed..86e041d 100644
--- b/test.txt
+++ a/test.txt
@@ -1,2 +1,3 @@
foo
-foo
+bar
+baz
Apply this hunk to index and worktree [y,n,q,a,d,/,e,?]? y
error: patch failed: test.txt:1
error: test.txt: patch does not apply
The selected hunks do not apply to the index!
Apply them to the worktree anyway? y
# Sanity check: inspect the working tree
# (the hunk "bar\nbaz" from test.txt was restored, as desired)
$ cat test.txt
foo
bar
baz
# (README.md, on the other hand, was not affected, as desired)
$ cat README.md
Hello, world.
another line
答案 1 :(得分:2)
如果在较早的提交中您只更改了此文件,并且您想要撤消所有这些更改, 然后简单地做:
git revert SHA
如果有多个文件,这里是一个纯git
(并不是很好)的解决方案:
git revert SHA --no-commit
git reset
git add path/to/file
git checkout .
git commit
或git
+ patch
解决方案(也不是很好):
git diff -p SHA path/to/file > patch
patch -R < patch
git commit .