将两个补丁合并为一个补丁的算法?

Sam*_*ern 10 git diff patch

我正在尝试做一些我认为应该非常简单的事情,但已经变成了一个兔子洞,我认为一定有更好的方法。

想象一下,您有两个连续的补丁文件(代表连续的更改)到一个源文件,但您没有源文件本身。

如何将两个补丁组合成一个代表组合更改集的补丁。将组合补丁应用到源文件的结果应该与按顺序应用两个补丁的结果相同。应保留所有上下文

有没有一个众所周知的算法?

例子。拿这两个补丁

@@ -1,1 +1,2 @@
+ add this first line
this line is just context
Run Code Online (Sandbox Code Playgroud)
@@ -1,2 +1,2 @@
- add this first line
+ change the first line
this line is just context
@@ -7,2 +7,2 @@
context
- change this line
+ to this one
more context
Run Code Online (Sandbox Code Playgroud)

结果将是:

@@ -1,1 +1,2 @@
+ change the first line
this line is just context
@@ -7,2 +7,2 @@
context
- change this line
+ to this one
more context
Run Code Online (Sandbox Code Playgroud)

我为这个用例找到的唯一工具/库就是这个,但在测试中它有很多错误,而且代码太密集,我无法弄清楚底层算法是什么: https://github。 com/twaugh/patchutils

小智 2

首先我修复了补丁文件中的语法错误:

  • 补丁文件必须有文件头,所以我添加了---+++行。
  • 上下文行以单个空格开头,因此我添加了 它们。
  • 帅哥中的数字@@必须与后面的行匹配,因此我将 更改23以包含该more context行。

p1 现在是:

--- old
+++ new
@@ -1,1 +1,2 @@
+ add this first line
 this line is just context
Run Code Online (Sandbox Code Playgroud)

p2 现在是:

--- old
+++ new
@@ -1,2 +1,2 @@
- add this first line
+ change the first line
 this line is just context
@@ -7,3 +7,3 @@
 context
- change this line
+ to this one
 more context
Run Code Online (Sandbox Code Playgroud)

运行combinediff p1 p2结果是:

combinediff: hunk-splitting is required in this case, but is not yet implemented
combinediff: use the -U option to work around this
Run Code Online (Sandbox Code Playgroud)

运行combinediff -U1 p1 p2结果是:

diff -U1 new new
--- new
+++ new
@@ -1 +1,2 @@
+ change the first line
 this line is just context
@@ -6,3 +7,3 @@
 context
- change this line
+ to this one
 more context
Run Code Online (Sandbox Code Playgroud)

结果有两个地方与您的期望不同:

  • 生成的补丁有@@ -1而不是@@ -1,1. 这是允许的缩写。
  • 生成的补丁有@@ -6,3代替@@ -7,3,它正确地解释了第一个补丁添加的 1 行。

除了未实现的功能外,这看起来与我预期的完全一样。