Suggest different variables to use if we want to tunnel both v4 and v6
[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     Recursively merges two or more hashes together and returns the resulting hash.
7
8     For example:
9
10         $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } }
11         $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } }
12         $merged_hash = deep_merge($hash1, $hash2)
13         # The resulting hash is equivalent to:
14         # $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } }
15
16     When there is a duplicate key that is a hash, they are recursively merged.
17     When there is a duplicate key that is not a hash, the key in the rightmost hash will "win."
18
19     DOC
20
21     if args.length < 2
22       raise Puppet::ParseError, "deep_merge(): wrong number of arguments (#{args.length}; must be at least 2)"
23     end
24
25     deep_merge = proc do |hash1, hash2|
26       hash1.merge(hash2) do |_key, old_value, new_value|
27         if old_value.is_a?(Hash) && new_value.is_a?(Hash)
28           deep_merge.call(old_value, new_value)
29         else
30           new_value
31         end
32       end
33     end
34
35     result = {}
36     args.each do |arg|
37       next if arg.is_a?(String) && arg.empty? # empty string is synonym for puppet's undef
38       # If the argument was not a hash, skip it.
39       unless arg.is_a?(Hash)
40         raise Puppet::ParseError, "deep_merge: unexpected argument type #{arg.class}, only expects hash arguments"
41       end
42
43       result = deep_merge.call(result, arg)
44     end
45     return(result)
46   end
47 end