Module: AdvFileUtils

Included in:
FileUtils
Defined in:
lib/advanced-fileutils.rb

Defined Under Namespace

Classes: CommandError, Error, FileLockError

Constant Summary collapse

OPT_TABLE =

Hash table to hold command options.

{}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.append(filename, *data_and_options, &block) ⇒ Object

Options: verbose, noop, force, backup

Append the given data to the file named by filename.

If called with a block then the File object is yielded to the block for appending data intead of the data being passed as an argument.

AdvFileUtils.append('data.log', "some data for log entry\n")
AdvFileUtils.append('data.log') { |f| f.puts "some data for log entry" }


193
194
195
# File 'lib/advanced-fileutils.rb', line 193

def append (filename, *data_and_options, &block)
  generic_write 'a', filename, *data_and_options, &block
end

.edit(filename, *data_and_options) ⇒ Object

Options: verbose, noop, force, backup, editor

Invoke an external editor to edit some text or a file.

edit(filename, options)
edit(filename, data, options)

Return values

true, if successful and file was edited
false, if successful and file was not edited
nil, if successful and file was not saved


282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/advanced-fileutils.rb', line 282

def edit (filename, *data_and_options)
  data, options = *parse_data_and_options(data_and_options)
  editor =
      options[:editor] ? options[:editor] :
      ENV.has_key?('VISUAL') ? ENV['VISUAL'] :
      ENV.has_key?('EDITOR') ? ENV['EDITOR'] : 'vi'

  file_stat = File.stat(filename)
  file_checksum = SHA1.file(filename)

  if not data.nil?
    truncate_options = options.reject do |k, v|
      OPT_TABLE['truncate'].index(k).nil?
    end
    truncate(filename, data, truncate_options)
  end

  system(editor, filename, options)
  proc_status = $?

  if options[:noop]
    return true

  elsif proc_status.success?
    return true if file_checksum != SHA1.file(filename)
    return nil if file_stat == File.stat(filename)
    return false

  elsif proc_status.signaled?
    raise AdvFileUtils::CommandError.new("editor terminated on signal #{proc_status.termsig}")

  else
    raise AdvFileUtils::CommandError.new("editor had non-zero exit code #{proc_status.exitstatus}")
  end
end

.edit_data(data, options = {}) ⇒ Object

Options: editor

Edit some data in an external editor and return the result.

edit_data("Hello World\n")


330
331
332
333
334
335
336
337
# File 'lib/advanced-fileutils.rb', line 330

def edit_data (data, options = {})
    tmp = Tempfile.new(File.basename($0))
    tmp.close
    edit(tmp.path, data, options)
    File.read(tmp.path)
  ensure
    tmp.delete if tmp
end

.replace(filename, *data_and_options) ⇒ Object

Options: verbose, noop, force, backup, lockfile, retry

Edit a file, but open a temporary lockfile instead and move it in place after editting is complete.



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
# File 'lib/advanced-fileutils.rb', line 350

def replace (filename, *data_and_options)
  data, options = *parse_data_and_options(data_and_options)
  lockfile = options[:lockfile] ? options[:lockfile] : "#{filename}.lock"

  begin
    if not options[:noop]
      fd = IO.sysopen(lockfile, IO::WRONLY | IO::CREAT | IO::EXCL, 0700)
      f = IO.new(fd, 'w')
      hook_write(f, lockfile) if block_given? and options[:verbose]
    else
      f = StringIO.new
      hook_write(f, lockfile, :rewind) if block_given? and options[:verbose]
    end

    file_stat = File.stat(filename) rescue nil

    if block_given?
      $stderr.puts "cat /dev/null > #{Escape.shell_single_word(lockfile)}" if options[:verbose]
      yield f
    else
      $stderr.puts AdvFileUtils.__send__(:write_echo_message, data, '>', lockfile) if options[:verbose]
      f.write(data)
    end

    f.close

    if file_stat
      FileUtils.chown(file_stat.uid.to_s, file_stat.gid.to_s, lockfile, options)
      FileUtils.chmod(file_stat.mode & 07777, lockfile, options)
    end
    FileUtils.mv(lockfile, filename, options)

  ensure
    f.close if f and not f.closed?
    begin
      File.delete(lockfile) if fd
    rescue Errno::ENOENT
    end
  end
