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']" }