Merge pull request #1589 from noresources/os-outputof-selective-std-stream

os.outputof: add a second argument to select which stream to output
This commit is contained in:
Samuel Surtees 2021-03-10 20:28:25 +10:00 committed by GitHub
commit 750f140b9d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 4 deletions

View File

@ -455,12 +455,30 @@
--
-- Run a shell command and return the output.
--
-- @param cmd Command to execute
-- @param streams Standard stream(s) to output
-- Must be one of
-- - "both" (default)
-- - "output" Return standard output stream content only
-- - "error" Return standard error stream content only
--
function os.outputof(cmd)
function os.outputof(cmd, streams)
cmd = path.normalize(cmd)
streams = streams or "both"
local redirection
if streams == "both" then
redirection = " 2>&1"
elseif streams == "output" then
redirection = " 2>/dev/null"
elseif streams == "error" then
redirection = " 2>&1 1>/dev/null"
else
error ('Invalid stream(s) selection. "output", "error", or "both" expected.')
end
local pipe = io.popen(cmd .. " 2>&1")
local pipe = io.popen(cmd .. redirection)
local result = pipe:read('*a')
local success, what, code = pipe:close()
if success then

View File

@ -185,6 +185,24 @@
end
end
-- Check outputof content
function suite.outputof_streams_output()
if (os.istarget("macosx")
or os.istarget("linux")
or os.istarget("solaris")
or os.istarget("bsd"))
and os.isdir (_TESTS_DIR)
then
local ob, e = os.outputof ("ls " .. _TESTS_DIR .. "/base")
local oo, e = os.outputof ("ls " .. _TESTS_DIR .. "/base", "output")
test.isequal (oo, ob)
local s, e = string.find (oo, "test_os.lua")
test.istrue(s ~= nil)
local o, e = os.outputof ("ls " .. cwd .. "/base", "error")
test.istrue(o == nil or #o == 0)
end
end
--
-- os.translateCommand() tests