Class: Ask::Tools::Code
- Inherits:
-
Ask::Tool
- Object
- Ask::Tool
- Ask::Tools::Code
- Defined in:
- lib/ask/tools/shell/code.rb
Overview
Write and execute Ruby code in a subprocess. Runs in a temp directory via ruby -e.
Constant Summary collapse
- MAX_OUTPUT_SIZE =
102_400
Instance Method Summary collapse
Instance Method Details
#execute(code:) ⇒ Object
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 |
# File 'lib/ask/tools/shell/code.rb', line 19 def execute(code:) Dir.mktmpdir("ask_code") do |_dir| stdout = StringIO.new stderr = StringIO.new exit_code = -1 begin Open3.popen3("ruby", "-e", code, chdir: Dir.pwd) do |stdin, out, err, wait_thr| stdin.close threads = [ Thread.new { IO.copy_stream(out, stdout) rescue nil }, Thread.new { IO.copy_stream(err, stderr) rescue nil } ] threads.each(&:join) exit_code = wait_thr.value.exitstatus end rescue => e return Ask::Result.error(message: "Code execution failed: #{e.}", metadata: { stdout: stdout.string, stderr: stderr.string }) end out_text = stdout.string err_text = stderr.string if out_text.length > MAX_OUTPUT_SIZE header = "[Output truncated to #{MAX_OUTPUT_SIZE / 1024}KB]\n" out_text = "#{header}#{out_text[-(MAX_OUTPUT_SIZE - header.length)..]}" end Ask::Result.ok(data: { stdout: out_text, stderr: err_text, exit_code: exit_code }) end end |