2017-01-20 06:33:31 +01:00
|
|
|
require 'securerandom'
|
|
|
|
|
|
|
|
class TerminalSession
|
2017-01-27 00:04:46 +01:00
|
|
|
ZSH_BIN = ENV['TEST_ZSH_BIN'] || 'zsh'
|
|
|
|
|
2017-01-29 18:43:00 +01:00
|
|
|
def initialize(opts = {})
|
|
|
|
opts = {
|
|
|
|
width: 80,
|
|
|
|
height: 24,
|
|
|
|
prompt: '',
|
|
|
|
term: 'xterm-256color',
|
|
|
|
zsh_bin: ZSH_BIN
|
|
|
|
}.merge(opts)
|
|
|
|
|
2017-02-18 00:01:07 +01:00
|
|
|
@opts = opts
|
|
|
|
|
|
|
|
cmd="PS1=\"#{opts[:prompt]}\" TERM=#{opts[:term]} #{ZSH_BIN} -f"
|
2017-01-29 18:43:00 +01:00
|
|
|
tmux_command("new-session -d -x #{opts[:width]} -y #{opts[:height]} '#{cmd}'")
|
2017-01-20 06:33:31 +01:00
|
|
|
end
|
|
|
|
|
2017-02-28 19:12:50 +01:00
|
|
|
def tmux_socket_name
|
|
|
|
@tmux_socket_name ||= SecureRandom.hex(6)
|
|
|
|
end
|
|
|
|
|
2017-01-20 06:33:31 +01:00
|
|
|
def run_command(command)
|
|
|
|
send_string(command)
|
|
|
|
send_keys('enter')
|
2017-01-29 18:42:28 +01:00
|
|
|
|
|
|
|
self
|
2017-01-20 06:33:31 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def send_string(str)
|
2017-02-19 00:51:53 +01:00
|
|
|
tmux_command("send-keys -t 0 -l -- '#{str.gsub("'", "\\'")}'")
|
2017-01-29 18:42:28 +01:00
|
|
|
|
|
|
|
self
|
2017-01-20 06:33:31 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def send_keys(*keys)
|
|
|
|
tmux_command("send-keys -t 0 #{keys.join(' ')}")
|
2017-01-29 18:42:28 +01:00
|
|
|
|
|
|
|
self
|
2017-01-20 06:33:31 +01:00
|
|
|
end
|
|
|
|
|
2017-03-04 23:04:04 +01:00
|
|
|
def paste_string(str)
|
|
|
|
tmux_command("set-buffer -- '#{str}'")
|
|
|
|
tmux_command("paste-buffer -dpr -t 0")
|
|
|
|
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
2017-01-20 06:33:31 +01:00
|
|
|
def content(esc_seqs: false)
|
|
|
|
cmd = 'capture-pane -p -t 0'
|
|
|
|
cmd += ' -e' if esc_seqs
|
|
|
|
tmux_command(cmd).strip
|
|
|
|
end
|
|
|
|
|
2017-02-17 03:18:03 +01:00
|
|
|
def clear_screen
|
2017-01-20 06:33:31 +01:00
|
|
|
send_keys('C-l')
|
2017-02-17 23:33:09 +01:00
|
|
|
|
|
|
|
i = 0
|
|
|
|
until content == opts[:prompt] || i > 20 do
|
|
|
|
sleep(0.1)
|
|
|
|
i = i + 1
|
|
|
|
end
|
2017-01-29 18:42:28 +01:00
|
|
|
|
|
|
|
self
|
2017-01-20 06:33:31 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def destroy
|
|
|
|
tmux_command('kill-session')
|
|
|
|
end
|
|
|
|
|
|
|
|
def cursor
|
|
|
|
tmux_command("display-message -t 0 -p '\#{cursor_x},\#{cursor_y}'").
|
|
|
|
strip.
|
|
|
|
split(',').
|
|
|
|
map(&:to_i)
|
|
|
|
end
|
|
|
|
|
2018-05-15 19:36:20 +02:00
|
|
|
def attach!
|
|
|
|
tmux_command('attach-session')
|
|
|
|
end
|
|
|
|
|
2017-01-20 06:33:31 +01:00
|
|
|
private
|
|
|
|
|
2017-02-18 00:01:07 +01:00
|
|
|
attr_reader :opts
|
|
|
|
|
2017-01-20 06:33:31 +01:00
|
|
|
def tmux_command(cmd)
|
2017-01-29 18:43:20 +01:00
|
|
|
out = `tmux -u -L #{tmux_socket_name} #{cmd}`
|
2017-01-20 06:33:31 +01:00
|
|
|
|
2017-02-17 03:18:03 +01:00
|
|
|
raise("tmux error running: '#{cmd}'") unless $?.success?
|
2017-01-20 06:33:31 +01:00
|
|
|
|
|
|
|
out
|
|
|
|
end
|
|
|
|
end
|