Class: Runcmd::Cli::RunCommand

Inherits:
Clamp::Command
  • Object
show all
Defined in:
lib/runcmd/cli/run_command.rb

Instance Method Summary collapse

Instance Method Details

#executeObject



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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/runcmd/cli/run_command.rb', line 17

def execute
  cmd = command_list.shift
  args = command_list

  stderr_reader, stderr_writer = IO.pipe

  env = {
    "LINES" => IO.console.winsize.first.to_s,
    "COLUMNS" => IO.console.winsize.last.to_s
  }

  log = File.new record, "w" if record

  stdout,stdin,pid = PTY.spawn(env, cmd, *args, err: stderr_writer.fileno)
  stderr_writer.close

  stdin_thr = Thread.new do
    while c = $stdin.getch
      case c
      when "\u0003"
        # control+c
        stdin.print c
      else
        stdin.print c
        log.print c if record
      end
    end

    stdin.close
  end

  stdout_thr = Thread.new do
    while c = stdout.getc
      print c
      log.print c if record
    end
  end

  stderr_thr = Thread.new do
    while c = stderr_reader.getc
      print c
      log.print c if record
    end
  end

  stdout_thr.join
  stdin_thr.kill

  stdin_thr.join
  stderr_thr.join

  log.close if record
end