Skip to content

Commit

Permalink
Merge pull request #2494 from mhashizume/FACT_3113/main/file_encoding
Browse files Browse the repository at this point in the history
(FACT-3113) Encode strings as UTF-8 when reading files
  • Loading branch information
joshcooper authored Jun 1, 2022
2 parents 7685a96 + effd741 commit e5ad338
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
4 changes: 2 additions & 2 deletions lib/facter/util/file_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ class << self
DEBUG_MESSAGE = 'File at: %s is not accessible.'

def safe_read(path, default_return = '')
return File.read(path) if File.readable?(path)
return File.read(path, encoding: Encoding::UTF_8) if File.readable?(path)

log_failed_to_read(path)
default_return
end

def safe_readlines(path, default_return = [])
return File.readlines(path) if File.readable?(path)
return File.readlines(path, encoding: Encoding::UTF_8) if File.readable?(path)

log_failed_to_read(path)
default_return
Expand Down
12 changes: 8 additions & 4 deletions spec/facter/util/file_helper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

describe '#safe_read' do
before do
allow(File).to receive(:read).with(path).and_return(content)
allow(File).to receive(:read).with(path, anything).and_return(content)
end

context 'when successfully read the file content' do
Expand All @@ -42,6 +42,10 @@
expect(file_helper.safe_read(path)).to eq(content)
end

it 'returns the file content as UTF-8' do
expect(file_helper.safe_read(path).encoding.name).to eq('UTF-8')
end

it 'File.readable? is called with the correct path' do
file_helper.safe_read(path)

Expand All @@ -51,7 +55,7 @@
it 'File.read is called with the correct path' do
file_helper.safe_read(path)

expect(File).to have_received(:read).with(path)
expect(File).to have_received(:read).with(path, anything)
end

it "doesn't log anything" do
Expand Down Expand Up @@ -129,7 +133,7 @@

describe '#safe_read_lines' do
before do
allow(File).to receive(:readlines).with(path).and_return(array_content)
allow(File).to receive(:readlines).with(path, anything).and_return(array_content)
end

context 'when successfully read the file lines' do
Expand All @@ -148,7 +152,7 @@
it 'File.readlines is called with the correct path' do
file_helper.safe_readlines(path)

expect(File).to have_received(:readlines).with(path)
expect(File).to have_received(:readlines).with(path, anything)
end

it "doesn't log anything" do
Expand Down

0 comments on commit e5ad338

Please sign in to comment.