Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- require 'rubygems'
- require 'optparse'
- require 'socket'
- require 'json'
- require 'readline'
- @interactive = STDIN.isatty and STDOUT.isatty
- def readline_hist
- if @interactive
- line = Readline.readline('$ ', true)
- else
- line = Readline.readline
- end
- return nil if line.nil?
- if line =~ /^\s*$/ or Readline::HISTORY.to_a[-2] == line
- Readline::HISTORY.pop
- end
- line
- end
- $runopts = {}
- $runopts[:verbose] = 0
- $runopts[:port] = 3300
- OptionParser.new do |opts|
- opts.banner = "#{__FILE__} -p port"
- opts.on('-p', '--port [LEVEL]', /^[0-9]+$/, 'Port') do |opt|
- $runopts[:port] = opt ? opt.to_i : 1
- end
- opts.on('-f', '--force', 'Reconnect on fail') do |opt|
- $runopts[:force] = opt
- end
- end.parse!
- sock = nil
- if $runopts[:force]
- while not sock
- waited = false
- begin
- sock = TCPSocket.open('localhost', $runopts[:port])
- rescue
- waited = true
- sleep 1
- print '.' if @interactive
- STDOUT.flush
- end
- print "\n" if waited
- end
- else
- begin
- sock = TCPSocket.open('localhost', $runopts[:port])
- rescue
- puts "Unable to connect."
- Process.exit
- end
- end
- last_cmd = ''
- next_cmd = nil
- while (c = next_cmd) or (c = readline_hist)
- if c.count(";") > 0
- c, next_cmd = c.split(";", 2)
- end
- c = c.strip
- skip = false
- cmd = ''
- case c
- when ''
- skip = true
- when 'ping'
- cmd = 'system.ping'
- when 'help'
- puts "WAT"
- skip = true
- when 'l'
- cmd = last_cmd
- when 'qs'
- sock.puts({"exec" => "system.exit"}.to_json)
- puts "Bye." if @interactive
- Process.exit
- when 'q'
- puts "Bye." if @interactive
- Process.exit
- else
- cmd = c
- end
- if not skip
- cmd_class, cmd_name = cmd.split('.')
- last_cmd = cmd
- begin
- sock.puts({"exec" => "#{cmd_class}.#{cmd_name}"}.to_json)
- rescue Exception => e
- if $runopts[:force]
- print 'Connection lost, reconnecting ' if @interactive
- STDOUT.flush
- sock.close
- sock = nil
- while not sock
- begin
- sock = TCPSocket.open('localhost', $runopts[:port])
- rescue
- end
- sleep 1
- print '.' if @interactive
- STDOUT.flush
- end
- print "\n"
- sock.puts({"exec" => "#{cmd_class}.#{cmd_name}"}.to_json)
- else
- Process.exit
- end
- end
- sleep 0.2
- begin
- ret = JSON.parse(sock.gets)
- rescue Exception => e
- end
- if @``interactive
- puts "Status: #{ret['status']}"
- puts "Return: #{ret['return'].inspect}"
- else
- puts ret['status']
- puts ret['return'].inspect
- end
- end
- end
Add Comment
Please, Sign In to add comment