Skip to content

Commit 72f898a

Browse files
authored
Merge pull request #7274 from hlindberg/PUP-9329_simple-format-for-array
(PUP-9329) Fix short form format rule for Array/Hash in string converter
2 parents 5835896 + 379b797 commit 72f898a

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

lib/puppet/pops/types/string_converter.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -484,8 +484,17 @@ def convert(value, string_formats = :default)
484484

485485
value_type = TypeCalculator.infer_set(value)
486486
if string_formats.is_a?(String)
487-
# add the format given for the exact type
488-
string_formats = { value_type => string_formats }
487+
# For Array and Hash, the format is given as a Hash where 'format' key is the format for the collection itself
488+
if Puppet::Pops::Types::PArrayType::DEFAULT.assignable?(value_type)
489+
# add the format given for the exact type
490+
string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => {'format' => string_formats }}
491+
elsif Puppet::Pops::Types::PHashType::DEFAULT.assignable?(value_type)
492+
# add the format given for the exact type
493+
string_formats = { Puppet::Pops::Types::PHashType::DEFAULT => {'format' => string_formats }}
494+
else
495+
# add the format given for the exact type
496+
string_formats = { value_type => string_formats }
497+
end
489498
end
490499

491500
case string_formats

spec/unit/pops/types/string_converter_spec.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -698,6 +698,15 @@
698698
expect(formatted).to eq(result)
699699
end
700700

701+
it 'applies a short form format' do
702+
result = [
703+
"[1,",
704+
" [2, 3],",
705+
" 4]"
706+
].join("\n")
707+
expect(converter.convert([1, [2,3], 4], '%#a')).to eq(result)
708+
end
709+
701710
it 'treats hashes as nested arrays wrt indentation' do
702711
string_formats = { Puppet::Pops::Types::PArrayType::DEFAULT => { 'format' => '%#a', 'separator' =>", " } }
703712
# formatting matters here
@@ -846,6 +855,17 @@
846855
expect(converter.convert({1 => "hello", 2 => {3=> "world"}}, string_formats)).to eq(result)
847856
end
848857

858+
it 'applies a short form format' do
859+
result = [
860+
"{",
861+
" 1 => {",
862+
" 2 => 3",
863+
" },",
864+
" 4 => 5",
865+
"}"].join("\n")
866+
expect(converter.convert({1 => {2 => 3}, 4 => 5}, '%#h')).to eq(result)
867+
end
868+
849869
context "containing an array" do
850870
it 'the hash and array renders without breaks and indentation by default' do
851871
result = "{1 => [1, 2, 3]}"

0 commit comments

Comments
 (0)