Sha256: dbfd7a67a97495e27dc070dd64df7fd12a2a9e521e86488f865494f2ef589f34

Contents?: true

Size: 1.88 KB

Versions: 4

Compression:

Stored size: 1.88 KB

Contents

module Mutant
  # Class to create diffs from source code
  class Diff
    include Adamantium::Flat, Concord.new(:old, :new)

    # Return source diff
    #
    # @return [String]
    #   if there is exactly one diff
    #
    # @return [nil]
    #   otherwise
    #
    # @api private
    #
    def diff
      return unless diffs.length.equal?(1)
      ::Diff::LCS::Hunk.new(old, new, diffs.first, max_length, 0)
        .diff(:unified) << "\n"
    end
    memoize :diff

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

    # Return new object
    #
    # @param [String] old
    # @param [String] new
    #
    # @return [Diff]
    #
    # @api private
    #
    def self.build(old, new)
      new(lines(old), lines(new))
    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
    private_class_method :lines

  private

    # Return diffs
    #
    # @return [Array<Array>]
    #
    # @api private
    #
    def diffs
      ::Diff::LCS.diff(old, new)
    end
    memoize :diffs

    # Return max length
    #
    # @return [Fixnum]
    #
    # @api private
    #
    def max_length
      [old, new].map(&:length).max
    end

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

  end # Diff
end # Mutant

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
mutant-0.5.23 lib/mutant/diff.rb
mutant-0.5.22 lib/mutant/diff.rb
mutant-0.5.21 lib/mutant/diff.rb
mutant-0.5.20 lib/mutant/diff.rb