Skip to content

Commit 9deef9c

Browse files
committed
(PUP-8243) Ignore leading BOM when reading templates
Specify the 'bom' flag to `read`. On Windows, we continue trying UTF-8, then the default external encoding. On POSIX, we continue using the default external encoding, which is what ruby defaults to.
1 parent f34a5e5 commit 9deef9c

File tree

4 files changed

+16
-3
lines changed

4 files changed

+16
-3
lines changed

lib/puppet/file_system/file_impl.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def read(path, opts = {})
8484
end
8585

8686
def read_preserve_line_endings(path)
87-
read(path)
87+
read(path, encoding: "bom|#{Encoding.default_external.name}")
8888
end
8989

9090
def binread(path)

lib/puppet/file_system/windows.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,8 @@ def chmod(mode, path)
109109
end
110110

111111
def read_preserve_line_endings(path)
112-
contents = path.read( :mode => 'rb', :encoding => Encoding::UTF_8)
113-
contents = path.read( :mode => 'rb', :encoding => Encoding::default_external) unless contents.valid_encoding?
112+
contents = path.read( :mode => 'rb', :encoding => 'bom|utf-8')
113+
contents = path.read( :mode => 'rb', :encoding => "bom|#{Encoding::default_external.name}") unless contents.valid_encoding?
114114
contents = path.read unless contents.valid_encoding?
115115

116116
contents

spec/unit/file_system_spec.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,12 @@ def increment_counter_in_multiple_processes(file, num_procs, options)
290290
expect(Puppet::FileSystem.read_preserve_line_endings(file)).to eq("file content \r\nsecond line \n")
291291
end
292292
end
293+
294+
it "should ignore leading BOM" do
295+
with_file_content("\uFEFFfile content \n") do |file|
296+
expect(Puppet::FileSystem.read_preserve_line_endings(file)).to eq("file content \n")
297+
end
298+
end
293299
end
294300

295301
context "read without an encoding specified" do

spec/unit/parser/templatewrapper_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@
4343
expect(tw.result).to eq(full_file_name)
4444
end
4545

46+
it "ignores a leading BOM" do
47+
full_file_name = given_a_template_file("bom_template", "\uFEFF<%= file %>")
48+
49+
tw.file = "bom_template"
50+
expect(tw.result).to eq(full_file_name)
51+
end
52+
4653
it "evaluates a given string as a template" do
4754
expect(tw.result("template contents")).to eql("template contents")
4855
end

0 commit comments

Comments
 (0)