From 72089f3d134a00e64f0b3d81237a266131d40412 Mon Sep 17 00:00:00 2001 From: Raymond Maika Date: Fri, 29 May 2015 00:27:08 -0400 Subject: (MODULES-2071) Refactor file_line provider to contain logic to handle parameter multiple in function handle_create_with_after Without this, file_line resource without the `match` parameter but with the `after` param will throw an error if there are multiple matches for the after expression. This patch creates the handling for the `multiple` parameter in handle_create_with_after. This allows you to add a line after the `after` expression if it appears at multiple points in a file. Updated reference to `file_line` in the README to reflect that the multiple parameter can be set when using `after` and/or `match` as the matching regex. --- lib/puppet/provider/file_line/ruby.rb | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) (limited to 'lib/puppet/provider') diff --git a/lib/puppet/provider/file_line/ruby.rb b/lib/puppet/provider/file_line/ruby.rb index e7854f0..c58e27e 100644 --- a/lib/puppet/provider/file_line/ruby.rb +++ b/lib/puppet/provider/file_line/ruby.rb @@ -61,20 +61,22 @@ Puppet::Type.type(:file_line).provide(:ruby) do def handle_create_with_after regex = Regexp.new(resource[:after]) count = count_matches(regex) - case count - when 1 # find the line to put our line after - File.open(resource[:path], 'w') do |fh| - lines.each do |l| - fh.puts(l) - if regex.match(l) then - fh.puts(resource[:line]) - end + + if count > 1 && resource[:multiple].to_s != 'true' + raise Puppet::Error, "#{count} lines match pattern '#{resource[:after]}' in file '#{resource[:path]}'. One or no line must match the pattern." + end + + 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 - when 0 # append the line to the end of the file + end + + if (count == 0) # append the line to the end of the file append_line - else - raise Puppet::Error, "#{count} lines match pattern '#{resource[:after]}' in file '#{resource[:path]}'. One or no line must match the pattern." end end -- cgit v1.2.3