Skip to content

Commit a8f87bd

Browse files
committed
Convert non UTF-8 string to avoid invalid UTF-8 sequence errors
1 parent 6ec2020 commit a8f87bd

4 files changed

Lines changed: 30 additions & 1 deletion

File tree

lib/git_diff_parser/patches.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def self.parse(contents)
1818
line_count = lines.count
1919
parsed = new
2020
lines.each_with_index do |line, count|
21-
case line.chomp
21+
case parsed.scrub_string(line.chomp)
2222
when /^diff/
2323
unless patch.empty?
2424
parsed << Patch.new(patch.join("\n") + "\n", file: file_name)
@@ -42,6 +42,15 @@ def self.parse(contents)
4242
parsed
4343
end
4444

45+
# @return [String]
46+
def scrub_string(line)
47+
if RUBY_VERSION >= '2.1'
48+
line.scrub
49+
else
50+
line.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
51+
end
52+
end
53+
4554
# @return [Patches<Patch>]
4655
def initialize(*args)
4756
super Array.new(*args)

spec/git_diff_parser/patches_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ module GitDiffParser
1111
let(:body2) { File.read('spec/support/fixtures/file2.diff') }
1212
let(:file3) { 'lib/saddler/reporter/github/support.rb' }
1313
let(:body3) { File.read('spec/support/fixtures/file3.diff') }
14+
15+
let(:sjis_file) { 'spec/support/fixtures/sjis.csv' }
16+
let(:sjis_diff) { sjis_file.gsub(/\.csv\z/, '.diff') }
17+
let(:sjis_body) { File.read(sjis_diff) }
18+
1419
it 'returns parsed patches' do
1520
diff_body = File.read('spec/support/fixtures/d1bd180-c27866c.diff')
1621
patches = Patches.parse(diff_body)
@@ -25,6 +30,12 @@ module GitDiffParser
2530
expect(patches[3].file).to eq file3
2631
expect(patches[3].body).to eq body3
2732
end
33+
34+
it 'handles non UTF-8 encoding characters' do
35+
patches = nil
36+
expect { patches = Patches.parse(sjis_body) }.not_to raise_error
37+
expect(patches[0].file).to eq sjis_file
38+
end
2839
end
2940
end
3041
end

spec/support/fixtures/sjis.csv

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
�M abcdefg

spec/support/fixtures/sjis.diff

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
diff --git a/spec/support/fixtures/sjis.csv b/spec/support/fixtures/sjis.csv
2+
new file mode 100644
3+
index 0000000..4c19aee
4+
--- /dev/null
5+
+++ b/spec/support/fixtures/sjis.csv
6+
@@ -0,0 +1 @@
7+
+�M abcdefg
8+
\ No newline at end of file

0 commit comments

Comments
 (0)