class RuboCop::Cop::Chef::Correctness::InvalidPlatformInCase

Use valid platform values in case statements. See [Infra Language: Platform](docs.chef.io/infra_language/checking_platforms/#platform-values) for a list of many common platform values.

@example

#### incorrect
case node['platform']
when 'rhel'
  puts "I'm on a Red Hat system!"
end

Constants

MSG
RESTRICT_ON_SEND

Public Instance Methods

on_case(node) click to toggle source
# File lib/rubocop/cop/chef/correctness/invalid_platform_values_in_case.rb, line 44
def on_case(node)
  node_platform?(node.condition) do
    node.each_when do |when_node|
      when_node.each_condition do |con|
        next unless con.str_type? # if the condition isn't a string we can't check so skip
        new_value = INVALID_PLATFORMS[con.str_content]
        # some invalid platform have no direct correction value and return nil instead
        next unless new_value

        add_offense(con, severity: :refactor) do |corrector|
          # if the correct value already exists in the when statement then we just want to delete this node
          if con.parent.conditions.any? { |x| x.str_content == new_value }
            range = range_with_surrounding_comma(range_with_surrounding_space(range: con.loc.expression, side: :left), :both)
            corrector.remove(range)
          else
            corrector.replace(con, "'#{new_value}'")
          end
        end
      end
    end
  end
end