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

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.



21
22
23
24
25
# File 'lib/binaryen/command.rb', line 21

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



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

def run(*arguments, stdin: nil, stderr: File::NULL)
  pid = nil
  command = build_command(*arguments)
  Timeout.timeout(@timeout) do
    pipe = IO.popen(command, "rb+", err: stderr)
    pid = pipe.pid
    pipe.write(stdin) if stdin
    pipe.close_write
    output = pipe
    Process.wait(pid)
    pid = nil

    if $CHILD_STATUS.exitstatus != 0
      raise Binaryen::NonZeroExitStatus, "command exited with status #{$CHILD_STATUS.exitstatus}: #{command}"
    end

    output
  end
end