class RuboCop::Cop::Chef::Style::UnnecessaryOSCheck

Use the platform_family?() helpers instead of node == ‘foo’ for platform_families that match one-to-one with OS values. These helpers are easier to read and can accept multiple platform arguments, which greatly simplifies complex platform logic. All values of ‘os` from Ohai match one-to-one with `platform_family` values except for `linux`, which has no single equivalent `platform_family`.

@example

#### incorrect
node['os'] == 'darwin'
node['os'] == 'windows'
node['os'].eql?('aix')
%w(netbsd openbsd freebsd).include?(node['os'])

#### correct
platform_family?('mac_os_x')
platform_family?('windows')
platform_family?('aix')
platform_family?('netbsd', 'openbsd', 'freebsd)

Constants

MSG
RESTRICT_ON_SEND
UNNECESSARY_OS_VALUES

sorted list of all the os values that match 1:1 with a platform_family

Public Instance Methods

array_from_ast(ast) click to toggle source

given an ast array spit out a ruby array

# File lib/rubocop/cop/chef/style/unnecessary_os_check.rb, line 94
def array_from_ast(ast)
  vals = []
  ast.each_child_node { |x| vals << x.value }
  vals.sort
end
on_send(node) click to toggle source
# File lib/rubocop/cop/chef/style/unnecessary_os_check.rb, line 59
def on_send(node)
  os_equals?(node) do |operator, val|
    return unless UNNECESSARY_OS_VALUES.include?(val.value)
    add_offense(node, severity: :refactor) do |corrector|
      corrected_string = (operator == :!= ? '!' : '') + "platform_family?('#{sanitized_platform(val.value)}')"
      corrector.replace(node, corrected_string)
    end
  end

  os_eql?(node) do |val|
    return unless UNNECESSARY_OS_VALUES.include?(val.value)
    add_offense(node, severity: :refactor) do |corrector|
      corrected_string = "platform_family?('#{sanitized_platform(val.value)}')"
      corrector.replace(node, corrected_string)
    end
  end

  os_include?(node) do |val|
    array_of_plats = array_from_ast(val)
    # see if all the values in the .include? usage are in our list of 1:1 platform family to os values
    return unless (UNNECESSARY_OS_VALUES & array_of_plats) == array_of_plats
    add_offense(node, severity: :refactor) do |corrector|
      platforms = val.values.map { |x| x.str_type? ? "'#{sanitized_platform(x.value)}'" : x.source }
      corrected_string = "platform_family?(#{platforms.join(', ')})"
      corrector.replace(node, corrected_string)
    end
  end
end
sanitized_platform(plat) click to toggle source

return the passed value unless the value is darwin and then return mac_os_x

# File lib/rubocop/cop/chef/style/unnecessary_os_check.rb, line 89
def sanitized_platform(plat)
  plat == 'darwin' ? 'mac_os_x' : plat
end