Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new ini_section type #537

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions lib/puppet/provider/ini_section/ruby.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# frozen_string_literal: true

require File.expand_path('../../util/ini_file', __dir__)

Puppet::Type.type(:ini_section).provide(:ruby) do
def self.instances
desc '
Creates new ini_section file, a specific config file with a provider that uses
this as its parent and implements the method
self.file_path, and that will provide the value for the path to the
ini file.'
raise(Puppet::Error, 'Ini_section only support collecting instances when a file path is hard coded') unless respond_to?(:file_path)

# figure out what to do about the seperator
ini_file = Puppet::Util::IniFile.new(file_path, '=')
resources = []
ini_file.section_names.each do |section_name|
next if section_name.empty?
resources.push(
new(
name: namevar(section_name),
ensure: :present,
),
)
end
resources
end

def self.namevar(section_name)
section_name
end

def exists?
ini_file.section_names.include?(section)
end

def create
ini_file.set_value(section)
ini_file.save
@ini_file = nil
end

def destroy
ini_file.remove_section(section)
ini_file.save
@ini_file = nil
end

def file_path
# this method is here to support purging and sub-classing.
# if a user creates a type and subclasses our provider and provides a
# 'file_path' method, then they don't have to specify the
# path as a parameter for every ini_section declaration.
# This implementation allows us to support that while still
# falling back to the parameter value when necessary.
if self.class.respond_to?(:file_path)
self.class.file_path
else
resource[:path]
end
end

def section
# this method is here so that it can be overridden by a child provider
resource[:section]
end

def section_prefix
if resource.class.validattr?(:section_prefix)
resource[:section_prefix] || '['
else
'['
end
end

def section_suffix
if resource.class.validattr?(:section_suffix)
resource[:section_suffix] || ']'
else
']'
end
end

private

def ini_file
@ini_file ||= Puppet::Util::IniFile.new(file_path, '=', section_prefix, section_suffix, ' ', 2)
end
end
52 changes: 52 additions & 0 deletions lib/puppet/type/ini_section.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# frozen_string_literal: true

Puppet::Type.newtype(:ini_section) do
desc 'ini_section is used to manage a single section in an INI file'
ensurable do
desc 'Ensurable method handles modeling creation. It creates an ensure property'
newvalue(:present) do
provider.create
end
newvalue(:absent) do
provider.destroy
end
def insync?(current)
if @resource[:refreshonly]
true
else
current == should
end
end
defaultto :present
end

newparam(:name, namevar: true) do
desc 'An arbitrary name used as the identity of the resource.'
end

newparam(:section) do
desc 'The name of the section in the ini file which should be managed.'
defaultto('')
end

newparam(:path) do
desc 'The ini file Puppet will ensure contains the specified section.'
validate do |value|
raise(Puppet::Error, _("File paths must be fully qualified, not '%{value}'") % { value: value }) unless Puppet::Util.absolute_path?(value)
end
end

newparam(:section_prefix) do
desc 'The prefix to the section name\'s header.'
defaultto('[')
end

newparam(:section_suffix) do
desc 'The suffix to the section name\'s header.'
defaultto(']')
end

autorequire(:file) do
Pathname.new(self[:path]).parent.to_s
end
end
22 changes: 12 additions & 10 deletions lib/puppet/util/ini_file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,17 @@ def remove_setting(section_name, setting)
# was modified.
section_index = @section_names.index(section_name)
decrement_section_line_numbers(section_index + 1)
end

return unless section.empty?
def remove_section(section_name)
section = @sections_hash[section_name]
return unless section

lines.replace(lines[0..(section.start_line - 1)] + lines[(section.end_line + 1)..-1])

section_index = @section_names.index(section.name)
decrement_section_line_numbers(section_index + 1, amount: section.length)

# By convention, it's time to remove this newly emptied out section
lines.delete_at(section.start_line)
decrement_section_line_numbers(section_index + 1)
@section_names.delete_at(section_index)
@sections_hash.delete(section.name)
end
Expand Down Expand Up @@ -222,24 +227,21 @@ def read_section(name, start_line, line_iter)
end_line_num = start_line
min_indentation = nil
empty = true
empty_line_count = 0
loop do
line, line_num = line_iter.peek
if line_num.nil? || @section_regex.match(line)
# the global section always exists, even when it's empty;
# when it's empty, we must be sure it's thought of as new,
# which is signalled with a nil ending line
end_line_num = nil if name == '' && empty
return Section.new(name, start_line, end_line_num, settings, min_indentation, empty_line_count)
return Section.new(name, start_line, end_line_num, settings, min_indentation)
end
if (match = @setting_regex.match(line))
settings[match[2]] = match[4]
indentation = match[1].length
min_indentation = [indentation, min_indentation || indentation].min
end
end_line_num = line_num
empty_line_count += 1 if line == "\n"

empty = false
line_iter.next
end
Expand Down Expand Up @@ -311,10 +313,10 @@ def insert_inline_setting_line(result, section, complete_setting)
# Utility method; given a section index (index into the @section_names
# array), decrement the start/end line numbers for that section and all
# all of the other sections that appear *after* the specified section.
def decrement_section_line_numbers(section_index)
def decrement_section_line_numbers(section_index, amount: 1)
@section_names[section_index..(@section_names.length - 1)].each do |name|
section = @sections_hash[name]
section.decrement_line_nums
section.decrement_line_nums(amount)
end
end

