Module: Doing::Util::Backup

Extended by:
Backup
Includes:
Doing::Util
Included in:
Backup
Defined in:
lib/doing/util_backup.rb

Overview

Backup utils

Instance Method Summary collapse

Methods included from Doing::Util

#args_for_editor, #deep_merge_hashes, #deep_merge_hashes!, #default_editor, #duplicable?, #duplicate_frozen_values, #editor_with_args, #exec_available, #find_default_editor, #first_available_exec, #mergable?, #merge_default_proc, #merge_values, #safe_load_file, #user_home, #write_to_file

Instance Method Details

#clear_redo(filename) ⇒ Object

Delete all redo files

Parameters:

  • limit —

    Maximum number of backups to retain



32
33
34
35
36
37
38
# File 'lib/doing/util_backup.rb', line 32

def clear_redo(filename)
  filename ||= Doing.config.settings['doing_file']
  backups = Dir.glob("undone*___#{File.basename(filename)}", base: backup_dir).sort.reverse
  backups.each do |file|
    FileUtils.rm(File.join(backup_dir, file))
  end
end

#clear_undone(filename = nil) ⇒ Object



92
93
94
95
96
97
98
# File 'lib/doing/util_backup.rb', line 92

def clear_undone(filename = nil)
  filename ||= Doing.config.settings['doing_file']
  # redo_file = File.join(backup_dir, "undone___#{File.basename(filename)}")
  Dir.glob("undone*#{File.basename(filename)}", base: backup_dir).each do |f|
    FileUtils.rm(File.join(backup_dir, f))
  end
end

#prune_backups(filename, limit = 10) ⇒ Object

Delete all but most recent 5 backups

Parameters:

  • limit (defaults to: 10) —

    Maximum number of backups to retain



16
17
18
19
20
21
22
23
24
25
# File 'lib/doing/util_backup.rb', line 16

def prune_backups(filename, limit = 10)
  backups = get_backups(filename)
  return unless backups.count > limit

  backups[limit..-1].each do |file|
    FileUtils.rm(File.join(backup_dir, file))
  end

  clear_redo(filename)
end

#redo_backup(filename = nil, count: 1) ⇒ Object

Undo last undo

Parameters:

  • filename (defaults to: nil) —

    The filename

Raises:

  • (DoingRuntimeError)


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/doing/util_backup.rb', line 68

def redo_backup(filename = nil, count: 1)
  filename ||= Doing.config.settings['doing_file']
  # redo_file = File.join(backup_dir, "undone___#{File.basename(filename)}")
  undones = Dir.glob("undone*#{File.basename(filename)}", base: backup_dir).sort
  total = undones.count
  count = total if count > total

  skipped = undones.slice!(0, count)
  undone = skipped.pop

  raise DoingRuntimeError, 'End of redo history' if undone.nil?

  redo_file = File.join(backup_dir, undone)

  FileUtils.move(redo_file, filename)

  skipped.each do |f|
    FileUtils.mv(File.join(backup_dir, f), File.join(backup_dir, f.sub(/^undone/, '')))
  end

  Doing.logger.warn('File update:', "restored undo step #{count}/#{total}")
  Doing.logger.debug('Backup:', "#{total - skipped.count - 1} redos remaining")
end

#restore_last_backup(filename = nil, count: 1) ⇒ Object

Restore the most recent backup. If a filename is provided, only backups of that filename will be used.

Parameters:

  • filename (defaults to: nil) —

    The filename to restore, if different from default

Raises:

  • (DoingRuntimeError)


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/doing/util_backup.rb', line 47

def restore_last_backup(filename = nil, count: 1)
  Doing.logger.benchmark(:restore_backup, :start)
  filename ||= Doing.config.settings['doing_file']

  result = get_backups(filename).slice(count - 1)
  raise DoingRuntimeError, 'End of undo history' if result.nil?

  backup_file = File.join(backup_dir, result)

  save_undone(filename)
  FileUtils.mv(backup_file, filename)
  prune_backups_after(File.basename(backup_file))
  Doing.logger.warn('File update:', "restored from #{result}")
  Doing.logger.benchmark(:restore_backup, :finish)
end

#select_backup(filename = nil) ⇒ Object

Select from recent backups. If a filename is provided, only backups of that filename will be used.

Parameters:

  • filename (defaults to: nil) —

    The filename to restore

Raises:

  • (DoingRuntimeError)


146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/doing/util_backup.rb', line 146

