class TrainSH::Command

Constants

MAGIC_STRING

Attributes

connection[W]

Public Class Methods

new(command, connection) click to toggle source
# File lib/trainsh/session.rb, line 12
def initialize(command, connection)
  @command = command
  @connection = connection

  @prefixes = []
  @postfixes = []
end

Public Instance Methods

aggregate_commands() click to toggle source
# File lib/trainsh/session.rb, line 70
def aggregate_commands
  separator = "\necho #{MAGIC_STRING}\n"

  commands = @prefixes.reverse.map { |ary| ary[:command] }
  commands << "#{@command}\n#{save_exit_code}"
  commands.concat(@postfixes.map { |ary| ary[:command] })

  commands.join(separator)
end
parse(result) click to toggle source
# File lib/trainsh/session.rb, line 62
def parse(result)
  result.stdout
        .gsub(/\r\n/, "\n")
        .gsub(/ *$/, '')
        .split(MAGIC_STRING)
        .map(&:strip)
end
postfix(postfix_command, &block) click to toggle source
# File lib/trainsh/session.rb, line 27
def postfix(postfix_command, &block)
  @postfixes << {
    command: postfix_command,
    block: block
  }
end
prefix(prefix_command, &block) click to toggle source
# File lib/trainsh/session.rb, line 20
def prefix(prefix_command, &block)
  @prefixes << {
    command: prefix_command,
    block: block
  }
end
run() click to toggle source
# File lib/trainsh/session.rb, line 34
def run
  result = @connection.run_command aggregate_commands
  stdouts = parse(result)

  prefixes_stdout = stdouts.first(@prefixes.count).reverse
  @prefixes.each_with_index do |prefix, idx|
    next if prefix[:block].nil?

    prefix[:block].call prefixes_stdout[idx]
  end
  @prefixes.count.times { stdouts.shift } unless @prefixes.empty?

  postfixes_stdout = stdouts.last(@postfixes.count)
  @postfixes.each_with_index do |postfix, idx|
    next if postfix[:block].nil?

    postfix[:block].call postfixes_stdout[idx]
  end
  @postfixes.count.times { stdouts.pop } unless @postfixes.empty?

  raise 'Pre-/Postfix command processing ended up with more than one remaining stdout' if stdouts.count > 1

  result.stdout = stdouts.first
  # result.stderr = "" # TODO
  result.exit_status = 0 # TODO
  result
end
save_exit_code() click to toggle source
# File lib/trainsh/session.rb, line 80
def save_exit_code
  @connection.platform.windows? ? "$#{TrainSH::EXITCODE_VAR}=$LastExitCode" : "export #{TrainSH::EXITCODE_VAR}=$?"
end