Class: Command::Backup

Inherits:
CommandBase show all
Defined in:
lib/command/backup.rb

Constant Summary collapse

BACKUP_DIR_NAME =
"backup"

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from CommandBase

execute!, #force_change_settings_function, help, #hook_call, #load_local_settings, #tagname_to_ids

Constructor Details

#initializeBackup

Returns a new instance of Backup.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/command/backup.rb', line 17

def initialize
  super("<target> [<target2> ...]")
  @opt.separator <<-EOS

  ・指定した小説のバックアップを作成します。
  ・バックアップファイルはZIP圧縮され、小説保存フォルダ直下の#{BACKUP_DIR_NAME}フォルダに保存されます。
  ・バックアップ対象は、バックアップファイル以外の小説保存フォルダにあるファイル全てが対象です。

  Examples:
narou backup 0
narou backup n9669bk
narou backup 0 1 musyoku
  EOS
end

Class Method Details

.oneline_helpObject



13
14
15
# File 'lib/command/backup.rb', line 13

def self.oneline_help
  "小説のバックアップを作成します"
end

Instance Method Details

#create_backup(data) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/command/backup.rb', line 36

def create_backup(data)
  zipfilename = create_backup_filename(data)
  pwd = Dir.pwd
  novel_dir = Downloader.get_novel_data_dir_by_target(data["id"])
  Dir.chdir(novel_dir)
  paths = Dir.glob("**/*").keep_if { |path|
    File.file?(path) && path.split("/", 2)[0] != BACKUP_DIR_NAME
  }
  FileUtils.mkdir(BACKUP_DIR_NAME) unless File.exist?(BACKUP_DIR_NAME)
  Zip.unicode_names = true unless Helper.os_windows?
  Zip::File.open(File.join(BACKUP_DIR_NAME, zipfilename), Zip::File::CREATE) do |zip|
    paths.each do |path|
      if Helper.os_windows?
        zipped_filename = path.encode(Encoding::Windows_31J,
                                      invalid: :replace, undef: :replace, replace: "_")
      else
        zipped_filename = path
      end
      zip.add(zipped_filename, path)
    end
  end
  Dir.chdir(pwd)
  zipfilename
end

#create_backup_filename(data) ⇒ Object



32
33
34
# File 'lib/command/backup.rb', line 32

def create_backup_filename(data)
  Helper.replace_filename_special_chars(data["title"]) + "_" + Time.now.strftime("%Y%m%d%H%M%S") + ".zip"
end

#execute(argv) ⇒ Object



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
# File 'lib/command/backup.rb', line 61

def execute(argv)
  super
  if argv.empty?
    puts @opt.help
    return
  end
  tagname_to_ids(argv)
  require "zip"
  argv.each_with_index do |target, i|
    Helper.print_horizontal_rule if i > 0
    data = Downloader.get_data_by_target(target)
    unless data
      puts "#{target} は存在しません"
      next
    end
    puts "ID:#{data["id"]} #{data["title"]}"
    print "バックアップを作成しています"
    Thread.new {
      loop do
        print "."
        sleep(0.5)
      end
    }.tap { |th|
      zipfilename =  create_backup(data)
      th.kill
      puts
      puts "#{zipfilename} を作成しました"
    }
  end
end