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.
|
---|
4 |
|
---|
5 | For example:
|
---|
6 |
|
---|
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 } }
|
---|
12 |
|
---|
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."
|
---|
15 |
|
---|
16 | ENDHEREDOC
|
---|
17 |
|
---|
18 | if args.length < 2
|
---|
19 | raise Puppet::ParseError, ("deep_merge(): wrong number of arguments (#{args.length}; must be at least 2)")
|
---|
20 | end
|
---|
21 |
|
---|
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)
|
---|
26 | else
|
---|
27 | new_value
|
---|
28 | end
|
---|
29 | end
|
---|
30 | end
|
---|
31 |
|
---|
32 | result = Hash.new
|
---|
33 | args.each do |arg|
|
---|
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"
|
---|
38 | end
|
---|
39 |
|
---|
40 | result = deep_merge.call(result, arg)
|
---|
41 | end
|
---|
42 | return( result )
|
---|
43 | end
|
---|
44 | end
|
---|