def select_backup(filename = nil)
  filename ||= Doing.config.settings['doing_file']

  options = get_backups(filename).each_with_object([]) do |file, arr|
    d, _base = date_of_backup(file)
    next if d.nil?
    arr.push("#{d.time_ago}\t#{File.join(backup_dir, file)}")
  end

  raise DoingRuntimeError, 'No backup files to load' if options.empty?

  backup_file = show_menu(options, filename)
  Util.write_to_file(File.join(backup_dir, "undone___#{File.basename(filename)}"), IO.read(filename), backup: false)
  FileUtils.mv(backup_file, filename)
  prune_backups_after(File.basename(backup_file))
  Doing.logger.warn('File update:', "restored from #{backup_file}")
end

#select_redo(filename = nil) ⇒ Object

Select from recent undos. If a filename is provided, only backups of that filename will be used.

Parameters:

  • filename (defaults to: nil) —

    The filename to restore

Raises:

  • (DoingRuntimeError)


106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/doing/util_backup.rb', line 106

def select_redo(filename = nil)
  filename ||= Doing.config.settings['doing_file']

  undones = Dir.glob("undone*#{File.basename(filename)}", base: backup_dir).sort

  raise DoingRuntimeError, 'End of redo history' if undones.empty?

  total = undones.count
  options = undones.each_with_object([]) do |file, arr|
    d, _base = date_of_backup(file)
    next if d.nil?

    arr.push("#{d.time_ago}\t#{File.join(backup_dir, file)}")
  end

  raise DoingRuntimeError, 'No backup files to load' if options.empty?

  backup_file = show_menu(options, filename)
  idx = undones.index(File.basename(backup_file))
  skipped = undones.slice!(idx, undones.count - idx)
  undone = skipped.shift

  redo_file = File.join(backup_dir, undone)

  FileUtils.move(redo_file, filename)

  skipped.each do |f|
    FileUtils.mv(File.join(backup_dir, f), File.join(backup_dir, f.sub(/^undone/, '')))
  end

  Doing.logger.warn('File update:', "restored undo step #{idx}/#{total}")
  Doing.logger.debug('Backup:', "#{total - skipped.count - 1} redos remaining")
end

#show_menu(options, filename) ⇒ Object

Raises:

  • (UserCancelled)


164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/doing/util_backup.rb', line 164

def show_menu(options, filename)
  if TTY::Which.which('colordiff')
    preview = 'colordiff -U 1'
    pipe = '| awk "(NR>2)"'
  elsif TTY::Which.which('git')
    preview = 'git --no-pager diff -U1 --color=always --minimal --word-diff'
    pipe = ' | awk "(NR>4)"'
  else
    preview = 'diff -U 1'
    pipe = if TTY::Which.which('delta')
             ' | delta --no-gitconfig --syntax-theme=1337'
           elsif TTY::Which.which('diff-so-fancy')
             ' | diff-so-fancy'
           elsif TTY::Which.which('ydiff')
             ' | ydiff -c always --wrap < /dev/tty'
           else
             cmd = 'sed -e "s/^-/`echo -e "\033[31m"`-/;s/^+/`echo -e "\033[32m"`+/;s/^@/`echo -e "\033[34m"`@/;s/\$/`echo -e "\033[0m"`/"'
             "| bash -c #{Shellwords.escape(cmd)}"
           end
    pipe += ' | awk "(NR>2)"'
  end

  result = Doing::Prompt.choose_from(options,
                                     prompt: 'Select a backup to restore',
                                     sorted: false,
                                     fzf_args: [
                                       '--delimiter="\t"',
                                       '--with-nth=1',
                                       %(--preview='#{preview} "#{filename}" {2} #{pipe}'),
                                       '--disabled',
                                       '--height=10',
                                       '--preview-window="right,70%,nowrap,follow"',
                                       '--header="Select a revision to restore"'
                                     ])
  raise UserCancelled unless result

  result.strip.split(/\t/).last
end

#write_backup(filename = nil) ⇒ Object

Writes a copy of the content to a dated backup file in a hidden directory

Parameters:

  • content —

    The data to back up



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/doing/util_backup.rb', line 209

def write_backup(filename = nil)
  Doing.logger.benchmark(:_write_backup, :start)
  filename ||= Doing.config.settings['doing_file']

  unless File.exist?(filename)
    Doing.logger.debug('Backup:', "original file doesn't exist (#{filename})")
    return
  end

  backup_file = File.join(backup_dir, "#{timestamp_filename}___#{File.basename(filename)}")
  # compressed = Zlib::Deflate.deflate(content)
  # Zlib::GzipWriter.open(backup_file + '.gz') do |gz|
  #   gz.write(IO.read(filename))
  # end

  FileUtils.cp(filename, backup_file)

  prune_backups(filename, Doing.config.settings['history_size'].to_i)
  clear_undone(filename)
  Doing.logger.benchmark(:_write_backup, :finish)
end