end

.shObject

Options: verbose, noop

An alternative to Kernel.system that accepts options for verbosity and dry runs.

Raises:

  • (ArgumentError)


256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/advanced-fileutils.rb', line 256

def system (*command_and_options)
  if command_and_options[-1].respond_to?(:has_key?)
    command = command_and_options[0...-1]
    options = command_and_options[-1]
  else
    command = command_and_options
    options = {}
  end

  raise ArgumentError.new('wrong number of arguments') if command.empty?

  if options[:verbose]
    if command.size == 1
      $stderr.puts command[0]
    else
      $stderr.puts command.collect { |word|
        Escape.shell_single_word word
      }.join(' ')
    end
  end

  if not options[:noop]
    Kernel.system(*command)
  end
end

.shellObject

Options: verbose, noop

An alternative to Kernel.system that accepts options for verbosity and dry runs.

Raises:

  • (ArgumentError)


260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/advanced-fileutils.rb', line 260

def system (*command_and_options)
  if command_and_options[-1].respond_to?(:has_key?)
    command = command_and_options[0...-1]
    options = command_and_options[-1]
  else
    command = command_and_options
    options = {}
  end

  raise ArgumentError.new('wrong number of arguments') if command.empty?

  if options[:verbose]
    if command.size == 1
      $stderr.puts command[0]
    else
      $stderr.puts command.collect { |word|
        Escape.shell_single_word word
      }.join(' ')
    end
  end

  if not options[:noop]
    Kernel.system(*command)
  end
end

.system(*command_and_options) ⇒ Object

Options: verbose, noop

An alternative to Kernel.system that accepts options for verbosity and dry runs.

Raises:

  • (ArgumentError)


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
# File 'lib/advanced-fileutils.rb', line 228

def system (*command_and_options)
  if command_and_options[-1].respond_to?(:has_key?)
    command = command_and_options[0...-1]
    options = command_and_options[-1]
  else
    command = command_and_options
    options = {}
  end

  raise ArgumentError.new('wrong number of arguments') if command.empty?

  if options[:verbose]
    if command.size == 1
      $stderr.puts command[0]
    else
      $stderr.puts command.collect { |word|
        Escape.shell_single_word word
      }.join(' ')
    end
  end

  if not options[:noop]
    Kernel.system(*command)
  end
end

.truncate(filename, *data_and_options, &block) ⇒ Object

Options: verbose, noop, force, backup

Replace the given data in the file named by filename.

If called with a block then the File object is yielded to the block for writing data intead of the data being passed as an argument.

AdvFileUtils.truncate('data.log', "some data\n")
AdvFileUtils.truncate('data.log') { |f| f.puts "some data" }


213
214
215
# File 'lib/advanced-fileutils.rb', line 213

def truncate (filename, *data_and_options, &block)
  generic_write 'w', filename, *data_and_options, &block
end

Instance Method Details

#append(filename, *data_and_options, &block) ⇒ Object

Options: verbose, noop, force, backup

Append the given data to the file named by filename.

If called with a block then the File object is yielded to the block for appending data intead of the data being passed as an argument.

AdvFileUtils.append('data.log', "some data for log entry\n")
AdvFileUtils.append('data.log') { |f| f.puts "some data for log entry" }


193
194
195
# File 'lib/advanced-fileutils.rb', line 193

def append (filename, *data_and_options, &block)
  generic_write 'a', filename, *data_and_options, &block
end

#edit(filename, *data_and_options) ⇒ Object

Options: verbose, noop, force, backup, editor

Invoke an external editor to edit some text or a file.

edit(filename, options)
edit(filename, data, options)

Return values

true, if successful and file was edited
false, if successful and file was not edited
nil, if successful and file was not saved


282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/advanced-fileutils.rb', line 282

