Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return standard output in popen_write #8541

Merged
merged 3 commits into from
Sep 2, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
42 changes: 40 additions & 2 deletions Library/Homebrew/test/utils/popen_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,49 @@
end

describe "::popen_write" do
it "with supports writing to a command's standard input" do
let(:foo) { mktmpdir/"foo" }

before { foo.write "Foo\n" }

it "supports writing to a command's standard input" do
subject.popen_write("grep", "-q", "success") do |pipe|
pipe.write("success\n")
pipe.write "success\n"
end
expect($CHILD_STATUS).to be_a_success
end

it "returns the command's standard output before writing" do
child_stdout = subject.popen_write("cat", foo, "-") do |pipe|
pipe.write "Bar\n"
end
expect($CHILD_STATUS).to be_a_success
expect(child_stdout).to eq <<~EOS
Foo
Bar
EOS
end

it "returns the command's standard output after writing" do
child_stdout = subject.popen_write("cat", "-", foo) do |pipe|
pipe.write "Bar\n"
end
expect($CHILD_STATUS).to be_a_success
expect(child_stdout).to eq <<~EOS
Bar
Foo
EOS
end

it "supports interleaved writing between two reads" do
child_stdout = subject.popen_write("cat", foo, "-", foo) do |pipe|
pipe.write "Bar\n"
end
expect($CHILD_STATUS).to be_a_success
expect(child_stdout).to eq <<~EOS
Foo
Bar
Foo
EOS
end
end
end
21 changes: 19 additions & 2 deletions Library/Homebrew/utils/popen.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,25 @@ def self.safe_popen_read(*args, **options, &block)
raise ErrorDuringExecution.new(args, status: $CHILD_STATUS, output: [[:stdout, output]])
end

def self.popen_write(*args, **options, &block)
popen(args, "wb", options, &block)
def self.popen_write(*args, **options)
popen(args, "w+b", options) do |pipe|
output = ""

# Before we yield to the block, capture as much output as we can
loop do
output += pipe.read_nonblock(4096)
rescue IO::WaitReadable, EOFError
break
end

yield pipe
pipe.close_write
IO.select([pipe])

# Capture the rest of the output
output += pipe.read
output.freeze
end
end

def self.safe_popen_write(*args, **options, &block)
Expand Down