Expand Down
15 changes: 9 additions & 6 deletions lib/puppet/util/ini_file/section.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,13 @@ class Section
# `end_line` of `nil`.
# * `start_line` and `end_line` will be set to `nil` for a new non-global
# section.
def initialize(name, start_line, end_line, settings, indentation, empty_line_count = 0)
def initialize(name, start_line, end_line, settings, indentation)
@name = name
@start_line = start_line
@end_line = end_line
@existing_settings = settings.nil? ? {} : settings
@additional_settings = {}
@indentation = indentation
@empty_line_count = empty_line_count
end

attr_reader :name, :start_line, :end_line, :additional_settings, :indentation
Expand Down Expand Up @@ -51,7 +50,11 @@ def existing_setting?(setting_name)
# the global section is empty whenever it's new;
# other sections are empty when they have no lines
def empty?
global? ? new_section? : (start_line == end_line || (end_line && (end_line - @empty_line_count)) == start_line)
global? ? new_section? : start_line == end_line
end

def length
end_line - start_line + 1
end

def update_existing_setting(setting_name, value)
Expand Down Expand Up @@ -80,9 +83,9 @@ def set_additional_setting(setting_name, value)
# Decrement the start and end line numbers for the section (if they are
# defined); this is intended to be called when a setting is removed
# from a section that comes before this section in the ini file.
def decrement_line_nums
@start_line -= 1 if @start_line
@end_line -= 1 if @end_line
def decrement_line_nums(amount)
@start_line -= amount if @start_line
@end_line -= amount if @end_line
end

# Increment the start and end line numbers for the section (if they are
Expand Down
5 changes: 3 additions & 2 deletions spec/acceptance/ini_setting_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@
subject { super().content }

it { is_expected.to match %r{four = five} }
it { is_expected.not_to match %r{\[one\]} }
it { is_expected.to match %r{\[one\]} }
it { is_expected.not_to match %r{two = three} }
end
end
Expand Down Expand Up @@ -296,7 +296,8 @@
describe '#content' do
subject { super().content }

it { is_expected.to be_empty }
it { is_expected.to match %r{\[section1\]} }
it { is_expected.not_to match %r{valueinsection1 = newValue} }
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion spec/acceptance/ini_subsetting_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@
describe '#content' do
subject { super().content }

it { is_expected.not_to match %r{\[one\]} }
it { is_expected.to match %r{\[one\]} }
it { is_expected.not_to match %r{key =} }
it { is_expected.not_to match %r{alphabet} }
it { is_expected.not_to match %r{betatrons} }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Puppet::Type.type(:inherit_ini_section).provide(
:ini_section,
parent: Puppet::Type.type(:ini_section).provider(:ruby),
) do
def self.namevar(section)
section
end

def self.file_path
File.expand_path(File.dirname(__FILE__) + '/../../../../../../tmp/inherit_inifile.cfg')
end
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Puppet::Type.newtype(:inherit_ini_section) do
ensurable
newparam(:section, namevar: true)
newproperty(:value)
end
63 changes: 63 additions & 0 deletions spec/unit/puppet/provider/ini_section/inheritance_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# frozen_string_literal: true

require 'spec_helper'

# This is a reduced version of ruby_spec.rb just to ensure we can subclass as
# documented
$LOAD_PATH << './spec/fixtures/inherit_ini_section/lib'

describe Puppet::Type.type(:inherit_ini_section).provider(:ini_section) do
include PuppetlabsSpec::Files

let(:tmpfile) { tmpfilename('inherit_ini_section_test') }

def validate_file(expected_content, tmpfile)
expect(File.read(tmpfile)).to eq(expected_content)
end

before :each do
File.write(tmpfile, orig_content)
end

context 'when calling instances' do
let(:orig_content) { '' }

it 'parses nothing when the file is empty' do
allow(described_class).to receive(:file_path).and_return(tmpfile)
expect(described_class.instances).to eq([])
end

context 'when the file has contents' do
let(:orig_content) do
<<-INIFILE
[red]
# A comment
red = blue
[green]
green = purple
INIFILE
end

it 'parses the results' do
allow(described_class).to receive(:file_path).and_return(tmpfile)
instances = described_class.instances
expect(instances.size).to eq(2)
# inherited version of namevar flattens the names
names = instances.map do |instance| instance.instance_variable_get(:@property_hash)[:name] end # rubocop:disable Style/BlockDelimiters
expect(names.sort).to eq(['green', 'red'])
end
end
end

context 'when ensuring that a setting is present' do
let(:orig_content) { '' }

it 'adds a value to the file' do
allow(described_class).to receive(:file_path).and_return(tmpfile)
resource = Puppet::Type::Inherit_ini_section.new(section: 'set_this')
provider = described_class.new(resource)
provider.create
expect(validate_file("[set_this]\n", tmpfile)).to be_truthy
end
end
end
Loading
Loading