你想的是正确的方向。
为此目的使用
require 'git' g = Git.open('path/to/dir') g.diff('your.file').patch #=> changes in your.file
例如,我们有空文件 git.rb 和 smth 在我们的git-repo中。
git.rb
smth
然后我们改变它们并检查差异:
$ git diff diff --git a/git.rb b/git.rb index e69de29..3ff224d 100644 --- a/git.rb +++ b/git.rb @@ -0,0 +1,3 @@ +require 'git' +g = Git.open(__dir__) +puts g.diff('smth').patch diff --git a/smth b/smth index e69de29..7c5bd35 100644 --- a/smth +++ b/smth @@ -0,0 +1 @@ +we want to know changes
正如已经修改过的猜测 git.rb ,现在我们只会看到变化 smth :
$ ruby git.rb diff --git a/smth b/smth index e69de29..7c5bd35 100644 --- a/smth +++ b/smth @@ -0,0 +1 @@ +we want to know changes
如果没有变化,您将获得空字符串 "" 。
""
您可能希望直接使用McIlroy-Hunt最长公共子序列(LCS)算法,而不是使用它的派生/包装。
看到 https://github.com/halostatue/diff-lcs
如果您比较a与b的变化而不是b与a的变化相比,差异将会改变,但您可以针对数组运行它 的 要么 强> 当然,反对整个文件。
如果你喜欢它而不是使用它的直接输出,gem也有经典的diff工具格式(由diff或git使用)。