Module: Canopus::Workspace::PersistentUndo

Defined in:
lib/canopus/workspace/persistent_undo.rb

Constant Summary collapse

MAX_FILE_BYTES =
16 * 1024 * 1024
MAX_PROJECT_BYTES =
256 * 1024 * 1024
RECORD_NAME =
/\A[0-9a-f]{64}\.json\z/

Instance Method Summary collapse

Instance Method Details

#load_persistent_undo(buffer) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/canopus/workspace/persistent_undo.rb', line 17

def load_persistent_undo(buffer)
  return false unless persistent_undo_enabled? && persistent_undo_eligible?(buffer)
  path = persistent_undo_record_path(buffer.path)
  return false unless path && File.file?(path) && !File.symlink?(path)
  return false if File.size(path) > MAX_FILE_BYTES
  record = JSON.parse(File.binread(path), max_nesting: 100)
  return false unless persistent_undo_record_valid?(record, buffer, path)
  buffer.restore_persistent_undo!(record)
rescue StandardError
  false
end

#persistent_undo_directory ⇒ Object



13
14
15
# File 'lib/canopus/workspace/persistent_undo.rb', line 13

def persistent_undo_directory
  File.join(@root, ".canopus", "undo")
end

#save_persistent_undo(buffer) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/canopus/workspace/persistent_undo.rb', line 29

def save_persistent_undo(buffer)
  return false unless persistent_undo_enabled? && persistent_undo_eligible?(buffer)
  record_path = persistent_undo_record_path(buffer.path)
  return false unless record_path && persistent_undo_directory_ready?
  record = buffer.persistent_undo_record(max_entries: @settings["persistent_undo"]["max_entries"])
  unless record
    persistent_undo_delete(record_path)
    return true
  end
  stat = File.stat(buffer.path)
  digest = buffer.disk_digest || Digest::SHA256.file(buffer.path).hexdigest
  record.merge!("version" => 1, "project_root" => @root,
    "relative_path" => persistent_undo_relative_path(buffer.path), "saved_at" => Time.now.to_i,
    "file" => {"size" => stat.size, "digest" => digest, "dev" => stat.dev, "ino" => stat.ino})
  payload = JSON.generate(record)
  return false if stat.size > MAX_FILE_BYTES || payload.bytesize > MAX_FILE_BYTES
  persistent_undo_make_room(record_path, payload.bytesize)
  return false if persistent_undo_project_bytes(except: record_path) + payload.bytesize > MAX_PROJECT_BYTES
  Tempfile.create([".undo-", ".json"], persistent_undo_directory, binmode: true) do |file|
    file.chmod(0o600)
    file.write(payload)
    file.flush
    file.fsync
    file.close
    File.rename(file.path, record_path)
  end
  true
rescue StandardError
  false
end