Class: Backup::FileBackup

Inherits:
Object
  • Object
show all
Defined in:
lib/backup/file_backup.rb

Overview

Backup directories and files to a backup directory

Instance Method Summary collapse

Constructor Details

#initialize(files = []) ⇒ FileBackup

Initializes the files to be backed up. If no file is provided an error is returned



16
17
18
# File 'lib/backup/file_backup.rb', line 16

def initialize(files=[])
  @files = files
end

Instance Method Details

#backup(backup_folder) ⇒ Object

The files to be backed up are initilized when creating an instance of FileBackup. These files are then backed up to the backup directory



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/backup/file_backup.rb', line 51

def backup(backup_folder)

  inexistent_files = []

  @files.each do |file|
    inexistent_files << file unless File.exists? file
  end

  unless inexistent_files.empty?
    STDERR.puts "Cannot backup inexistent files"
    STDERR.puts "Following #{inexistent_files.size} file(s) do not exist"
    STDERR.puts "#{inexistent_files.join(', ')}"
    exit 1
  end
  
  backup_folder += '/' unless backup_folder.match(/.*\/\Z/)
  
  Dir.mkdir backup_folder unless File.exists? backup_folder

  backup_files = []

  @files.each.with_index do |file, index|
    backup_files << backup_file = backup_folder+File.basename(file)
    FileUtils.cp file, backup_file
  end

  backup_files

end

#check_for_inexistent(files) ⇒ Object

Checks if the files all exist. Files that do not exist are returned in an Array



83
84
85
86
87
88
89
90
# File 'lib/backup/file_backup.rb', line 83

def check_for_inexistent (files)
  inexistent_files = []
  files.each do |f|
    inexistent_files << f unless File.exists? f
  end

  inexistent_files
end

#compress(files, backup_folder) ⇒ Object

Compress the files to the backup directory



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/backup/file_backup.rb', line 21

def compress(files, backup_folder)
  inexistent_files = check_for_inexistent files
  unless inexistent_files.empty?
    STDERR.puts "Cannot compress inexistent files"
    STDERR.puts "Following #{inexistent_files.size} file(s) do not exist"
    STDERR.puts inexistent_files.join(" ")
    exit 2
  end

  timestamp = Time.now.strftime("%Y%m%d-%H%M%S")
  backup_folder += '/' unless backup_folder.match(/.*\/\Z/)
  compress_file = backup_folder + timestamp + "_" + "files.tar.gz"

  tar_command = "tar cfz #{compress_file} " + files.join(" ")

  stdout_str, stderr_str, status = Open3.capture3(tar_command)

  unless status.exitstatus == 0
    STDERR.puts "There was a problem running tar command"
    STDERR.puts "--> #{tar_command}"
    STDERR.puts stderr_str
    exit(2)
  end

  status.exitstatus

end