bugfix: unindent description misbehaviors

Unindent has been misbehaving for control `desc`riptions by completely removing newlines. This is now fixed and the unindentation mechanism improved to behave as expected.

Removing empty lines at the beginning and end of string remains unchanged.
Tabs are not treated as multi-space indentations; supporting them as 8-space chars would require additional effort (please comment if this is important to you)

Signed-off-by: Dominik Richter <dominik.richter@gmail.com>
This commit is contained in:
Dominik Richter 2017-04-25 12:39:25 +02:00
parent 5f9d1980f7
commit 37a2e45cd1
2 changed files with 37 additions and 6 deletions

View file

@ -231,16 +231,22 @@ module Inspec
end
end
# Idio(ma)tic unindent
# TODO: replace this
# Idio(ma)tic unindent, behaves similar to Ruby2.3 curly heredocs.
# Find the shortest indentation of non-empty lines and strip that from every line
# See: https://bugs.ruby-lang.org/issues/9098
#
# It is implemented here to support pre-Ruby2.3 with this feature and
# to not force non-programmers to understand heredocs.
#
# Please note: tabs are not supported! (they will be removed but they are not
# treated the same as in Ruby2.3 heredocs)
#
# @param [String] text string which needs to be unindented
# @return [String] input with indentation removed
# @return [String] input with indentation removed; '' if input is nil
def unindent(text)
return '' if text.nil?
text.strip.split("\n").map(&:strip)
.map { |x| x.empty? ? "\n" : x }
.join(' ')
len = text.split("\n").reject { |l| l.strip.empty? }.map { |x| x.index(/[^\s]/) }.compact.min
text.gsub(/^[[:blank:]]{#{len}}/, '').strip
end
# get the rule's source code

View file

@ -15,6 +15,31 @@ describe 'controls' do
.params[:controls]['1']
end
let(:rand_string) { rand.to_s }
it 'adds a title' do
load("title #{rand_string.inspect}")[:title].must_equal rand_string
end
it 'adds a description' do
load("desc #{rand_string.inspect}")[:desc].must_equal rand_string
end
it 'adds a multiline description' do
t = rand_string + "\n" + rand_string
load("desc #{t.inspect}")[:desc].must_equal t
end
it 'strips empty lines and spaces in description at start and end' do
t = " \n" + rand_string + "\n "
load("desc #{t.inspect}")[:desc].must_equal rand_string
end
it 'unindents properly' do
t = "\n #{rand_string}\n \n\t\t #{rand_string}\n "
load("desc #{t.inspect}")[:desc].must_equal "#{rand_string}\n \n #{rand_string}"
end
it 'works with empty refs' do
load('ref')[:refs].must_be :empty?
end