gpt4 book ai didi

git - 如何仅从给定提交中记录的文件中恢复几行?

转载 作者:IT王子 更新时间:2023-10-29 01:22:54 27 4
gpt4 key购买 nike

我想从旧提交中记录的文件中恢复几行。我可以通过运行看到这些行

git log -p

作为最后的手段,我准备简单地从该日志的输出中复制这些行,但这会伤害我的纯粹主义者的心并且看起来相当不专业。

只想运行git checkout <file>因为那会丢弃对 <file> 所做的本地更改自有问题的提交以来。相反,我想将该提交的更改 merge 到 <file> 中在工作树中仅使用纯 Git 命令。

我该怎么做?

最佳答案

使用交互式 checkout

以下git-checkout语法,

git checkout --patch <tree-ish> -- <paths>

或者,等价地,

git checkout -p <tree-ish> -- <paths>

允许您以交互方式检查一个或多个文件中的 hunk,这些文件列在 <paths> 中, 如记录在 <tree-ish> (最常见的是提交)。

参见 git-checkout man page了解更多详情。

例子

为了修正想法,这里有一个玩具示例(省略了不相关的标准输出):

# 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

关于git - 如何仅从给定提交中记录的文件中恢复几行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27336028/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com