lib/nanoc3/data_sources/filesystem.rb in nanoc3-3.2.0a4 vs lib/nanoc3/data_sources/filesystem.rb in nanoc3-3.2.0b1
- old
+ new
@@ -261,16 +261,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