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)")
```

Constant Summary collapse

MAX_OUTPUT_SIZE =
256 * 1024 * 1024
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.



23
24
25
26
27
# File 'lib/binaryen/command.rb', line 23

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: nil) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/binaryen/command.rb', line 29

def run(*arguments, stdin: nil, stderr: nil)
  args = [@cmd] + arguments + @default_args
  child = POSIX::Spawn::Child.new(*args, input: stdin, timeout: @timeout, max: MAX_OUTPUT_SIZE)
  stderr&.write(child.err)
  status = child.status

  raise Binaryen::NonZeroExitStatus, "command exited with status #{status.exitstatus}" unless status.success?

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