Skip to content

Commit 08f3340

Browse files
author
Sam Goldstein
authored
Merge pull request #99 from dark-panda/fix-diffs-with-dashes-and-pluses
Fix diff lines that begin with -- or ++
2 parents 027effe + c71e806 commit 08f3340

File tree

2 files changed

+40
-5
lines changed

2 files changed

+40
-5
lines changed

lib/diffy/diff.rb

+16-5
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def initialize(string1, string2, options = {})
4242

4343
def diff
4444
@diff ||= begin
45-
paths = case options[:source]
45+
@paths = case options[:source]
4646
when 'strings'
4747
[tempfile(string1), tempfile(string2)]
4848
when 'files'
@@ -51,10 +51,10 @@ def diff
5151

5252
if WINDOWS
5353
# don't use open3 on windows
54-
cmd = sprintf '"%s" %s %s', diff_bin, diff_options.join(' '), paths.map { |s| %("#{s}") }.join(' ')
54+
cmd = sprintf '"%s" %s %s', diff_bin, diff_options.join(' '), @paths.map { |s| %("#{s}") }.join(' ')
5555
diff = `#{cmd}`
5656
else
57-
diff = Open3.popen3(diff_bin, *(diff_options + paths)) { |i, o, e| o.read }
57+
diff = Open3.popen3(diff_bin, *(diff_options + @paths)) { |i, o, e| o.read }
5858
end
5959
diff.force_encoding('ASCII-8BIT') if diff.respond_to?(:valid_encoding?) && !diff.valid_encoding?
6060
if diff =~ /\A\s*\Z/ && !options[:allow_empty_diff]
@@ -84,9 +84,20 @@ def diff
8484

8585
def each
8686
lines = case @options[:include_diff_info]
87-
when false then diff.split("\n").reject{|x| x =~ /^(---|\+\+\+|@@|\\\\)/ }.map {|line| line + "\n" }
88-
when true then diff.split("\n").map {|line| line + "\n" }
87+
when false
88+
# this "primes" the diff and sets up the paths we'll reference below.
89+
diff
90+
91+
# caching this regexp improves the performance of the loop by a
92+
# considerable amount.
93+
regexp = /^(--- "?#{@paths[0]}"?|\+\+\+ "?#{@paths[1]}"?|@@|\\\\)/
94+
95+
diff.split("\n").reject{|x| x =~ regexp }.map {|line| line + "\n" }
96+
97+
when true
98+
diff.split("\n").map {|line| line + "\n" }
8999
end
100+
90101
if block_given?
91102
lines.each{|line| yield line}
92103
else

spec/diffy_spec.rb

+24
Original file line numberDiff line numberDiff line change
@@ -585,6 +585,30 @@ def tempfile(string, fn = 'diffy-spec')
585585
line
586586
end).to eq([" foo\n", " bar\n", "+baz\n"])
587587
end
588+
589+
it "should handle lines that begin with --" do
590+
string1 = "a a\n-- b\nc c\n"
591+
string2 = "a a\nb b\nc c\n"
592+
593+
expect(Diffy::Diff.new(string1, string2).to_s).to eq <<-DIFF
594+
a a
595+
--- b
596+
+b b
597+
c c
598+
DIFF
599+
end
600+
601+
it "should handle lines that begin with ++" do
602+
string1 = "a a\nb b\nc c\n"
603+
string2 = "a a\n++ b\nc c\n"
604+
605+
expect(Diffy::Diff.new(string1, string2).to_s).to eq <<-DIFF
606+
a a
607+
-b b
608+
+++ b
609+
c c
610+
DIFF
611+
end
588612
end
589613
end
590614

0 commit comments

Comments
 (0)