1 Puppet::Type.type(:file_line).provide(:ruby) do
4 line.chomp == resource[:line].chomp
10 handle_create_with_match
11 elsif resource[:after]
12 handle_create_with_after
20 File.open(resource[:path],'w') do |fh|
21 fh.write(local_lines.reject{|l| l.chomp == resource[:line] }.join(''))
27 # If this type is ever used with very large files, we should
28 # write this in a different way, using a temp
29 # file; for now assuming that this type is only used on
30 # small-ish config files that can fit into memory without
32 @lines ||= File.readlines(resource[:path])
35 def handle_create_with_match()
36 regex = resource[:match] ? Regexp.new(resource[:match]) : nil
37 regex_after = resource[:after] ? Regexp.new(resource[:after]) : nil
38 match_count = count_matches(regex)
40 if match_count > 1 && resource[:multiple].to_s != 'true'
41 raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'"
44 File.open(resource[:path], 'w') do |fh|
46 fh.puts(regex.match(l) ? resource[:line] : l)
47 if (match_count == 0 and regex_after)
48 if regex_after.match(l)
49 fh.puts(resource[:line])
50 match_count += 1 #Increment match_count to indicate that the new line has been inserted.
56 fh.puts(resource[:line])
61 def handle_create_with_after
62 regex = Regexp.new(resource[:after])
63 count = count_matches(regex)
65 when 1 # find the line to put our line after
66 File.open(resource[:path], 'w') do |fh|
69 if regex.match(l) then
70 fh.puts(resource[:line])
74 when 0 # append the line to the end of the file
77 raise Puppet::Error, "#{count} lines match pattern '#{resource[:after]}' in file '#{resource[:path]}'. One or no line must match the pattern."
81 def count_matches(regex)
82 lines.select{|l| l.match(regex)}.size
86 # append the line to the file.
90 File.open(resource[:path], 'w') do |fh|
94 fh.puts resource[:line]