|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require File.expand_path('../../util/ini_file', __dir__) |
| 4 | + |
| 5 | +Puppet::Type.type(:ini_section).provide(:ruby) do |
| 6 | + def self.instances |
| 7 | + desc ' |
| 8 | + Creates new ini_section file, a specific config file with a provider that uses |
| 9 | + this as its parent and implements the method |
| 10 | + self.file_path, and that will provide the value for the path to the |
| 11 | + ini file.' |
| 12 | + raise(Puppet::Error, 'Ini_section only support collecting instances when a file path is hard coded') unless respond_to?(:file_path) |
| 13 | + |
| 14 | + # figure out what to do about the seperator |
| 15 | + ini_file = Puppet::Util::IniFile.new(file_path, '=') |
| 16 | + resources = [] |
| 17 | + ini_file.section_names.each do |section_name| |
| 18 | + next if section_name.empty? |
| 19 | + resources.push( |
| 20 | + new( |
| 21 | + name: namevar(section_name), |
| 22 | + ensure: :present, |
| 23 | + ), |
| 24 | + ) |
| 25 | + end |
| 26 | + resources |
| 27 | + end |
| 28 | + |
| 29 | + def self.namevar(section_name) |
| 30 | + section_name |
| 31 | + end |
| 32 | + |
| 33 | + def exists? |
| 34 | + ini_file.section_names.include?(section) |
| 35 | + end |
| 36 | + |
| 37 | + def create |
| 38 | + ini_file.set_value(section) |
| 39 | + ini_file.save |
| 40 | + @ini_file = nil |
| 41 | + end |
| 42 | + |
| 43 | + def destroy |
| 44 | + ini_file.remove_section(section) |
| 45 | + ini_file.save |
| 46 | + @ini_file = nil |
| 47 | + end |
| 48 | + |
| 49 | + def file_path |
| 50 | + # this method is here to support purging and sub-classing. |
| 51 | + # if a user creates a type and subclasses our provider and provides a |
| 52 | + # 'file_path' method, then they don't have to specify the |
| 53 | + # path as a parameter for every ini_section declaration. |
| 54 | + # This implementation allows us to support that while still |
| 55 | + # falling back to the parameter value when necessary. |
| 56 | + if self.class.respond_to?(:file_path) |
| 57 | + self.class.file_path |
| 58 | + else |
| 59 | + resource[:path] |
| 60 | + end |
| 61 | + end |
| 62 | + |
| 63 | + def section |
| 64 | + # this method is here so that it can be overridden by a child provider |
| 65 | + resource[:section] |
| 66 | + end |
| 67 | + |
| 68 | + def section_prefix |
| 69 | + if resource.class.validattr?(:section_prefix) |
| 70 | + resource[:section_prefix] || '[' |
| 71 | + else |
| 72 | + '[' |
| 73 | + end |
| 74 | + end |
| 75 | + |
| 76 | + def section_suffix |
| 77 | + if resource.class.validattr?(:section_suffix) |
| 78 | + resource[:section_suffix] || ']' |
| 79 | + else |
| 80 | + ']' |
| 81 | + end |
| 82 | + end |
| 83 | + |
| 84 | + private |
| 85 | + |
| 86 | + def ini_file |
| 87 | + @ini_file ||= Puppet::Util::IniFile.new(file_path, '=', section_prefix, section_suffix, ' ', 2) |
| 88 | + end |
| 89 | +end |
0 commit comments