Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / deep_merge.rb
1 #
2 # deep_merge.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:deep_merge, :type => :rvalue, :doc => <<-'DOC') do |args|
6     @summary
7       Recursively merges two or more hashes together and returns the resulting hash.
8
9     @example Example usage
10
11       $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } }
12       $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } }
13       $merged_hash = deep_merge($hash1, $hash2)
14
15       The resulting hash is equivalent to:
16
17       $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } }
18
19       When there is a duplicate key that is a hash, they are recursively merged.
20       When there is a duplicate key that is not a hash, the key in the rightmost hash will "win."
21
22     @return [Hash] The merged hash
23     DOC
24
25     if args.length < 2
26       raise Puppet::ParseError, "deep_merge(): wrong number of arguments (#{args.length}; must be at least 2)"
27     end
28
29     deep_merge = proc do |hash1, hash2|
30       hash1.merge(hash2) do |_key, old_value, new_value|
31         if old_value.is_a?(Hash) && new_value.is_a?(Hash)
32           deep_merge.call(old_value, new_value)
33         else
34           new_value
35         end
36       end
37     end
38
39     result = {}
40     args.each do |arg|
41       next if arg.is_a?(String) && arg.empty? # empty string is synonym for puppet's undef
42       # If the argument was not a hash, skip it.
43       unless arg.is_a?(Hash)
44         raise Puppet::ParseError, "deep_merge: unexpected argument type #{arg.class}, only expects hash arguments"
45       end
46
47       result = deep_merge.call(result, arg)
48     end
49     return(result)
50   end
51 end