Module: Aef::Bakker

Defined in:
lib/bakker/bakker.rb

Overview

Bakker is a Ruby library and commandline tool to help with simple task of renaming or copying files for quick backup purposes.

Constant Summary collapse

VERSION =
'1.1.0'
DEFAULT_EXTENSION =
'.bak'
MODES =
[:toggle, :add, :remove]
ACTIONS =
[:move, :copy]

Class Method Summary collapse

Class Method Details

.process(filename, extension = DEFAULT_EXTENSION, mode = MODES.first, action = ACTIONS.first, options = {}) ⇒ Object

For possible options see FileUtils methods cp() and mv()

Raises:

  • (ArgumentError)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/bakker/bakker.rb', line 33

def process(filename, extension = DEFAULT_EXTENSION, mode = MODES.first, action = ACTIONS.first, options = {})
  raise ArgumentError, 'Action can only be :copy or :move.' unless ACTIONS.include?(action)
  raise ArgumentError, 'Mode can only be :toggle, :add or :remove.' unless MODES.include?(mode)

  # Regex used for determining if an extension should be added or removed
  regexp = /#{Regexp.escape(extension)}$/

  # Find out both the basic file name and the extended file name for every
  # situation possible
  filename_without_extension = filename.gsub(regexp, '')
  filename_with_extension = filename_without_extension + extension

  # Check both cases for existence for further processing
  without_exists = File.exists?(filename_without_extension)
  with_exists = File.exists?(filename_with_extension)

  # Error if both unextended and extended files or none of them exist
  #
  # The mode variable contains symbols :copy or :move which correspond to
  # methods of class FileUtils which are invoked through the send() method.
  if without_exists and with_exists
    raise Aef::BakkerWarning, "Both #{filename_without_extension} and #{filename_with_extension} already exist."
  elsif without_exists and not with_exists
    if [:toggle, :add].include?(mode)
      FileUtils.send(action, filename_without_extension, filename_with_extension, options)
      filename_with_extension
    else
      filename_without_extension
    end
  elsif not without_exists and with_exists
    if [:toggle, :remove].include?(mode)
      FileUtils.send(action, filename_with_extension, filename_without_extension, options)
      filename_without_extension
    else
      filename_with_extension
    end
  else
    raise Aef::BakkerWarning, "Neither #{filename_without_extension} nor #{filename_with_extension} found."
  end
end