Skip to content

Commit

Permalink
Merge pull request #99 from dark-panda/fix-diffs-with-dashes-and-pluses
Browse files Browse the repository at this point in the history
Fix diff lines that begin with -- or ++
  • Loading branch information
Sam Goldstein authored Dec 30, 2018
2 parents 027effe + c71e806 commit 08f3340
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
21 changes: 16 additions & 5 deletions lib/diffy/diff.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def initialize(string1, string2, options = {})

def diff
@diff ||= begin
paths = case options[:source]
@paths = case options[:source]
when 'strings'
[tempfile(string1), tempfile(string2)]
when 'files'
Expand All @@ -51,10 +51,10 @@ def diff

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

def each
lines = case @options[:include_diff_info]
when false then diff.split("\n").reject{|x| x =~ /^(---|\+\+\+|@@|\\\\)/ }.map {|line| line + "\n" }
when true then diff.split("\n").map {|line| line + "\n" }
when false
# this "primes" the diff and sets up the paths we'll reference below.
diff

# caching this regexp improves the performance of the loop by a
# considerable amount.
regexp = /^(--- "?#{@paths[0]}"?|\+\+\+ "?#{@paths[1]}"?|@@|\\\\)/

diff.split("\n").reject{|x| x =~ regexp }.map {|line| line + "\n" }

when true
diff.split("\n").map {|line| line + "\n" }
end

if block_given?
lines.each{|line| yield line}
else
Expand Down
24 changes: 24 additions & 0 deletions spec/diffy_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,30 @@ def tempfile(string, fn = 'diffy-spec')
line
end).to eq([" foo\n", " bar\n", "+baz\n"])
end

it "should handle lines that begin with --" do
string1 = "a a\n-- b\nc c\n"
string2 = "a a\nb b\nc c\n"

expect(Diffy::Diff.new(string1, string2).to_s).to eq <<-DIFF
a a
--- b
+b b
c c
DIFF
end

it "should handle lines that begin with ++" do
string1 = "a a\nb b\nc c\n"
string2 = "a a\n++ b\nc c\n"

expect(Diffy::Diff.new(string1, string2).to_s).to eq <<-DIFF
a a
-b b
+++ b
c c
DIFF
end
end
end

Expand Down

0 comments on commit 08f3340

Please sign in to comment.