Top Level Namespace

Defined Under Namespace

Modules: Opal

Constant Summary collapse

SystemRunner =

Generic runner that will resort to calling an external program.

->(data, &block) {
  options  = data[:options] || {}
  builder  = data.fetch(:builder).call
  output   = data.fetch(:output)

  env      = options.fetch(:env, {})
  debug    = options.fetch(:debug, false) || RUBY_ENGINE == 'opal'

  code = builder.to_s
  # Temporary issue with UTF-8, Base64 and source maps
  code += "\n" + builder.source_map.to_data_uri_comment unless RUBY_ENGINE == 'opal'

  ext = builder.output_extension

  tempfile =
    if debug
      File.new("opal-nodejs-runner.#{ext}", 'wb')
    else
      Tempfile.new(['opal-system-runner', ".#{ext}"], mode: File::BINARY)
    end

  tempfile.write code
  cmd = block.call tempfile
  tempfile.close

  if RUBY_PLATFORM == 'opal'
    # Opal doesn't support neither `out:` nor `IO.try_convert` nor `open3`
    system(env, *cmd)
    $?.exitstatus
  elsif IO.try_convert(output) && RUBY_PLATFORM != 'java'
    system(env, *cmd, out: output)
    $?.exitstatus
  else
    # JRuby (v9.2) doesn't support using `out:` to redirect output.
    require 'open3'
    captured_output, status = Open3.capture2(env, *cmd)
    output.write captured_output
    status.exitstatus
  end
}