Method: Leg::Diff.parse

Defined in:
lib/leg/diff.rb

.parse(git_diff) ⇒ Object

Parse a git diff and return an array of Diff objects, one for each file in the git diff.



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
# File 'lib/leg/diff.rb', line 51

def self.parse(git_diff)
  in_diff = false
  old_line_num = nil
  new_line_num = nil
  cur_diff = nil
  diffs = []

  git_diff.lines.each do |line|
    if line =~ /^--- (.+)$/
      cur_diff = Leg::Diff.new
      if $1 == '/dev/null'
        cur_diff.is_new_file = true
      end
      diffs << cur_diff
      in_diff = false
    elsif line =~ /^\+\+\+ (.+)$/
      cur_diff.filename = $1.strip.sub(/^b\//, '')
    elsif line =~ /^@@ -(\d+)(,\d+)? \+(\d+)(,\d+)? @@/
      # TODO: somehow preserve function name that comes to the right of the @@ header?
      in_diff = true
      old_line_num = $1.to_i
      new_line_num = $3.to_i
    elsif in_diff && line[0] == '\\'
      # Ignore "\ No newline at end of file".
    elsif in_diff && [' ', '|', '+', '-'].include?(line[0])
      case line[0]
      when ' ', '|'
        line_nums = [old_line_num, new_line_num]
        old_line_num += 1
        new_line_num += 1
        cur_diff << Leg::Line::Unchanged.new(line[1..-1], line_nums)
      when '+'
        line_nums = [nil, new_line_num]
        new_line_num += 1
        cur_diff << Leg::Line::Added.new(line[1..-1], line_nums)
      when '-'
        line_nums = [old_line_num, nil]
        old_line_num += 1
        cur_diff << Leg::Line::Removed.new(line[1..-1], line_nums)
      end
    else
      in_diff = false
    end
  end

  diffs
end