Class: FileEdit

Inherits:
Object
  • Object
show all
Defined in:
lib/chef/util/fileedit.rb

Instance Method Summary collapse

Constructor Details

#initialize(filepath) ⇒ FileEdit

Returns a new instance of FileEdit.

Raises:

  • (ArgumentError)


30
31
32
33
34
35
36
# File 'lib/chef/util/fileedit.rb', line 30

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

Instance Method Details

#insert_line_after_match(regex, newline) ⇒ Object

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



64
65
66
# File 'lib/chef/util/fileedit.rb', line 64

def insert_line_after_match(regex, newline)
  search_match(regex, newline, 'i', 0)
end

#search_file_delete(regex) ⇒ Object

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



58
59
60
# File 'lib/chef/util/fileedit.rb', line 58

def search_file_delete(regex)
  search_match(regex, " ", 'd', 2)
end

#search_file_delete_line(regex) ⇒ Object

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



52
53
54
# File 'lib/chef/util/fileedit.rb', line 52

def search_file_delete_line(regex)
  search_match(regex, " ", 'd', 1)
end

#search_file_replace(regex, replace) ⇒ Object

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



46
47
48
# File 'lib/chef/util/fileedit.rb', line 46

def search_file_replace(regex, replace)
  search_match(regex, replace, 'r', 2)
end

#search_file_replace_line(regex, newline) ⇒ Object

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



40
41
42
# File 'lib/chef/util/fileedit.rb', line 40

def search_file_replace_line(regex, newline)
  search_match(regex, newline, 'r', 1)
end

#write_fileObject

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



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/chef/util/fileedit.rb', line 69

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"
    File.copy(original_pathname, backup_pathname)
    Tempfile.open("w") do |newfile|
      contents.each do |line|
        newfile.puts(line)
      end
      newfile.flush
      FileUtils.mv(newfile.path, original_pathname)
    end
  end
  self.file_edited = false

end