Skip to content
Kward Search API index

Module: Kward::PromptInterface::EditorFileSave

Defined in:
lib/kward/prompt_interface/editor/file_save.rb

Overview

Stages the new contents beside the destination before replacing it.

Defined Under Namespace

Classes: Conflict

Class Method Summary collapse

Class Method Details

.read(path) ⇒ Object

Raises:

  • (IOError)


11
12
13
14
15
16
# File 'lib/kward/prompt_interface/editor/file_save.rb', line 11

def read(path)
  return nil unless File.exist?(path) || File.symlink?(path)
  raise IOError, "Not a regular file: #{path}" unless File.file?(path)

  File.read(path)
end

.write(path, content, expected:) ⇒ Object



18
19
20
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
48
49
50
51
52
53
# File 'lib/kward/prompt_interface/editor/file_save.rb', line 18

def write(path, content, expected:)
  target = File.exist?(path) ? File.realpath(path) : path
  raise Conflict unless read(path) == expected

  mode = if expected.nil?
           0o666 & ~File.umask
         else
           File.open(target, "r+") do |file|
             stat = file.stat
             raise IOError, "Cannot atomically save a hard-linked file" if stat.nlink > 1

             stat.mode & 0o777
           end
         end

  Tempfile.create([".kward-edit-", ".tmp"], File.dirname(target)) do |file|
    file.binmode
    file.write(content)
    file.flush
    file.chmod(mode)
    file.fsync
    file.close
    raise Conflict unless read(path) == expected

    if expected.nil?
      # Do not replace an entry created after the conflict check.
      File.link(file.path, target)
    else
      raise Conflict unless File.realpath(path) == target

      File.rename(file.path, target)
    end
  end
rescue Errno::EEXIST
  raise Conflict
end