Module: Cfruby::FileEdit

Defined in:
lib/libcfruby/fileedit.rb

Overview

Methods for line-based editing of files. Generally geared towards editing configuration files on POSIX-based systems.

Defined Under Namespace

Classes: AnchorNotFoundError, FileEditError

Constant Summary collapse

APPEND =
"append"
PREPEND =
"prepend"

Class Method Summary collapse

Class Method Details

.comment(filename, regex, options = {}) ⇒ Object

Comments out lines that match regex, which may also be given as a string Options:

:commentwith

(defaults to ‘#’) Use this at the front of the line to comment the line

:fuzzymatch

(defaults to true) If regex is given as a String, ignore whitespace



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'lib/libcfruby/fileedit.rb', line 421

def FileEdit.comment(filename, regex, options = {})
	if(options[:fuzzymatch] == nil)
		options[:fuzzymatch] = true
	end

	if(!options[:commentwith])
		options[:commentwith] = '#'
	end

	if(!regex.kind_of?(Array))
		regex = Array.[](regex)
	end
	
	regex.each_index() { |i|
		if(!regex[i].kind_of?(Regexp))
			if(options[:fuzzymatch])
				regex[i] = convert_to_fuzzy_regex(regex[i], :partialstr => true)
			else
				regex[i] = Regexp.new(Regexp.escape(regex[i]))
			end
		end				
	}

	commented = Regexp.new("^\\s*#{Regexp.escape(options[:commentwith])}")

	changed = false
	Cfruby.controller.attempt("Commenting all lines matching \"#{regex.map() { |r| r.source() }.join(',')}\" in \"#{filename}\"", 'destructive') {
		lines = Array.new()
		File.open(filename, File::RDONLY) { |fp|
			lines = fp.readlines()
		}
	
		lines.each_index() { |i|
			regex.each() { |r|
				if(r.match(lines[i]) and !commented.match(lines[i]))
					lines[i] = options[:commentwith] + ' ' + lines[i]
					Cfruby.controller.inform('verbose', "Commented \"#{lines[i].strip()}\" in #{filename}")
					changed = true
				end						
			}
		}
	
		if(!changed)
			Cfruby.controller.attempt_abort("nothing commented")
		end

		FileEdit.open(filename, File::WRONLY | File::TRUNC) { |fp|
			lines.each() { |line|
				fp.write(line)
			}
		}				
	}
	
	return(changed)
end

.contains?(filename, pattern) ⇒ Boolean

Returns true if the given pattern (str or regular expression) is found in filename

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/libcfruby/fileedit.rb', line 30

def FileEdit.contains?(filename, pattern)
	if(!pattern.kind_of?(Regexp))
		pattern = Regexp.new(Regexp.escape(pattern.to_s()))
	end
	
	File.open(filename, File::RDONLY) { |fp|
		fp.each_line() { |line|
			if(pattern.match(line))
				return(true)
			end
		}
	}
	
	return(false)
end

.file_append(filename, str) ⇒ Object

Appends str to the end of filename



276
277
278
279
280
281
282
283
284
285
# File 'lib/libcfruby/fileedit.rb', line 276

def FileEdit.file_append(filename, str) 
	changed = false
	Cfruby.controller.attempt("appending \"#{str}\" to #{filename}", 'destructive') {
		changed = FileEdit.open(filename, File::WRONLY|File::APPEND) { |fp|
			fp.write(str)
		}
	}
	
	return(changed)
end

.file_must_contain(filename, str, options = {}) ⇒ Object

Ensures that filename contains str. If str is a single line, that line will be searched for. If str contains multiple lines then, by default, it will be split on /n/ and each line will be checked/added in turn. If :block => true is passed in then the first line of a multiline block will be searched for (or :regex if it is given), and the entire block will be added if it is not found. If str contains an array then file_must_contain will be called on each item in order.

Returns true if str (or any substr) was added, false if it was not (meaning everything passed was already in the file). Options:

:position

may be FileEdit::APPEND or FileEdit::PREPEND (or ‘append’ or ‘prepend’). Defaults to FileEdit::APPEND

:anchor

may be nil, a line number, or a regular expression. Used to determine where to append or prepend

:fuzzymatch

defaults to true - causes whitespace in str to be largely ignored for purposes of matching.

:regex

if given, then str will be added if regex matches no lines in the file

:block

defaults to false - determines whether multiline str’s will be treated as a single block

:allwaysadd

If true str will be added even if the given anchor cannot be found. Defaults to false.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/libcfruby/fileedit.rb', line 60

def FileEdit.file_must_contain(filename, str, options={})
	if(!options[:position])
		options[:position] = APPEND
	elsif(options[:postion] == 'append')
		options[:position] = APPEND
	elsif(options[:position] == 'prepend')
		options[:position] = PREPEND
	end
	
	if(options[:fuzzymatch] == nil)
		options[:fuzzymatch] = true
	end
	
	if(str.kind_of?(Array))
		added = false
		str.each() { |substr|
			if(file_must_contain(filename, substr, options))
				added = true
			end
		}
		return(added)
	elsif(str =~ /\n./ and !options[:block])
		return(file_must_contain(filename, str.split(/\n/), options))
	end
	
	# add a newline to str if it wasn't passed in with one
	if(str !~ /\n$/)
		str = str + "\n"
	end

	regex = options[:regex]
	if(regex == nil)
		# if the str is multi-line, split it and use the first line
		matchstr = str
		if(str =~ /\n./)
			matchstr = str.split(/\n/)[0]
		end
		
		if(options[:fuzzymatch])
			regex = convert_to_fuzzy_regex(matchstr)
		else			
			regex = Regexp.new(Regexp.escape(matchstr))
		end
	end
			
	# don't call contains? here because we need to snag the last line in the file
	lastline = "\n"
	File.open(filename, File::RDONLY) { |fp|
		fp.each_line() { |line|
			if(regex.match(line))
				return(false)
			end
			lastline = line
		}
	}
	
	Cfruby.controller.attempt("adding \"#{str}\" to #{filename}", 'destructive') {
		begin
			# if we get here, it isn't in the file - stick it in
			if(options[:position] == APPEND)
				if(options[:anchor] == nil)
					FileEdit.open(filename, File::RDWR|File::APPEND) { |fp|
						if(lastline !~ /\n$/)
							fp.write("\n")
						end
						fp.write(str)
					}
				elsif(options[:anchor].kind_of?(Integer))
					lines = nil
					File.open(filename, File::RDONLY) { |fp|
						lines = fp.readlines()									
					}
					if(options[:anchor] < 0 or lines.length+1 < options[:anchor])
						raise(AnchorNotFoundError, "options[:anchor] is past the last line in the file \"#{filename}\"")
					end
					lines.insert(options[:anchor]+1, str)
					write_file(filename, lines)
				elsif(options[:anchor].respond_to?(:match))
					added = false
					lines = Array.new()
					File.open(filename, File::RDONLY) { |fp|
						fp.each_line() { |line|
							lines << line
							if(options[:anchor].match(line))
								lines << str
								added = true
							end				
						}
					}
					if(added)
						write_file(filename, lines)
					else
						raise(AnchorNotFoundError, "Anchor \"#{options[:anchor].source}\" not found in \"#{filename}\"")
					end
				else
					raise(ArgumentError, "options[:anchor] was not nil, a number, or a regular expression")
				end
			elsif(options[:position] == PREPEND)						
				if(options[:anchor] == nil)
					File.open(filename, File::RDWR) { |fp|
						lines = fp.readlines
						fp.seek(0, IO::SEEK_SET)
						fp.truncate(0)
						fp.write(str)
						lines.each() { |line|
							fp.write(line)
						}
					}
				elsif(options[:anchor].kind_of?(Integer))
					lines = nil
					File.open(filename, File::RDONLY) { |fp|
						lines = fp.readlines
					}
					if(options[:anchor] < 0 or lines.length < options[:anchor])
						raise(AnchorNotFoundError, "options[:anchor] is past the last line in the file \"#{filename}\"")
					end
					lines.insert(options[:anchor], str)
					write_file(filename, lines)
				elsif(options[:anchor].respond_to?(:match))
					added = false
					lines = Array.new()
					File.open(filename, File::RDONLY) { |fp|
						fp.each_line() { |line|
							if(options[:anchor].match(line))
								lines << str
								added = true
							end				
							lines << line
						}									
					}

					if(added)
						write_file(filename, lines)
					else
						raise(AnchorNotFoundError, "Anchor \"#{options[:anchor].source}\" not found in \"#{filename}\"")
					end
				else
					raise(ArgumentError, "options[:anchor] was not nil, a number, or a regular expression")
				end
			end
		rescue AnchorNotFoundError
			if(options[:allwaysadd])
				options[:anchor] = nil
				file_must_contain(filename, str, options)
			else
				raise($!)
			end
		end
	}
	
	return(true)
end

.file_must_not_contain(filename, pattern, options = {}) ⇒ Object

Ensures that filename does not contain lines matching pattern. Pattern may be a String, Regexp, or an Array of either. Options:

:fuzzymatch

defaults to true - causes whitespace in pattern (if passed as a String) to be largely ignored for purposes of matching.



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/libcfruby/fileedit.rb', line 217

def FileEdit.file_must_not_contain(filename, pattern, options={})
	if(pattern.kind_of?(Array))
		pattern.each() { |p|
			file_must_not_contain(filename, p)
		}
		return()
	elsif(!pattern.kind_of?(Regexp) and pattern.to_s() =~ /\n./)
		file_must_not_contain(filename, pattern.split("\n"))
	end
	
	if(options[:fuzzymatch] == nil)
		options[:fuzzymatch] = true
	end
	
	regex = pattern			
	# convert regex to a real Regexp if it isn't one
	if(!pattern.kind_of?(Regexp))
		if(options[:fuzzymatch])
			regex = convert_to_fuzzy_regex(regex)
		else
			regex = regex.to_s()
			if(regex !~ /\n$/)
				regex += "\n"
			end
			regex = Regexp.new("^#{Regexp.escape(regex.to_s)}$")
		end
	end
	
	# do this in two passes, one with the file open read only to check
	# for the existence of the line, then trunc and write out a new file
	# if it does
	lines = Array.new()
	rewrite = false
	FileEdit.open(filename, File::RDONLY) { |fp|
		fp.each_line() { |line|
			if(regex.match(line))
				rewrite = true
			else
				lines << line
			end
		}
	}
	
	changed = false
	if(rewrite == true)
		Cfruby.controller.attempt("removing \"#{regex.to_s()}\" from #{filename}", 'nonreversible', 'destructive') {
			changed = FileEdit.open(filename, File::TRUNC|File::WRONLY) { |fp|
				lines.each() { |line|
					fp.write(line)
				}
			}
		}
	end
	
	return(changed)
end

.file_prepend(filename, str) ⇒ Object

Prepends str to filename



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/libcfruby/fileedit.rb', line 289

def FileEdit.file_prepend(filename, str)
	changed = false
	Cfruby.controller.attempt("prepending \"#{str}\" to #{filename}", 'destructive') {
		lines = File.open(filename, File::RDONLY).readlines()
		changed = FileEdit.open(filename, File::WRONLY|File::TRUNC) { |fp|
			fp.write(str)
			if(str !~ /\n$/)
				fp.write("\n")
			end
			lines.each() { |line|
				fp.write(line)
			}
		}
	}
	
	return(changed)
end

.open(filename, mode, &block) ⇒ Object

Handles atomic editing by creating a temporary copy of filename and only writing it back if an actual change has been made. Yields a File object.



571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
# File 'lib/libcfruby/fileedit.rb', line 571

def FileEdit.open(filename, mode, &block)
	Cfruby.controller.attempt("Editing \"#{filename}\"") {
		newfile = Tempfile.new('fileedit')
		newfile.close(false)
		
		# attempt to chown the temp file - and set move based on our ability to do so
		move = false
		begin
			Cfruby::FileOps.chown(newfile.path, File.stat(filename).uid, File.stat(filename).gid)
			move = true
		rescue
			# we failed - do nothing
		end
		
		# chmod the temp file
		Cfruby::FileOps.chmod(newfile.path, File.stat(filename).mode)
		
		buffer = ''
		File.open(filename, File::RDONLY) { |orig|
			File.open(newfile.path, File::WRONLY|File::TRUNC) { |copy|
				while(orig.read(2048, buffer) != nil)
					copy.write(buffer)
				end
			}
		}

		File.open(newfile.path, mode) { |fp|
			yield(fp)
		}

		if(Cfruby::Checksum::Checksum.get_checksums(filename).sha1 != Cfruby::Checksum::Checksum.get_checksums(newfile.path).sha1)
			# backup the file
			FileOps.backup(filename)
			
			if(move)
				FileOps.move(newfile.path, filename, :force => true, :preserve => true)
			else
				File.open(newfile.path, File::RDONLY) { |orig|
					File.open(filename, File::WRONLY|File::TRUNC) { |copy|
						while(orig.read(2048, buffer) != nil)
							copy.write(buffer)
						end
					}
				}
			end
			
			return(true)
		else
			Cfruby.controller.attempt_abort("unchanged")
		end
	}
	
	return(false)
end

.replace(filename, regex, str, options = {}) ⇒ Object

Replaces all lines matching regex with str. Options:

:firstonly

if true then the first match is replaced and all other matching lines are removed from the file.

:fuzzymatch

(defaults to true) causes String whitespace to be ignored for matching purposes

:alwaysadd

(defaults to true) then the line will be added (by calling file_must_contain and passing

through options) to the end of the file even if no lines match regex.



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/libcfruby/fileedit.rb', line 348

def FileEdit.replace(filename, regex, str, options={})
	if(options[:fuzzymatch] == nil)
		options[:fuzzymatch] = true
	end

	if(options[:alwaysadd] == nil)
		options[:alwaysadd] = true
	end
	
	if(str !~ /\n$/)
		str << "\n"
	end
	
	if(!regex.kind_of?(Array))
		regex = Array.[](regex)
	end
	
	regex.each_index() { |i|
		if(!regex[i].kind_of?(Regexp))
			if(options[:fuzzymatch])
				regex[i] = convert_to_fuzzy_regex(regex[i], :partialstr => true)
			else
				regex[i] = Regexp.new(Regexp.escape(regex[i]))
			end
		end
	}
	
	replaced = false
	Cfruby.controller.attempt("Replacing #{regex[0].source}... with #{str} in \"#{filename}\"", 'destructive', 'nonreversible') {
		lines = Array.new()
		File.open(filename, File::RDONLY) { |fp|
			fp.each_line() { |line|
				regex.each() { |r|
					if(r.match(line))
						if(replaced && options[:firstonly])
							next
						else
							line = str
							replaced = true
						end
					end
				}
				lines << line
			}
		}
	
		if(!replaced and options[:alwaysadd])
			file_must_contain(filename, str, options)
			replaced = true
		elsif(replaced)
			changed = write_file(filename, lines)
			if(changed != true)
				replaced = false
				Cfruby.controller.attempt_abort("unchanged")
			end
		else
			replaced = false
			Cfruby.controller.attempt_abort("unchanged")
		end
	}
	
	if(replaced)
		return(true)
	else
		return(false)
	end
end

.set(filename, variable, value, options = {}) ⇒ Object

Sets variable to value in filename (as in hostname = “my.hostname.com”). Options:

:delimiter

(‘=’ by default) determines what delimiter to place between variable and value

:whitespace

(overrides delimiter) uses a special whitespace matching delimiter if true



543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
# File 'lib/libcfruby/fileedit.rb', line 543

def FileEdit.set(filename, variable, value, options={})
  replaced = false
	Cfruby.controller.attempt("Setting \"#{variable}\" to \"#{value}\" in \"#{filename}\"", 'destructive', 'nonreversible') {
		delimiter = '='
		replacement = delimiter
		if(options[:whitespace])
			delimiter = "\\s+"
			replacement = ' '
		elsif(options[:delimiter] != nil)
			replacement = options[:delimiter]
			delimiter = Regexp.escape(options[:delimiter])
		end
	
		regex = Regexp.new("^\\s*#{Regexp.escape(variable)}\\s*?#{delimiter}")
		str = "#{variable}#{replacement}#{value}\n"
	
		replaced = replace(filename, regex, str)
		if(replaced != true)
			Cfruby.controller.attempt_abort("unchanged")
		end
	}

	return(replaced)
end

.set_contents(filename, remove, add, options = {}) ⇒ Object

Atomically sets the contents of filename by first removing all lines in remove and then adding all lines in add using file_must_not_contain and file_must_contain



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/libcfruby/fileedit.rb', line 310

def FileEdit.set_contents(filename, remove, add, options={})
	filename = Pathname.new(filename).realpath

	newfile = Tempfile.new('fileedit')
	File.open(filename, File::RDONLY) { |fp|
		fp.each_line() { |line|
			newfile.write(line)
		}
	}
	newfile.close()
	
	changed = false
	if(remove)
		mustnotchanged = file_must_not_contain(newfile.path, remove, options)
		if(mustnotchanged)
			changed = true
		end
	end
	if(add)
		mustchanged = file_must_contain(newfile.path, add, options)
		if(mustchanged)
			changed = true
		end
	end
	
	if(changed)
		FileOps.move(newfile.path, filename, :force=>true, :preserve=>true)
	end
	
	return(changed)
end

.uncomment(filename, regex, options = {}) ⇒ Object

Uncomments lines that match regex, which may also be given as a string Options:

:commentwith

(defaults to ‘#’) Remove this from the front of the line to uncomment the line

:fuzzymatch

(defaults to true) If regex is given as a String, ignore whitespace



482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
# File 'lib/libcfruby/fileedit.rb', line 482

def FileEdit.uncomment(filename, regex, options = {})
	if(options[:fuzzymatch] == nil)
		options[:fuzzymatch] = true
	end

	if(!options[:commentwith])
		options[:commentwith] = '#'
	end

	if(!regex.kind_of?(Array))
		regex = Array.[](regex)
	end

	regex.each_index() { |i|
		if(!regex[i].kind_of?(Regexp))
			if(options[:fuzzymatch])
				regex[i] = convert_to_fuzzy_regex(regex[i], :partialstr => true)
			else
				regex[i] = Regexp.new(Regexp.escape(regex[i]))
			end
		end				
	}

	commented = Regexp.new("^\\s*#{Regexp.escape(options[:commentwith])}")

	changed = false
	Cfruby.controller.attempt("Uncommenting all lines matching \"#{regex.map() { |r| r.source() }.join(',')}\" in \"#{filename}\"", 'destructive') {
		lines = Array.new()
		File.open(filename, File::RDONLY) { |fp|
			lines = fp.readlines()
		}

		lines.each_index() { |i|
			regex.each() { |r|
				if(r.match(lines[i]) and commented.match(lines[i]))
					# use multiline match here to get the newline on the end
					lines[i] = lines[i][/^\s*#{Regexp.escape(options[:commentwith])}\s*(.*)$/m, 1]
					Cfruby.controller.inform('verbose', "Uncommented \"#{lines[i].strip()}\" in #{filename}")
					changed = true
				end						
			}
		}

		if(!changed)
			Cfruby.controller.attempt_abort("nothing uncommented")
		end

		FileEdit.open(filename, File::WRONLY | File::TRUNC) { |fp|
			lines.each() { |line|
				fp.write(line)
			}
		}
	}
	
	return(changed)
end