Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rewrite facter_version_for_puppet_version for a better style #183

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 17 additions & 13 deletions lib/rspec-puppet-facts.rb
Original file line number Diff line number Diff line change
Expand Up @@ -394,30 +394,34 @@ def self.facter_version_for_puppet_version(puppet_version)
return Facter.version
end

fd = File.open(json_path, 'rb:UTF-8')
data = JSON.parse(fd.read)
data = File.open(json_path, 'rb:UTF-8') do |fd|
JSON.parse(fd.read)
rescue JSON::ParserError
warning "#{json_path} contains invalid JSON, defaulting to Facter #{Facter.version}"
return Facter.version
end

puppet_gem_version = Gem::Version.new(puppet_version)

version_map = data.map { |_, versions|
applicable_versions = data.filter_map do |_, versions|
if versions['puppet'].nil? || versions['facter'].nil?
nil
else
[Gem::Version.new(versions['puppet']), versions['facter']]
puppet_version = Gem::Version.new(versions['puppet'])
if puppet_gem_version >= puppet_version
[puppet_version, versions['facter']]
else
nil
end
end
}.compact
end

puppet_gem_version = Gem::Version.new(puppet_version)
applicable_versions = version_map.select { |p, _| puppet_gem_version >= p }
if applicable_versions.empty?
warning "Unable to find Puppet #{puppet_version} in #{json_path}, defaulting to Facter #{Facter.version}"
return Facter.version
end

applicable_versions.sort { |a, b| b.first <=> a.first }.first.last
rescue JSON::ParserError
warning "#{json_path} contains invalid JSON, defaulting to Facter #{Facter.version}"
Facter.version
ensure
fd.close if fd
applicable_versions.max_by { |p, _| p }.last
end
end

Expand Down
Loading