如何为坚固的提交选择合适的diff / patch

时间:2016-11-05 11:13:33

标签: ruby git rugged

我尝试获取在git repo的本地副本中的日期之后完成的提交,然后提取文件的相关修改。

如果我想将它与git命令进行比较,那将是:

git log -p --reverse --after="2016-10-01"

这是我使用的脚本:

require "rugged"
require "date"

git_dir = "../ruby-gnome2/"

repo = Rugged::Repository.new(git_dir)
walker = Rugged::Walker.new(repo)
walker.sorting(Rugged::SORT_DATE| Rugged::SORT_REVERSE)
walker.push(repo.head.target)

walker.each do |commit|
  c_time = Time.at(commit.time)
  next unless c_time >= Date.new(2016,10,01).to_time

    puts c_time
    puts commit.diff.size
    puts commit.diff.stat.inspect
end

问题是看起来这里修改了很多文件是这个脚本输出的结尾:

2016-10-22 17:33:37 +0200
2463
[2463, 0, 271332]

这意味着有2463个文件被修改/删除/替换。虽然git log -p --reverse --after="2016-10-22"显示只修改了2个文件。

如何获得与git命令相同的结果?即如何找到由此提交修改的真实文件?

1 个答案:

答案 0 :(得分:1)

由于我没有得到崎岖团队的任何回答,我已经为libgit2-glib https://github.com/ruby-gnome2/ggit做了一个ruby gobject-introspection加载器。

现在我可以找到与git命令行界面对应的diff和日志:

require "ggit"

PATH = File.expand_path(File.dirname(__FILE__))

repo_path = "#{PATH}/ruby-gnome2/.git"

file = Gio::File.path(repo_path)

begin
  repo = Ggit::Repository.open(file)
  revwalker = Ggit::RevisionWalker.new(repo)
  revwalker.sort_mode = [:time, :topological, :reverse]
  head = repo.head
  revwalker.push(head.target)
rescue => error
  STDERR.puts error.message
  exit 1
end

def signature_to_string(signature)
  name = signature.name
  email = signature.email
  time = signature.time.format("%c")

  "#{name} <#{email}> #{time}"
end

while oid = revwalker.next do
  commit = repo.lookup(oid, Ggit::Commit.gtype)

  author = signature_to_string(commit.author)
  date = commit.committer.time
  next unless (date.year >= 2016 && date.month >= 11 && date.day_of_month > 5)
  committer = signature_to_string(commit.committer)

  subject = commit.subject
  message = commit.message

  puts "SHA: #{oid}"
  puts "Author:  #{author}"
  puts "Committer: #{committer}"
  puts "Subject: #{subject}"
  puts "Message: #{message}"
  puts "----------------------------------------"

  commit_parents = commit.parents
  if commit_parents.size > 0
    parent_commit = commit_parents.get(0)
    commit_tree = commit.tree
    parent_tree = parent_commit.tree

    diff = Ggit::Diff.new(repo, :old_tree => parent_tree,
                          :new_tree => commit_tree, :options => nil)

    diff.print( Ggit::DiffFormatType::PATCH ).each do |_delta, _hunk, line|
      puts "\t | #{line.text}"
      0
    end

  end

end