From e4863b0fda02c0bdc8f02448a41d9bc9852bb4f4 Mon Sep 17 00:00:00 2001 From: jordanbreen28 Date: Mon, 5 Feb 2024 14:57:47 +0000 Subject: [PATCH] (GH-189) - invalid fact correction for top scope structured fact Prior to this commit, if you had a top scope structured fact like this in your manifest `$::my_structured_fact['foo']['test']`, lint would return an invalid correction when passed the fix flag. Now, we have altered the top_scope_facts plugin, to first check if it is a structured fact, and if one is found using regex, apply different logic to fix. --- .../plugins/top_scope_facts/top_scope_facts.rb | 10 +++++++++- .../plugins/top_scope_facts/top_scope_facts_spec.rb | 12 ++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/lib/puppet-lint/plugins/top_scope_facts/top_scope_facts.rb b/lib/puppet-lint/plugins/top_scope_facts/top_scope_facts.rb index 5f537710..d3fcb324 100644 --- a/lib/puppet-lint/plugins/top_scope_facts/top_scope_facts.rb +++ b/lib/puppet-lint/plugins/top_scope_facts/top_scope_facts.rb @@ -44,6 +44,14 @@ def check end def fix(problem) - problem[:token].value = "facts['" + problem[:token].value.sub(%r{^::}, '') + "']" + problem[:token].value.sub!(%r{^::}, '') + # checks if the fact is a top level structured fact e.g. ::my_structured_fact['foo']['bar'] + if %r{\[.*}.match?(problem[:token].value) + fact_name = problem[:token].value.sub(%r{\[.*}, '') + nested_facts = problem[:token].value.scan(%r{\[.*}).first + problem[:token].value = "facts['" + fact_name + "']" + nested_facts + else + problem[:token].value = "facts['" + problem[:token].value + "']" + end end end diff --git a/spec/unit/puppet-lint/plugins/top_scope_facts/top_scope_facts_spec.rb b/spec/unit/puppet-lint/plugins/top_scope_facts/top_scope_facts_spec.rb index 939be5be..22281f84 100644 --- a/spec/unit/puppet-lint/plugins/top_scope_facts/top_scope_facts_spec.rb +++ b/spec/unit/puppet-lint/plugins/top_scope_facts/top_scope_facts_spec.rb @@ -102,6 +102,18 @@ end end + context 'top scope structured fact not present on allowlist' do + let(:code) { "$::my_structured_fact['foo']['test']" } + + it 'detects a problem' do + expect(problems).to contain_fixed('top scope fact instead of facts hash').on_line(1).in_column(1) + end + + it 'fixes the problem' do + expect(manifest).to eq("$facts['my_structured_fact']['foo']['test']") + end + end + context 'top scope $::trusted hash' do let(:code) { "$::trusted['certname']" }