From d07b004d39e9a6f74f7841daae5c1e52db34efde Mon Sep 17 00:00:00 2001 From: Tim Smith Date: Wed, 24 Jul 2019 08:35:08 -0700 Subject: [PATCH] Add new PropertyWithNameAttribute rule This catches properties that define a name_attribute instead of a name_property Signed-off-by: Tim Smith --- config/cookstyle.yml | 6 ++ .../cop/chef/property_with_name_attribute.rb | 59 +++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 lib/rubocop/cop/chef/property_with_name_attribute.rb diff --git a/config/cookstyle.yml b/config/cookstyle.yml index 544ee50c8..aa17c10a4 100644 --- a/config/cookstyle.yml +++ b/config/cookstyle.yml @@ -105,6 +105,12 @@ Chef/WhyRunSupportedTrue: Description: why_run_supported? no longer needs to be set to true as it is the default in Chef 13+ Enabled: true +PropertyWithNameAttribute: + Description: Resource property sets name_attribute not name_property + Enabled: true + #Include: + # - '**/resources/*' + ############################### # Utilize new built-in resources ############################### diff --git a/lib/rubocop/cop/chef/property_with_name_attribute.rb b/lib/rubocop/cop/chef/property_with_name_attribute.rb new file mode 100644 index 000000000..cf7bcb0a1 --- /dev/null +++ b/lib/rubocop/cop/chef/property_with_name_attribute.rb @@ -0,0 +1,59 @@ +# +# Copyright:: Copyright 2019, Chef Software Inc. +# Author:: Tim Smith () +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +module RuboCop + module Cop + module Chef + # When using properties in a custom resource you should use name_property not + # the legacy name_attribute from the days of attributes + # + # @example + # + # # bad + # property :bob, String, name_attribute: true + # + # # good + # property :bob, String, name_property: true + # + class PropertyWithNameAttribute < Cop + MSG = 'Resource property sets name_attribute not name_property'.freeze + + def on_send(node) + add_offense(node, location: :expression, message: MSG, severity: :refactor) if attribute_method_mix?(node) + end + + def autocorrect(node) + lambda do |corrector| + corrector.replace(node.loc.expression, node.source.gsub('name_attribute: true', 'name_property: true')) + end + end + + private + + def attribute_method_mix?(node) + if node.method_name == :property + node.arguments.each do |arg| + if arg.type == :hash + return true if arg.source == 'name_attribute: true' + end + end + false # no name_attribute found + end + end + end + end + end +end