Skip to content

Instantly share code, notes, and snippets.

@mpeterv
Last active July 31, 2016 19:01
Show Gist options
  • Save mpeterv/132cae34b55ae65394a6fc8f847010a8 to your computer and use it in GitHub Desktop.
Save mpeterv/132cae34b55ae65394a6fc8f847010a8 to your computer and use it in GitHub Desktop.
local lua = "lua"
local i = 0
while arg[i] do
lua = arg[i]
i = i - 1
end
local is_windows = package.config:sub(1, 1) == "\\"
local function quote_arg(argument)
if is_windows then
if argument == "" or argument:find('[ \f\t\v"]') then
argument = '"' .. argument:gsub('(\\*)"', '%1%1\\"'):gsub('\\+$', "%0%0") .. '"'
end
return (argument:gsub('["^<>!|&%%]', "^%0"))
else
if argument == "" or argument:find('[^a-zA-Z0-9_@%+=:,./-]') then
argument = "'" .. argument:gsub("'", "'\\''") .. "'"
end
return argument
end
end
local function quote_command(arguments)
local quoted_arguments = {}
for i, argument in ipairs(arguments) do
quoted_arguments[i] = quote_arg(argument)
end
return table.concat(quoted_arguments, " ")
end
math.randomseed(tonumber(arg[1]))
local chars = ""
for i = 1, 255 do
local char = string.char(i)
if char ~= "\26" and char ~= "\r" and char ~= "\n" then
chars = chars .. char
end
end
local function random_arg()
local res = ""
for _ = 1, math.random(15) + math.random(15) do
local index = math.random(#chars)
res = res .. chars:sub(index, index)
end
return res
end
local function dump(s)
for i = 1, #s do
print(i, s:byte(i, i))
end
end
local function test(nargs)
local args = {lua, "script.lua"}
for _ = 1, nargs do
local new_arg = random_arg()
print(new_arg)
table.insert(args, new_arg)
end
local cmd = quote_command(args)
print("Command: " .. cmd)
local handler = assert(io.popen(cmd, "rb"))
local output = handler:read("*a")
handler:close()
print("Output: " .. output)
local printed_args = {}
for printed_arg in output:gmatch("[^\0]+") do
table.insert(printed_args, printed_arg)
end
for i = 1, nargs do
if printed_args[i] ~= args[i + 2] then
print("Got: " .. tostring(printed_args[i]))
if printed_args[i] then
dump(printed_args[i])
end
print("Expected: " .. args[i + 2])
dump(args[i + 2])
os.exit()
end
end
end
while true do
test(10)
end
for _, argument in ipairs(arg) do
io.stdout:write(argument, "\0")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment