Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions lib/spoom/context/exec.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# typed: strict
# frozen_string_literal: true

require "shellwords"

module Spoom
class ExecResult < T::Struct
const :out, String
Expand Down Expand Up @@ -30,11 +32,21 @@ def exec(command, capture_err: true)
Bundler.with_unbundled_env do
opts = { chdir: absolute_path } #: Hash[Symbol, untyped]

# When Ruby is wrapped in another dev environment (e.g. Nix), that environment might set
# env variables that cause Sorbet (or other tools) to link to incorrect versions of
# dependencies.
#
# In the case of Sorbet, this can lead to corrupted JSON output.
#
# Executing the command directly through the shell bypasses any Ruby wrappers and
# ensures that we are using the versions of tools that are default on the system.
command_with_shell = "/bin/sh -c #{command.shellescape}"

if capture_err
out, err, status = Open3.capture3(command, opts)
out, err, status = Open3.capture3(command_with_shell, opts)
ExecResult.new(out: out, err: err, status: T.must(status.success?), exit_code: T.must(status.exitstatus))
else
out, status = Open3.capture2(command, opts)
out, status = Open3.capture2(command_with_shell, opts)
ExecResult.new(out: out, err: nil, status: T.must(status.success?), exit_code: T.must(status.exitstatus))
end
end
Expand Down
8 changes: 5 additions & 3 deletions test/spoom/context/exec_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ class ExecTest < Minitest::Test
def test_context_exec
context = Context.mktmp!

assert_raises(Errno::ENOENT) do
context.exec("command/not/found")
end
# Test that unknown commands return a failed status (not raise an exception)
# due to shell wrapping in exec method
res = context.exec("command_that_does_not_exist")
refute(res.status)
refute_empty(res.err)

Comment thread
egiurleo marked this conversation as resolved.
res = context.exec("echo 'Hello, world!'")
assert_equal("Hello, world!\n", res.out)
Expand Down