File: diff.rb

package info (click to toggle)
ruby-unparser 0.6.13-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 936 kB
  • sloc: ruby: 7,691; sh: 6; makefile: 4
file content (98 lines) | stat: -rw-r--r-- 1,865 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# frozen_string_literal: true

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

    ADDITION = '+'
    DELETION = '-'
    NEWLINE  = "\n"

    # Unified source diff between old and new
    #
    # @return [String]
    #   if there is exactly one diff
    #
    # @return [nil]
    #   otherwise
    def diff
      return if diffs.empty?

      minimized_hunk.diff(:unified) + NEWLINE
    end
    memoize :diff

    # Colorized unified source diff between old and new
    #
    # @return [String]
    #   if there is a diff
    #
    # @return [nil]
    #   otherwise
    def colorized_diff
      return unless diff

      diff.lines.map(&self.class.method(:colorize_line)).join
    end
    memoize :colorized_diff

    # Build new object from source strings
    #
    # @param [String] old
    # @param [String] new
    #
    # @return [Diff]
    def self.build(old, new)
      new(lines(old), lines(new))
    end

    # Break up source into lines
    #
    # @param [String] source
    #
    # @return [Array<String>]
    def self.lines(source)
      source.lines.map(&:chomp)
    end
    private_class_method :lines

  private

    def diffs
      ::Diff::LCS.diff(old, new)
    end

    def hunks
      diffs.map do |diff|
        ::Diff::LCS::Hunk.new(old.map(&:dup), new, diff, max_length, 0)
      end
    end

    def minimized_hunk
      head, *tail = hunks

      tail.reduce(head) do |left, right|
        right.merge(left)
        right
      end
    end

    def max_length
      [old, new].map(&:length).max
    end

    def self.colorize_line(line)
      case line[0]
      when ADDITION
        Color::GREEN
      when DELETION
        Color::RED
      else
        Color::NONE
      end.format(line)
    end
    private_class_method :colorize_line

  end # Diff
end # Unparser