class LTools::Tool

Attributes

cmd[R]
stderr[R]
stdin[R]
stdout[R]
verbose[RW]

Public Class Methods

check?() click to toggle source
# File lib/core/tool.rb, line 97
def self.check?
  system "hash #{@name} 2>&-"
  $?.success?
end
inherited(child_class) click to toggle source
# File lib/core/tool.rb, line 93
def self.inherited(child_class)
  LTools.add_tool(child_class)
end
new(*args) click to toggle source
# File lib/core/tool.rb, line 21
def initialize(*args)
  tool, *args = args

  # 检测参数类型进行变换,支持一下格式:
  #   args = 'echo 1231'
  #   args = ['echo', '1231']
  #   args = [['echo', '1231']]
  case tool
  when String
    if args.empty? and tool.include? ' '
      tool, *args = Shellwords.split(tool)
    end
  when Array
    tool, *args = tool
  else
    raise
  end

  @cmd = args.unshift(tool).map(&:to_s)
  @process = ChildProcess.build(*@cmd)

  @stdout, @stdout_w = IO.pipe
  @process.io.stdout = @stdout_w 

  @stderr, @stderr_w = IO.pipe
  @process.io.stderr = @stderr_w

  @verbose = true if LTools.verbose
end

Public Instance Methods

command() click to toggle source
# File lib/core/tool.rb, line 74
def command
  @cmd.map{|str|
    if str.include?(' ')
      if str.include? '"'
        "'#{str}'"
      else
        "\"#{str}\""
      end
    else
      str
    end
  }.join ' '
end
io_inherit!() click to toggle source
# File lib/core/tool.rb, line 88
def io_inherit!
  @inherit = true
  @process.io.inherit!
end
start() click to toggle source
# File lib/core/tool.rb, line 51
def start
  @process.duplex    = true unless @inherit
  @process.start
  @stdin = @process.io.stdin unless @inherit
  if @verbose
    puts "[#{'+'.light_green.bold}] #{self.class.to_s.light_yellow} (pid: #{pid})"
    puts "  #{?$.light_red.bold} #{command}"
    puts
  end
end
stop() click to toggle source
# File lib/core/tool.rb, line 68
def stop
  @process.stop
  @stdout_w.close
  @stderr_w.close
end
wait() click to toggle source
# File lib/core/tool.rb, line 62
def wait
  @process.wait
  @stdout_w.close
  @stderr_w.close
end