|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module PuppetStrings::Hiera |
| 4 | + class Data |
| 5 | + attr_reader :config_path, :data_paths |
| 6 | + |
| 7 | + def initialize(config_path) |
| 8 | + @config_path = config_path |
| 9 | + @data_paths = [] |
| 10 | + |
| 11 | + load_config |
| 12 | + end |
| 13 | + |
| 14 | + def files |
| 15 | + @files ||= begin |
| 16 | + result = {} |
| 17 | + |
| 18 | + data_paths.each do |dp| |
| 19 | + dp.matches.each do |file, interpolations| |
| 20 | + unless result.key?(file) |
| 21 | + result[file] = interpolations |
| 22 | + end |
| 23 | + end |
| 24 | + end |
| 25 | + |
| 26 | + result |
| 27 | + end |
| 28 | + end |
| 29 | + |
| 30 | + # @return [Hash[String, Hash[String, Any]]] |
| 31 | + # Full variable (class::var) -> filename: value |
| 32 | + def overrides |
| 33 | + @overrides ||= begin |
| 34 | + overrides = {} |
| 35 | + |
| 36 | + files.each_key do |file| |
| 37 | + data = YAML.load(File.read(file)) |
| 38 | + data.each do |key, value| |
| 39 | + overrides[key] ||= {} |
| 40 | + overrides[key][file] = value |
| 41 | + end |
| 42 | + end |
| 43 | + |
| 44 | + overrides |
| 45 | + end |
| 46 | + end |
| 47 | + |
| 48 | + # @return [Hash[String, Hash[String, Any]]] |
| 49 | + # variable -> filename: value |
| 50 | + def for_class(class_name) |
| 51 | + result = {} |
| 52 | + overrides.each do |key, value| |
| 53 | + override_class_name, _, variable = key.rpartition('::') |
| 54 | + if override_class_name == class_name |
| 55 | + result[variable] = value |
| 56 | + end |
| 57 | + end |
| 58 | + result |
| 59 | + end |
| 60 | + |
| 61 | + def to_s |
| 62 | + config_path |
| 63 | + end |
| 64 | + |
| 65 | + private |
| 66 | + |
| 67 | + def load_config |
| 68 | + return unless File.exist?(config_path) |
| 69 | + |
| 70 | + config = YAML.load(File.read(config_path)) |
| 71 | + |
| 72 | + unless config['version'] == 5 |
| 73 | + raise "Unsupported version '#{config['version']}'" |
| 74 | + end |
| 75 | + |
| 76 | + hierarchy = config['hierarchy'] |
| 77 | + return unless hierarchy |
| 78 | + |
| 79 | + hierarchy.each do |level| |
| 80 | + data_hash = level['data_hash'] || config['defaults']['data_hash'] |
| 81 | + next unless data_hash == 'yaml_data' |
| 82 | + |
| 83 | + datadir = level['datadir'] || config['defaults']['datadir'] |
| 84 | + |
| 85 | + if level['path'] |
| 86 | + data_paths << PuppetStrings::Hiera::HierarchyDataPath.new(datadir, level['path']) |
| 87 | + elsif level['paths'] |
| 88 | + level['paths'].each do |path| |
| 89 | + data_paths << PuppetStrings::Hiera::HierarchyDataPath.new(datadir, path) |
| 90 | + end |
| 91 | + end |
| 92 | + end |
| 93 | + end |
| 94 | + end |
| 95 | +end |
0 commit comments