1 module Puppet::Parser::Functions
2 newfunction(:deep_merge, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args|
3 Recursively merges two or more hashes together and returns the resulting hash.
7 $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } }
8 $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } }
9 $merged_hash = deep_merge($hash1, $hash2)
10 # The resulting hash is equivalent to:
11 # $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } }
13 When there is a duplicate key that is a hash, they are recursively merged.
14 When there is a duplicate key that is not a hash, the key in the rightmost hash will "win."
19 raise Puppet::ParseError, ("deep_merge(): wrong number of arguments (#{args.length}; must be at least 2)")
22 deep_merge = Proc.new do |hash1,hash2|
23 hash1.merge(hash2) do |key,old_value,new_value|
24 if old_value.is_a?(Hash) && new_value.is_a?(Hash)
25 deep_merge.call(old_value, new_value)
34 next if arg.is_a? String and arg.empty? # empty string is synonym for puppet's undef
35 # If the argument was not a hash, skip it.
36 unless arg.is_a?(Hash)
37 raise Puppet::ParseError, "deep_merge: unexpected argument type #{arg.class}, only expects hash arguments"
40 result = deep_merge.call(result, arg)