简体   繁体   中英

How to parse git diff of specific file using Ruby?

I have an Android XML (string) file that is edited in a Ruby script. I would like to list and output the changes that were made then. I have tried it with Nokogiri and nokogiri/diff . But it does not have the desired result.

I also have the feeling that it has problems when a new line is added in the middle of it. All in all, I think it would be easiest if I could use git diff .

I've also found ruby-git gem, but I still could not get it to work. Especially because I only need the diff of a specific file.

require 'git'

Git.configure do |config|
 #not sure if I actually need something?
end

g = Git.open(path_to_my_dir, :log => Logger.new(STDOUT))    
g.diff(path_to_file)
#or
g.diff().path(path_to_file)

Can Someone please help me out? :-(

You thought in the right direction.

For this purpose use

require 'git'
g = Git.open('path/to/dir')
g.diff('your.file').patch #=> changes in your.file

For example we had empty files git.rb and smth in our git-repo.

Then we changed them and checked difference:

$ 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

As already guessed from modified git.rb , now we will see changes only in 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

In case there are no changes, you will get empty string "" .

You might want to use the McIlroy-Hunt longest common subsequence (LCS) algorithm directly instead of using derivates/wrappers of it.

See https://github.com/halostatue/diff-lcs

The diff will change if you compare changes of a vs. b as opposed to changes of b vs. a, but you can run it against an array or against a whole file of course.

The gem also has the classic diff tool formatting (used by diff or git) if you prefer that instead of using its direct output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM