In Files

  • lib/chef/util/file_edit.rb

Class/Module Index [+]

Quicksearch

Chef::Util::FileEdit

Public Class Methods

new(filepath) click to toggle source
 
               # File lib/chef/util/file_edit.rb, line 31
def initialize(filepath)
        @original_pathname = filepath
        @file_edited = false
        
        raise ArgumentError, "File doesn't exist" unless File.exist? @original_pathname
        raise ArgumentError, "File is blank" unless (@contents = File.new(@original_pathname).readlines).length > 0
end
            

Public Instance Methods

insert_line_after_match(regex, newline) click to toggle source

search the file line by line and match each line with the given regex if matched, insert newline after each matching line

 
               # File lib/chef/util/file_edit.rb, line 65
def insert_line_after_match(regex, newline)
        search_match(regex, newline, 'i', 0)
end
            
search_file_delete(regex) click to toggle source

search the file line by line and match each line with the given regex if matched, delete the match (all occurances) from the line

 
               # File lib/chef/util/file_edit.rb, line 59
def search_file_delete(regex)
        search_match(regex, " ", 'd', 2)
end
            
search_file_delete_line(regex) click to toggle source

search the file line by line and match each line with the given regex if matched, delete the line

 
               # File lib/chef/util/file_edit.rb, line 53
def search_file_delete_line(regex)
        search_match(regex, " ", 'd', 1)
end
            
search_file_replace(regex, replace) click to toggle source

search the file line by line and match each line with the given regex if matched, replace the match (all occurances) with the replace parameter

 
               # File lib/chef/util/file_edit.rb, line 47
def search_file_replace(regex, replace)
        search_match(regex, replace, 'r', 2)
end
            
search_file_replace_line(regex, newline) click to toggle source

search the file line by line and match each line with the given regex if matched, replace the whole line with newline.

 
               # File lib/chef/util/file_edit.rb, line 41
def search_file_replace_line(regex, newline)
        search_match(regex, newline, 'r', 1)
end
            
write_file() click to toggle source

Make a copy of old_file and write new file out (only if file changed)

 
               # File lib/chef/util/file_edit.rb, line 70
        def write_file
                
                # file_edited is false when there was no match in the whole file and thus no contents have changed.
if file_edited
  backup_pathname = original_pathname + ".old"
  FileUtils.cp(original_pathname, backup_pathname, :preserve => true)
  File.open(original_pathname, "w") do |newfile|
    contents.each do |line|
      newfile.puts(line)
    end
    newfile.flush
  end
end
self.file_edited = false
        end