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

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
# File 'lib/binaryen/command.rb', line 27

def run(*arguments, stdin: nil, stderr: File::NULL)
  command = build_command(*arguments)
  pipe = IO.popen(command, "rb+", err: stderr)
  pid = pipe.pid
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  remaining_timeout = @timeout

  if stdin
    start_time, remaining_timeout = write_to_pipe(pipe, stdin, start_time, remaining_timeout)
  end

  output, remaining_timeout = read_from_pipe(pipe, start_time, remaining_timeout)

  wait_or_kill(pid, start_time, remaining_timeout)

  output
end