lib/berkshelf/lockfile.rb in berkshelf-2.0.4 vs lib/berkshelf/lockfile.rb in berkshelf-2.0.5

- old
+ new

@@ -31,23 +31,13 @@ load! if File.exists?(@filepath) end # Load the lockfile from file system. def load! - contents = File.read(filepath) + contents = File.read(filepath).strip - begin - hash = JSON.parse(contents, symbolize_names: true) - rescue JSON::ParserError - if contents =~ /^cookbook ["'](.+)["']/ - Berkshelf.ui.warn 'You are using the old lockfile format. Attempting to convert...' - hash = LockfileLegacy.parse(berksfile, contents) - else - raise - end - end - + hash = parse(contents) @sha = hash[:sha] hash[:sources].each do |name, options| add(CookbookSource.new(berksfile, name.to_s, options)) end @@ -165,9 +155,28 @@ def to_json(options = {}) JSON.pretty_generate(to_hash, options) end private + + # Parse the given string as JSON. + # + # @param [String] contents + # + # @return [Hash] + def parse(contents) + # Ruby's JSON.parse cannot handle an empty string/file + return { sha: nil, sources: [] } if contents.strip.empty? + + JSON.parse(contents, symbolize_names: true) + rescue Exception => e + if e.class == JSON::ParserError && contents =~ /^cookbook ["'](.+)["']/ + Berkshelf.ui.warn 'You are using the old lockfile format. Attempting to convert...' + return LockfileLegacy.parse(berksfile, contents) + else + raise Berkshelf::LockfileParserError.new(filepath, e) + end + end # Save the contents of the lockfile to disk. def save File.open(filepath, 'w') do |file| file.write to_json + "\n"