Skip to content

Commit 6c335b8

Browse files
committed
diff preview
1 parent 05f658c commit 6c335b8

File tree

1 file changed

+32
-4
lines changed

1 file changed

+32
-4
lines changed

lib/approvals/approval.rb

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,35 @@ def verify
4545
fail_with "Approval file \"#{approved_path}\" not found."
4646
end
4747

48+
@approved_content, @received_content = read_content
49+
4850
unless received_matches?
49-
fail_with "Received file \"#{received_path}\" does not match approved \"#{approved_path}\"."
51+
fail_with "Received file does not match approved:\n"+
52+
"#{received_path}\n#{approved_path}\n#{diff_preview}"
5053
end
5154

5255
success!
5356
end
5457

58+
def diff_preview
59+
approved, received = diff_lines
60+
return unless approved and received
61+
diff_index =
62+
approved.each_char.with_index.find_index do |approved_char, i|
63+
approved_char != received[i]
64+
end
65+
"approved fragment: #{approved[diff_index - 10 .. diff_index + 30]}\n"+
66+
"received fragment: #{received[diff_index - 10 .. diff_index + 30]}"
67+
end
68+
69+
def diff_lines
70+
approved = @approved_content.split("\n")
71+
received = @received_content.split("\n")
72+
approved.each_with_index do |line, i|
73+
return line, received[i] unless line == received[i]
74+
end
75+
end
76+
5577
def success!
5678
File.delete received_path
5779
end
@@ -62,14 +84,20 @@ def approved?
6284

6385
BINARY_FORMATS = [:binary]
6486

65-
def received_matches?
87+
def read_content
6688
if BINARY_FORMATS.include?(@format) # Read without ERB
67-
IO.read(received_path).chomp == IO.read(approved_path).chomp
89+
[IO.read(approved_path).chomp,
90+
IO.read(received_path).chomp]
6891
else
69-
ERB.new(IO.read(received_path).chomp).result == ERB.new(IO.read(approved_path).chomp).result
92+
[ERB.new(IO.read(approved_path).chomp).result,
93+
ERB.new(IO.read(received_path).chomp).result]
7094
end
7195
end
7296

97+
def received_matches?
98+
@approved_content == @received_content
99+
end
100+
73101
def fail_with(message)
74102
Dotfile.append(diff_path)
75103

0 commit comments

Comments
 (0)