diff --git a/lib/inspec/objects/control.rb b/lib/inspec/objects/control.rb index b1b5634dd..dfb2e0567 100644 --- a/lib/inspec/objects/control.rb +++ b/lib/inspec/objects/control.rb @@ -23,7 +23,7 @@ module Inspec def to_ruby res = ["control #{id.inspect} do"] res.push " title #{title.inspect}" unless title.to_s.empty? - res.push " desc #{desc.inspect.gsub('\n', "\n")}" unless desc.to_s.empty? + res.push " desc #{prettyprint_text(desc, 2)}" unless desc.to_s.empty? res.push " impact #{impact}" unless impact.nil? tags.each { |t| res.push(indent(t.to_ruby, 2)) } tests.each { |t| res.push(indent(t.to_ruby, 2)) } @@ -33,6 +33,18 @@ module Inspec private + # Pretty-print a text block of InSpec code + # + # @param s [String] should not be empty + # @param depth [Int] indentation length for multiline text blocks + # @return [String] pretty-printed textblock + def prettyprint_text(s, depth) + txt = s.to_s.inspect.gsub('\n', "\n") + return txt if !txt.include?("\n") + middle = indent(txt[1..-2], depth+2) + txt[0] + "\n" + middle + "\n" + ' '*depth + txt[-1] + end + def indent(txt, d) dt = ' '*d dt + txt.gsub("\n", "\n"+dt) diff --git a/test/unit/dsl/objects_test.rb b/test/unit/dsl/objects_test.rb index c01faae96..0f04c0426 100644 --- a/test/unit/dsl/objects_test.rb +++ b/test/unit/dsl/objects_test.rb @@ -254,13 +254,39 @@ end '.strip end - it 'constructs a multiline desc in a control' do + it 'constructs a multiline desc in a control with indentation' do control = Inspec::Control.new - control.desc = "Multiline\ncontrol" + control.desc = "Multiline\n control" control.to_ruby.must_equal ' control nil do - desc "Multiline -control" + desc " + Multiline + control + " +end +'.strip + end + + it 'ignores empty control descriptions' do + control = Inspec::Control.new + x = ' +control nil do +end +'.strip + + control.desc = '' + control.to_ruby.must_equal x + + control.desc = nil + control.to_ruby.must_equal x + end + + it 'handles non-string descriptions' do + control = Inspec::Control.new + control.desc = 123 + control.to_ruby.must_equal ' +control nil do + desc "123" end '.strip end