Method: Doing::WWID#fork_editor

Defined in:
lib/doing/wwid/editor.rb

#fork_editor(input = '', message: :default) ⇒ Object

Create a process for an editor and wait for the file handle to return

Parameters:

  • input (String) (defaults to: '')

    Text input for editor

Raises:

  • (MissingEditor)


10
11
12
13
14
15
16
17
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
# File 'lib/doing/wwid/editor.rb', line 10

def fork_editor(input = '', message: :default)
  # raise NonInteractive, 'Non-interactive terminal' unless $stdout.isatty || ENV['DOING_EDITOR_TEST']

  raise MissingEditor, 'No EDITOR variable defined in environment' if Util.default_editor.nil?

  tmpfile = Tempfile.new(['doing_temp', '.doing'])

  File.open(tmpfile.path, 'w+') do |f|
    f.puts input
    unless message.nil?
      f.puts message == :default ? '# First line is the entry title, lines after are added as a note' : message
    end
  end

  pid = Process.fork { system("#{Util.editor_with_args} #{tmpfile.path}") }

  trap('INT') do
    begin
      Process.kill(9, pid)
    rescue StandardError
      Errno::ESRCH
    end
    tmpfile.unlink
    tmpfile.close!
    exit 0
  end

  Process.wait(pid)

  begin
    if $?.exitstatus == 0
      input = IO.read(tmpfile.path)
    else
      exit_now! 'Cancelled'
    end
  ensure
    tmpfile.close
    tmpfile.unlink
  end

  input.split(/\n/).delete_if(&:ignore?).join("\n")
end