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_undone(filename = nil) ⇒ Object



77
78
79
80
81
82
83
# File 'lib/doing/util_backup.rb', line 77

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
# 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
end

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

Undo last undo

Parameters:

  • filename (defaults to: nil) —

    The filename

Raises:

  • (DoingRuntimeError)


53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/doing/util_backup.rb', line 53

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)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/doing/util_backup.rb', line 32

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



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/doing/util_backup.rb', line 129

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

  backup_file = show_menu(options, filename)
  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)


91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/doing/util_backup.rb', line 91

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

  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)


145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/doing/util_backup.rb', line 145

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



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/doing/util_backup.rb', line 190

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