def edit (filename, *data_and_options)
  data, options = *parse_data_and_options(data_and_options)
  editor =
      options[:editor] ? options[:editor] :
      ENV.has_key?('VISUAL') ? ENV['VISUAL'] :
      ENV.has_key?('EDITOR') ? ENV['EDITOR'] : 'vi'

  file_stat = File.stat(filename)
  file_checksum = SHA1.file(filename)

  if not data.nil?
    truncate_options = options.reject do |k, v|
      OPT_TABLE['truncate'].index(k).nil?
    end
    truncate(filename, data, truncate_options)
  end

  system(editor, filename, options)
  proc_status = $?

  if options[:noop]
    return true

  elsif proc_status.success?
    return true if file_checksum != SHA1.file(filename)
    return nil if file_stat == File.stat(filename)
    return false

  elsif proc_status.signaled?
    raise AdvFileUtils::CommandError.new("editor terminated on signal #{proc_status.termsig}")

  else
    raise AdvFileUtils::CommandError.new("editor had non-zero exit code #{proc_status.exitstatus}")
  end
end

#edit_data(data, options = {}) ⇒ Object

Options: editor

Edit some data in an external editor and return the result.

edit_data("Hello World\n")


330
331
332
333
334
335
336
337
# File 'lib/advanced-fileutils.rb', line 330

def edit_data (data, options = {})
    tmp = Tempfile.new(File.basename($0))
    tmp.close
    edit(tmp.path, data, options)
    File.read(tmp.path)
  ensure
    tmp.delete if tmp
end

#replace(filename, *data_and_options) ⇒ Object

Options: verbose, noop, force, backup, lockfile, retry

Edit a file, but open a temporary lockfile instead and move it in place after editting is complete.



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
# File 'lib/advanced-fileutils.rb', line 350

def replace (filename, *data_and_options)
  data, options = *parse_data_and_options(data_and_options)
  lockfile = options[:lockfile] ? options[:lockfile] : "#{filename}.lock"

  begin
    if not options[:noop]
      fd = IO.sysopen(lockfile, IO::WRONLY | IO::CREAT | IO::EXCL, 0700)
      f = IO.new(fd, 'w')
      hook_write(f, lockfile) if block_given? and options[:verbose]
    else
      f = StringIO.new
      hook_write(f, lockfile, :rewind) if block_given? and options[:verbose]
    end

    file_stat = File.stat(filename) rescue nil

    if block_given?
      $stderr.puts "cat /dev/null > #{Escape.shell_single_word(lockfile)}" if options[:verbose]
      yield f
    else
      $stderr.puts AdvFileUtils.__send__(:write_echo_message, data, '>', lockfile) if options[:verbose]
      f.write(data)
    end

    f.close

    if file_stat
      FileUtils.chown(file_stat.uid.to_s, file_stat.gid.to_s, lockfile, options)
      FileUtils.chmod(file_stat.mode & 07777, lockfile, options)
    end
    FileUtils.mv(lockfile, filename, options)

  ensure
    f.close if f and not f.closed?
    begin
      File.delete(lockfile) if fd
    rescue Errno::ENOENT
    end
  end
end

#system(*command_and_options) ⇒ Object Also known as: sh, shell

Options: verbose, noop

An alternative to Kernel.system that accepts options for verbosity and dry runs.

Raises:

  • (ArgumentError)


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
# File 'lib/advanced-fileutils.rb', line 228

def system (*command_and_options)
  if command_and_options[-1].respond_to?(:has_key?)
    command = command_and_options[0...-1]
    options = command_and_options[-1]
  else
    command = command_and_options
    options = {}
  end

  raise ArgumentError.new('wrong number of arguments') if command.empty?

  if options[:verbose]
    if command.size == 1
      $stderr.puts command[0]
    else
      $stderr.puts command.collect { |word|
        Escape.shell_single_word word
      }.join(' ')
    end
  end

  if not options[:noop]
    Kernel.system(*command)
  end
end

#truncate(filename, *data_and_options, &block) ⇒ Object

Options: verbose, noop, force, backup

Replace the given data in the file named by filename.

If called with a block then the File object is yielded to the block for writing data intead of the data being passed as an argument.

AdvFileUtils.truncate('data.log', "some data\n")
AdvFileUtils.truncate('data.log') { |f| f.puts "some data" }


213
214
215
# File 'lib/advanced-fileutils.rb', line 213

def truncate (filename, *data_and_options, &block)
  generic_write 'w', filename, *data_and_options, &block
end