Sha256: 03bd31f9d8c3eb48a52c3235128fb316acbb5f168ac476a5faa2e975f1116be1

Contents?: true

Size: 1.79 KB

Versions: 8

Compression:

Stored size: 1.79 KB

Contents

module Mutant
  # Class to create diffs from source code
  class Differ
    include Adamantium::Flat

    # Return source diff 
    #
    # @return [String]
    #
    # @api private
    #
    def diff
      output = ''
      @diffs.each do |piece|
        hunk = Diff::LCS::Hunk.new(@old, @new, piece, CONTEXT_LINES, length_difference)
        output << hunk.diff(FORMAT)
        output << "\n"
      end
      output
    end
    memoize :diff

    # Return colorized source diff 
    #
    # @return [String]
    #
    # @api private
    #
    def colorized_diff
      diff.lines.map do |line|
        self.class.colorize_line(line)
      end.join
    end
    memoize :colorized_diff

  private

    FORMAT = :unified
    CONTEXT_LINES = 3

    # Initialize differ object
    #
    # @param [String] old 
    # @param [String] new
    #
    # @return [undefined]
    #
    # @api private
    #
    def initialize(old, new)
      @old, @new = self.class.lines(old), self.class.lines(new)
      @diffs = Diff::LCS.diff(@old, @new)
    end

    # Return length difference
    #
    # @return [Fixnum]
    #
    # @api private
    #
    def length_difference
      @new.size - @old.size
    end

    # Break up source into lines
    #
    # @param [String] source
    #
    # @return [Array<String>]
    #
    # @api private
    #
    def self.lines(source)
      source.lines.map { |line| line.chomp }
    end

    # Return colorized diff line
    #
    # @param [String] line
    #
    # @return [String]
    #   returns colorized line
    #
    # @api private
    #
    def self.colorize_line(line)
      case line[0].chr
      when '+'
        Color::GREEN
      when '-'
        Color::RED
      when '@'
        line[1].chr == '@' ? Color::BLUE : Color::NONE
      else
        Color::NONE
      end.format(line)
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
mutant-0.2.7 lib/mutant/differ.rb
mutant-0.2.6 lib/mutant/differ.rb
mutant-0.2.5 lib/mutant/differ.rb
mutant-0.2.4 lib/mutant/differ.rb
mutant-0.2.3 lib/mutant/differ.rb
mutant-0.2.2 lib/mutant/differ.rb
mutant-0.2.1 lib/mutant/differ.rb
mutant-0.2.0 lib/mutant/differ.rb