gitlibgit2rugged

Iterate with Ruby through git commits for a particular branch


I'd like to use Rugged to iterate through all the commits on a particular branch, from the oldest (first) to the newest (last). I'd like to examine the SHA1 and the comment for each.

Maybe I'm better off just running 'git log --reverse' and parsing the results, but as long as there's this nice Ruby library for working with Git I figure I'll use it.

Forgive me but I can't quite figure out how to do what I want from the Rugged or libgit2 docs.


Solution

  • You can create a commit walker, something like this:

    require 'rugged'
    
    repo = Rugged::Repository.new('/path/for/your/repo')
    walker = Rugged::Walker.new(repo)
    walker.sorting(Rugged::SORT_REVERSE)
    walker.push(repo.branches["master"].target_id)
    
    walker.each do |commit| 
      puts "commit #{commit.oid}"
      puts "Author: #{commit.author[:name]} <#{commit.author[:email]}>"
      puts "Date:   #{commit.author[:time]}"
      puts "\n    #{commit.message}\n"
    end
    walker.reset
    

    You can check the documentation and read the testing code in the repository to see what you can do with Rugged.