lib/nanoc3/data_sources/filesystem.rb in nanoc3-3.1.7 vs lib/nanoc3/data_sources/filesystem.rb in nanoc3-3.1.8

- old
+ new

@@ -262,16 +262,35 @@ # Reads the content of the file with the given name and returns a string # in UTF-8 encoding. The original encoding of the string is derived from # the default external encoding, but this can be overridden by the # “encoding” configuration attribute in the data source configuration. def read(filename) - data = File.read(filename) - if data.respond_to?(:encode) - data.force_encoding(@config[:encoding]) if @config && @config[:encoding] - data.encode('UTF-8') - else - data + # Read + begin + data = File.read(filename) + rescue => e + raise RuntimeError.new("Could not read #{filename}: #{e.inspect}") end + + # Fix + if data.respond_to?(:encode!) + if @config && @config[:encoding] + original_encoding = Encoding.find(@config[:encoding]) + data.force_encoding(@config[:encoding]) + else + original_encoding = data.encoding + end + + data.encode!('UTF-8') rescue raise_encoding_error(filename, original_encoding) + raise_encoding_error(filename, original_encoding) if !data.valid_encoding? + end + + data + end + + # Raises an invalid encoding error for the given filename and encoding. + def raise_encoding_error(filename, encoding) + raise RuntimeError.new("Could not read #{filename} because the file is not valid #{encoding}.") end end end