|
| 1 | +# Recursively merges two or more hashes together and returns the resulting hash. |
| 2 | +# For example: |
| 3 | +# |
| 4 | +# $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } } |
| 5 | +# $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } } |
| 6 | +# $merged_hash = mysql::deepmerge($hash1, $hash2) |
| 7 | +# # The resulting hash is equivalent to: |
| 8 | +# # $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } } |
| 9 | +# |
| 10 | +# When there is a duplicate key that is a hash, they are recursively merged. |
| 11 | +# When there is a duplicate key that is not a hash, the key in the rightmost hash will "win." |
| 12 | +# When there are conficting uses of dashes and underscores in two keys (which mysql would otherwise equate), |
| 13 | +# the rightmost style will win. |
| 14 | +Puppet::Functions.create_function(:'mysql::deepmerge') do |
| 15 | + def deepmerge(*args) |
| 16 | + if args.length < 2 |
| 17 | + raise Puppet::ParseError, _('mysql_deepmerge(): wrong number of arguments (%{args_length}; must be at least 2)') % { args_length: args.length } |
| 18 | + end |
| 19 | + |
| 20 | + result = {} |
| 21 | + args.each do |arg| |
| 22 | + next if arg.is_a?(String) && arg.empty? # empty string is synonym for puppet's undef |
| 23 | + # If the argument was not a hash, skip it. |
| 24 | + unless arg.is_a?(Hash) |
| 25 | + raise Puppet::ParseError, _('mysql_deepmerge: unexpected argument type %{arg_class}, only expects hash arguments.') % { args_class: args.class } |
| 26 | + end |
| 27 | + |
| 28 | + # We need to make a copy of the hash since it is frozen by puppet |
| 29 | + current = deep_copy(arg) |
| 30 | + |
| 31 | + # Now we have to traverse our hash assigning our non-hash values |
| 32 | + # to the matching keys in our result while following our hash values |
| 33 | + # and repeating the process. |
| 34 | + overlay(result, current) |
| 35 | + end |
| 36 | + result |
| 37 | + end |
| 38 | + |
| 39 | + def normalized?(hash, key) |
| 40 | + return true if hash.key?(key) |
| 41 | + return false unless key =~ %r{-|_} |
| 42 | + other_key = key.include?('-') ? key.tr('-', '_') : key.tr('_', '-') |
| 43 | + return false unless hash.key?(other_key) |
| 44 | + hash[key] = hash.delete(other_key) |
| 45 | + true |
| 46 | + end |
| 47 | + |
| 48 | + def overlay(hash1, hash2) |
| 49 | + hash2.each do |key, value| |
| 50 | + if normalized?(hash1, key) && value.is_a?(Hash) && hash1[key].is_a?(Hash) |
| 51 | + overlay(hash1[key], value) |
| 52 | + else |
| 53 | + hash1[key] = value |
| 54 | + end |
| 55 | + end |
| 56 | + end |
| 57 | + |
| 58 | + def deep_copy(inputhash) |
| 59 | + return inputhash unless inputhash.is_a? Hash |
| 60 | + hash = {} |
| 61 | + inputhash.each do |k, v| |
| 62 | + hash.store(k, deep_copy(v)) |
| 63 | + end |
| 64 | + hash |
| 65 | + end |
| 66 | +end |
0 commit comments