end
def handle_create_without_match
- File.open(resource[:path], 'a') do |fh|
- fh.puts resource[:line]
+
+ regex = resource[:after] ? Regexp.new(resource[:after]) : nil
+ after_count = File.exists?(resource[:path]) ? lines.select { |l| regex.match(l) }.size : 0
+ if after_count > 1 then
+ raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches after pattern '#{resource[:after]}'"
end
- end
+ if (after_count == 0)
+
+ File.open(resource[:path], 'a') do |fh|
+ fh.puts resource[:line]
+ end
+
+ else
+
+ File.open(resource[:path], 'w') do |fh|
+ lines.each do |l|
+ fh.puts(l)
+ if regex.match(l) then
+ fh.puts(resource[:line])
+ end
+ end
+ end
+
+ end
+
+ end
end
newvalues(true, false)
end
+ newparam(:after) do
+ desc 'An optional value used to specify the line after which we will add any new lines. (Existing lines are added in place)'
+ end
+
newparam(:line) do
desc 'The line to be appended to the file located by the path parameter.'
end
File.read(@tmpfile).chomp.should eql("foo1\nfoo = bar\nfoo2\nfoo = bar")
end
+ it 'should replace all lines that matches with after' do
+ @resource = Puppet::Type::File_line.new(
+ {
+ :name => 'foo',
+ :path => @tmpfile,
+ :line => 'inserted = line',
+ :after => '^foo1',
+ }
+ )
+ @provider = provider_class.new(@resource)
+ File.open(@tmpfile, 'w') do |fh|
+ fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz")
+ end
+ @provider.exists?.should be_nil
+ @provider.create
+ File.read(@tmpfile).chomp.should eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo = baz")
+ end
+
it 'should raise an error with invalid values' do
expect {
@resource = Puppet::Type::File_line.new(