Pad long usage messages

Long usage messages are split into lines. A margin is added so that they line up under "Usage: " part of the message.
This commit is contained in:
mpeterv
2014-02-18 13:28:06 +04:00
parent ccad58ef50
commit 07af666206
3 changed files with 23 additions and 11 deletions

View File

@@ -44,7 +44,8 @@ describe("tests related to help message generation", function()
:args "*" :args "*"
assert.equal(table.concat({ assert.equal(table.concat({
"Usage: foo [-h] <first> <second-and-third> <second-and-third> [<maybe-fourth>] [<others>] ...", "Usage: foo [-h] <first> <second-and-third> <second-and-third>",
" [<maybe-fourth>] [<others>] ...",
"", "",
"Arguments: ", "Arguments: ",
" first", " first",

View File

@@ -18,9 +18,10 @@ describe("tests related to usage message generation", function()
parser:argument "others" parser:argument "others"
:args "*" :args "*"
assert.equal( assert.equal(table.concat({
[=[Usage: foo <first> <second-and-third> <second-and-third> [<maybe-fourth>] [<others>] ...]=], "Usage: foo <first> <second-and-third> <second-and-third>",
parser:prepare():get_usage() " [<maybe-fourth>] [<others>] ..."
}, "\r\n"), parser:prepare():get_usage()
) )
end) end)

View File

@@ -309,28 +309,38 @@ function Parser:update_charset(charset)
return charset return charset
end end
local max_usage_width = 70
local usage_welcome = "Usage: "
function Parser:get_usage() function Parser:get_usage()
if not self._usage then if not self._usage then
local buf = {"Usage:", self._name} local lines = {usage_welcome .. self._name}
local function add(s)
if #lines[#lines]+1+#s <= max_usage_width then
lines[#lines] = lines[#lines] .. " " .. s
else
lines[#lines+1] = (" "):rep(#usage_welcome) .. s
end
end
for _, elements in ipairs{self._options, self._arguments} do for _, elements in ipairs{self._options, self._arguments} do
for _, element in ipairs(elements) do for _, element in ipairs(elements) do
table.insert(buf, element:get_usage()) add(element:get_usage())
end end
end end
if #self._commands > 0 then if #self._commands > 0 then
if self._require_command then if self._require_command then
table.insert(buf, "<command>") add("<command>")
else else
table.insert(buf, "[<command>]") add("[<command>]")
end end
table.insert(buf, "...") add("...")
end end
-- TODO: prettify self._usage = table.concat(lines, "\r\n")
self._usage = table.concat(buf, " ")
end end
return self._usage return self._usage