Class: RuboCop::Cop::Chef::Correctness::InvalidPlatformInCase

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp, RuboCop::Chef::PlatformHelpers
Defined in:
lib/rubocop/cop/chef/correctness/invalid_platform_values_in_case.rb

Overview

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.

Examples:


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

Constant Summary collapse

MSG =
'Use valid platform values in case statements.'
RESTRICT_ON_SEND =
[:[]].freeze

Constants included from RuboCop::Chef::PlatformHelpers

RuboCop::Chef::PlatformHelpers::INVALID_PLATFORMS, RuboCop::Chef::PlatformHelpers::INVALID_PLATFORM_FAMILIES

Instance Method Summary collapse

Methods inherited from Base

#target_chef_version

Instance Method Details

#on_case(node) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 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