gitgrit

Grit: how to to tell between two commits which is newer?


I'd like to be able to tell between two Grit::Commit objects, which is newer. What I mean by newer is that if commit_A is a parent (or parent of a parent,etc) of commit_B, then commit_B is newer. This assumes that commit_A and commit_B are on the same branch.

I thought about using Grit::Commit#date(), but I think this'll be inaccurate.

Any ideas?


Solution

  • Here is what I ended up implementing. See comments for explanation.

    Performance is dog slow, but it was worse when using repo.git.rev_list(via method_missing).

    require 'grit'
    
    module Grit
    
        class Commit
    
            # Returns true if any commits in +commits+ are decendants of calling commit. True
            # means that one or more commits in +commits+ are newer.
            def has_decendant_in? *commits 
                total_commits = commits.flatten
                raise ArgumentError "at least one commit required." if total_commits.empty?
                total_commits.each do |commit|
                    return true if repo.commits_between(commit.id, id).empty?
                end
                return false
            end
    
            # Returns an Array of commits which tie for being the newest commits. Ties can
            # occur when commits are in different branches.
            def self.newest *commits
                oldest_commits = []
                total_commits = commits.flatten
                raise ArgumentError "at least one commit required." if total_commits.empty?
                (total_commits).each do |commit|
                    if commit.has_decendant_in?(total_commits - [commit])
                        oldest_commits << commit 
                    end
                end
                return total_commits - oldest_commits
            end
    
        end
    
    end