-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcommand.rb
More file actions
92 lines (76 loc) · 2.61 KB
/
Copy pathcommand.rb
File metadata and controls
92 lines (76 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# frozen_string_literal: true
require "timeout"
require "tempfile"
module Binaryen
class Command
DEFAULT_MAX_OUTPUT_SIZE = 256 * 1024 * 1024 * 1024 # 256 MiB
DEFAULT_TIMEOUT = 10
DEFAULT_ARGS_FOR_COMMAND = {}.freeze
def initialize(cmd, timeout: DEFAULT_TIMEOUT, max_output_size: DEFAULT_MAX_OUTPUT_SIZE, 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, [])
@max_output_size = max_output_size
end
def run(*arguments, stdin: nil, stderr: nil)
args = [@cmd] + arguments + @default_args
Timeout.timeout(@timeout) do
spawn_command(*args, stderr: stderr, stdin: stdin)
end
end
private
def command_path(cmd, ignore_missing)
Dir[File.join(Binaryen.bindir, cmd)].first || (ignore_missing && cmd)
end
def spawn_command(*args, stderr: nil, stdin: nil)
pid = nil
Tempfile.create("binaryen-input") do |in_write|
in_write.binmode
in_write.write(stdin) if stdin
in_write.close
Tempfile.create("binaryen-output") do |tmpfile|
tmpfile.close
File.open(File::NULL, "w") do |devnull|
IO.pipe do |err_read, err_write|
pid = Process.spawn(
*args,
"--output=#{tmpfile.path}",
in_write.path,
in: devnull,
out: devnull,
err: err_write,
)
err_write.close
_, status = Process.waitpid2(pid)
pid = nil
stderr&.write(err_read.read)
err_read.close
if status.signaled?
raise Binaryen::Signal, "command terminated by signal #{status.termsig}"
elsif status.exited? && !status.success?
raise Binaryen::NonZeroExitStatus, "command exited with status #{status.exitstatus}"
elsif File.size(tmpfile.path) > @max_output_size
raise Binaryen::MaximumOutputExceeded, "maximum output size exceeded (#{@max_output_size} bytes)"
end
File.binread(tmpfile.path)
end
end
rescue
if pid
begin
Process.kill(:KILL, pid)
rescue SystemCallError
# Expected
end
begin
Process.wait(pid, Process::WNOHANG)
rescue SystemCallError
# Expected
end
end
raise
end
end
end
end
end