Class: Binaryen::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/binaryen/command.rb

Overview

Wrapper around a binaryen executable command with a timeout and streaming IO.

Examples:

Running wasm-opt


```ruby
command = Binaryen::Command.new("wasm-opt", timeout: 10)
optimized_wasm = command.run("-O4", stdin: "(module)")
```

Defined Under Namespace

Classes: TimeoutChecker

Constant Summary collapse

DEFAULT_ARGS_FOR_COMMAND =
{
  "wasm-opt" => ["--output=-"],
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(cmd, timeout: 10, ignore_missing: false) ⇒ Command

Returns a new instance of Command.



37
38
39
40
41
# File 'lib/binaryen/command.rb', line 37

def initialize(cmd, timeout: 10, ignore_missing: false)
  @cmd = command_path(cmd, ignore_missing) || raise(ArgumentError, "command not found: #{cmd}")
  @timeout = timeout
  @default_args = DEFAULT_ARGS_FOR_COMMAND.fetch(cmd, [])
end

Instance Method Details

#run(*arguments, stdin: nil, stderr: File::NULL) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/binaryen/command.rb', line 43

def run(*arguments, stdin: nil, stderr: File::NULL)
  args = build_arguments(*arguments)
  child = POSIX::Spawn::Child.new(@cmd, *args, input: stdin, timeout: @timeout)
  if child.status && !child.status.success?
    err_io = stderr.is_a?(String) ? File.open(stderr, "w") : stderr
    err_io.binmode
    err_io.write(child.err)
    err_io.rewind
    raise NonZeroExitStatus, "command exited with non-zero status: #{child.status}"
  end

  child.out
rescue POSIX::Spawn::TimeoutExceeded => e
  raise Timeout::Error, e.message
end