Skip to content

Commit

Permalink
Maintain consistent JSON formatting
Browse files Browse the repository at this point in the history
The JSON gem has historically included newlines when pretty printing
empty arrays or hashes. This changed with ruby/json@b2c4480 in JSON
2.8.0.

In order to maintain consistent behavior for our users, this commit
special cases empty array and hash facts and adds a new test for empty
hashes.
  • Loading branch information
mhashizume committed Nov 25, 2024
1 parent c3a5090 commit 295d2f9
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/puppet/face/facts.rb
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,15 @@

case result
when Array, Hash
Puppet::Util::Json.dump(result, :pretty => true)
# JSON < 2.8.0 would pretty print empty arrays and hashes with newlines
# Maintain that behavior for our users for now
if result.is_a?(Array) && result.empty?
"[\n\n]"
elsif result.is_a?(Hash) && result.empty?
"{\n}"
else
Puppet::Util::Json.dump(result, :pretty => true)
end
else # one of VALID_TYPES above
result
end
Expand Down
1 change: 1 addition & 0 deletions spec/unit/application/facts_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@

{
"type_hash" => [{'a' => 2}, "{\n \"a\": 2\n}"],
"type_empty_hash" => [{}, "{\n}"],
"type_array" => [[], "[\n\n]"],
"type_string" => ["str", "str"],
"type_int" => [1, "1"],
Expand Down

0 comments on commit 295d2f9

Please sign in to comment.