|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# @summary |
| 4 | +# Digs into the facts hash using dot-notation |
| 5 | +# |
| 6 | +# Supports the use of dot-notation for referring to structured facts. If a fact requested |
| 7 | +# does not exist, returns Undef. |
| 8 | +# |
| 9 | +# @example Example usage: |
| 10 | +# fact('osfamily') |
| 11 | +# fact('os.architecture') |
| 12 | +# |
| 13 | +# @example Array indexing: |
| 14 | +# fact('mountpoints."/dev".options.1') |
| 15 | +# |
| 16 | +# @example Fact containing a "." in the name: |
| 17 | +# fact('vmware."VRA.version"') |
| 18 | +# |
| 19 | +Puppet::Functions.create_function(:fact) do |
| 20 | + # @param fact_name |
| 21 | + # The name of the fact to check |
| 22 | + # |
| 23 | + # @return |
| 24 | + # All information retrieved on the given fact_name |
| 25 | + dispatch :fact do |
| 26 | + param 'String', :fact_name |
| 27 | + end |
| 28 | + |
| 29 | + def to_dot_syntax(array_path) |
| 30 | + array_path.map { |string| |
| 31 | + string.include?('.') ? %("#{string}") : string |
| 32 | + }.join('.') |
| 33 | + end |
| 34 | + |
| 35 | + def fact(fact_name) |
| 36 | + facts = closure_scope['facts'] |
| 37 | + |
| 38 | + # Transform the dot-notation string into an array of paths to walk. Make |
| 39 | + # sure to correctly extract double-quoted values containing dots as single |
| 40 | + # elements in the path. |
| 41 | + path = fact_name.scan(%r{([^."]+)|(?:")([^"]+)(?:")}).map { |x| x.compact.first } |
| 42 | + |
| 43 | + walked_path = [] |
| 44 | + path.reduce(facts) do |d, k| |
| 45 | + return nil if d.nil? || k.nil? |
| 46 | + |
| 47 | + if d.is_a?(Array) |
| 48 | + begin |
| 49 | + result = d[Integer(k)] |
| 50 | + rescue ArgumentError => e # rubocop:disable Lint/UselessAssignment : Causes errors if assigment is removed. |
| 51 | + Puppet.warning("fact request for #{fact_name} returning nil: '#{to_dot_syntax(walked_path)}' is an array; cannot index to '#{k}'") |
| 52 | + result = nil |
| 53 | + end |
| 54 | + elsif d.is_a?(Hash) |
| 55 | + result = d[k] |
| 56 | + else |
| 57 | + Puppet.warning("fact request for #{fact_name} returning nil: '#{to_dot_syntax(walked_path)}' is not a collection; cannot walk to '#{k}'") |
| 58 | + result = nil |
| 59 | + end |
| 60 | + |
| 61 | + walked_path << k |
| 62 | + result |
| 63 | + end |
| 64 | + end |
| 65 | +end |
0 commit comments