Module: CmdTools::Commands::Backup

Extended by:
RubyPatch::AutoLoad
Defined in:
lib/cmd_tools/commands/backup.rb

Constant Summary collapse

BAK_DIR_HEAD =
"bak_since_"
BAK_DIR_REG =
/(\A|\/)#{BAK_DIR_HEAD}\d{12}\z/
BAK_PREFIX =
'bak.'

Class Method Summary collapse

Class Method Details

.delete_nested_bak_dir(dest, nested_bak_dir_reg) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/cmd_tools/commands/backup.rb', line 47

def self.delete_nested_bak_dir(dest, nested_bak_dir_reg)
  Find.find(dest){|f| # I did not used #select method chain style to use Find.prune.
    next unless File.directory?(f)
    next unless f =~ nested_bak_dir_reg

    $stdout.puts "Delete #{f}? [y/N]"
    if $stdin.gets.strip =~ /\Ay/i
      $stdout.puts "Deleting: #{f}"
      FileUtils.rm_rf(f)
      Find.prune
    end
  }
end

.get_bak_dir(time_stamp) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/cmd_tools/commands/backup.rb', line 34

def self.get_bak_dir(time_stamp)
  Dir.foreach('.')\
    .select{|f| File.directory?(f)}\
    .select{|f| f =~ BAK_DIR_REG}\
    .first\
  or BAK_DIR_HEAD + time_stamp
end

.get_dest(bak_dir, file, time_stamp) ⇒ Object



42
43
44
45
# File 'lib/cmd_tools/commands/backup.rb', line 42

def self.get_dest(bak_dir, file, time_stamp)
  ext = File.extname(file)
  File.join(bak_dir, [BAK_PREFIX, file, '.', time_stamp, ext].join)
end

.run(*files) ⇒ Object

Back up files and directories to bak_dir.

Parameters:

  • files (Array<String>)

    Files and directories to be backed up.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/cmd_tools/commands/backup.rb', line 13

def self.run(*files)
  time_stamp = Time.now.ymdhms
  bak_dir = get_bak_dir(time_stamp)
  nested_bak_dir_reg = /\A#{bak_dir}\/.*#{BAK_DIR_HEAD}\d{12}\z/
  FileUtils.mkdir_p(bak_dir)
  (files.flatten.map{|f| f.chomp('/')} - ['.', '..', bak_dir])\
    .select{|f| File.exist?(f)}\
    .each{|f|
    dest = get_dest(bak_dir, f, time_stamp)
    begin
      FileUtils.cp_r(f, dest)
    rescue
      warn "WARN: Failed to back up #{f}"
    end

    delete_nested_bak_dir(dest, nested_bak_dir_reg) if(File.directory?(dest))
  }
end