From 35428fb38da881b86e94175668c0e0fa9430c57a Mon Sep 17 00:00:00 2001 From: Craig Gumbley Date: Mon, 27 Feb 2023 16:58:22 +0000 Subject: [PATCH] (CONT-666) Skip CLASSREF types MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit fixes https://github.com/voxpupuli/puppet-lint-trailing_comma-check/issues/31. It appears that the `resource_indexes` method cannot differentiate between a resource declaration and a defaults declaration. If we compare the two, you can see that a defaults declaration type starts with a capital letter whereas a resource declaration does not. ```puppet Service { 'foo': ensure => running, } ``` ```puppet service { 'foo': ensure => running, } ``` When the `resource_indexes` method runs, it initially selects tokens by the presence of a colon then works to the right to decide if there are any violations. That means we are actually only starting to collect information about the declaration after the name.. so we never know the actual type of the declaration. ```puppet Service { 'foo': ↑ (here) ensure => running, } ``` https://github.com/puppetlabs/puppet-lint/blob/main/lib/puppet-lint/data.rb#L167 In contrast, `defaults_indexes` will skip any tokens that do not have a type of `:CLASSREF` because we know that a defaults declaration will always start with a capital letter (See [puppet-lint.com](http://puppet-lint.com/developer/tokens/) for more information on token types). This commit fixes the above by ensuring that `resource_indexes` checks the type of resource that it is analysing and skips the itteration if it detects a `:CLASSREF`. --- lib/puppet-lint/data.rb | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/lib/puppet-lint/data.rb b/lib/puppet-lint/data.rb index 6a49fadd..927f1728 100644 --- a/lib/puppet-lint/data.rb +++ b/lib/puppet-lint/data.rb @@ -155,6 +155,21 @@ def title_tokens end end + # Internal: Determine if the given token contains a CLASSREF in + # the token chain.. + # + # Returns a Boolean. + def classref?(token) + current_token = token + while true # rubocop:disable Style/InfiniteLoop + current_token = current_token.prev_code_token + break if current_token.nil? + + return true if current_token.type == :CLASSREF + return false if current_token.type == :NAME + end + end + # Internal: Calculate the positions of all resource declarations within the # tokenised manifest. These positions only point to the content of the # resource declarations, they do not include resource types or titles. @@ -169,6 +184,7 @@ def resource_indexes marker = 0 result = [] tokens.select { |t| t.type == :COLON }.each do |colon_token| + next if classref?(colon_token) next unless colon_token.next_code_token && colon_token.next_code_token.type != :LBRACE rel_start_idx = tokens[marker..-1].index(colon_token)