删除行时应该如何编辑补丁签出?

How should I edit a patch checkout when removing lines?

我有一个文件 bar.txt,我在其中删除了 3 行并且还没有暂存任何内容。我想通过 git checkout -p.

恢复删除的行之一

Example/Bash 输出:

$ git checkout -p foo/bar.txt
diff --git a/bin/custom/foo/bar.txt b/bin/custom/foo/bar.txt
index 35483b7..e945cae 100644
--- a/bin/custom/foo/bar.txt
+++ b/bin/custom/foo/bar.txt
@@ -1097,9 +1097,6 @@ mond.desc.refinements   = Foo
 mond.desc.removeAttribute                    = Foo
 mond.desc.resultsForStore                    = Foo
 mond.no.results                              = Foo
-mond.page.CO.class.name                      = Foo
-mond.page.CO.parent.name                     = Foo
-mond.page.brands.parent.name                 = Foo
 mond.page.cmscontent.datetime                = Foo
 mond.page.currentPage                        = Foo
 mond.page.firstPage                          = Foo

我试过类似的东西:

@@ -1097,9 +1097,8 @@ mond.desc.refinements   = Foo
 mond.desc.removeAttribute                    = Foo
 mond.desc.resultsForStore                    = Foo
 mond.no.results                              = Foo
-mond.page.CO.class.name                      = Foo
 mond.page.CO.parent.name                     = Foo
 mond.page.brands.parent.name                 = Foo
 mond.page.cmscontent.datetime                = Foo
 mond.page.currentPage                        = Foo
 mond.page.firstPage                          = Foo

但是不行。

我可能会从另一个方向着手。不用费心去 git add -p 想要 的更改,提交它们,然后 git checkout . 清除其他内容。如果您实际上还不想提交,只需 git reset HEAD^ 撤消我们刚刚所做的提交,将保留的更改留在您的工作区中。

但这不是你问的,也不是很有趣,所以...


这令人困惑,因为双重否定并不令人困惑,但如果你动动脑筋,你就可以解决它。

假设我们有文件 numbers,其中包含:

one
two
three
four

我们删除 twothree,所以 git diff 看起来像:

diff --git a/numbers b/numbers
index f384549..a9c7698 100644
--- a/numbers
+++ b/numbers
@@ -1,4 +1,2 @@
 one
-two
-three
 four

现在我们运行git checkout -p numbers。请注意,提示询问您是否要 丢弃 减去 twothree 的大块。如果你说 y,它会放弃减法,为你留下一个包含所有四个数字的完整文件。

 one
-two
-three
 four
Discard this hunk from worktree [y,n,q,a,d,/,e,?]?

现在我们将编辑大块头以创建我们想要丢弃的大块头。这意味着如果我们实际上只想删除 two,我们想要丢弃删除 three 的更改。与直觉相反,这意味着您可以通过 删除 -two.

来编辑帅哥
@@ -1,4 +1,2 @@
 one
-three
 four

这会丢弃 three 的删除,并且不会丢弃 two 的删除,留下差异:

diff --git a/numbers b/numbers
index f384549..ceb5927 100644
--- a/numbers
+++ b/numbers
@@ -1,4 +1,3 @@
 one
-two
 three
 four

总而言之,从大块头中删除您仍想删除的行。保留要丢弃的减法线。您编辑的 hunk 将包含您保留的行的减法(将被丢弃),并且不会包含您仍想删除的行。