1ca8257514d2f2ba76fa7b7dafb0748287d687aa
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / merge.rb
1 #
2 # merge.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:merge, :type => :rvalue, :doc => <<-'DOC') do |args|
6     Merges two or more hashes together and returns the resulting hash.
7
8     For example:
9
10         $hash1 = {'one' => 1, 'two', => 2}
11         $hash2 = {'two' => 'dos', 'three', => 'tres'}
12         $merged_hash = merge($hash1, $hash2)
13         # The resulting hash is equivalent to:
14         # $merged_hash =  {'one' => 1, 'two' => 'dos', 'three' => 'tres'}
15
16     When there is a duplicate key, the key in the rightmost hash will "win."
17
18     Note that since Puppet 4.0.0 the same merge can be achieved with the + operator.
19
20         $merged_hash = $hash1 + $hash2
21     DOC
22
23     if args.length < 2
24       raise Puppet::ParseError, "merge(): wrong number of arguments (#{args.length}; must be at least 2)"
25     end
26
27     # The hash we accumulate into
28     accumulator = {}
29     # Merge into the accumulator hash
30     args.each do |arg|
31       next if arg.is_a?(String) && arg.empty? # empty string is synonym for puppet's undef
32       unless arg.is_a?(Hash)
33         raise Puppet::ParseError, "merge: unexpected argument type #{arg.class}, only expects hash arguments"
34       end
35       accumulator.merge!(arg)
36     end
37     # Return the fully merged hash
38     accumulator
39   end
40 end