cmdopt2/parser: add usage overload for FILE*

This commit is contained in:
Danny Robson 2022-03-18 12:18:22 +10:00
parent cd2b6be6e8
commit c5e4811efc
2 changed files with 34 additions and 11 deletions

View File

@ -184,29 +184,51 @@ parser::parse (int const argc, const char *const *argv)
///////////////////////////////////////////////////////////////////////////////
void
parser::usage (int argc, char const * const* argv, std::ostream &os) const
{
os << "Usage:";
template <typename OutputT>
static void
usage (
int argc,
char const * const* argv,
std::vector<cruft::cmdopt2::positional> const &positional,
std::vector<cruft::cmdopt2::keyword> const &keyword,
OutputT &output
) {
fmt::print (output, "Usage:");
if (argc > 0)
os << ' ' << argv[0];
fmt::print (output, " {}", argv[0]);
static char constexpr OPTIONAL[2] { '[', ']' };
static char constexpr REQUIRED[2] { '<', '>' };
for (auto const &arg: m_keyword) {
for (auto const &arg: keyword) {
auto const &delimiters = arg.required ? REQUIRED : OPTIONAL;
if (arg.short_)
os << ' ' << delimiters[0] << '-' << *arg.short_ << delimiters[1];
fmt::print (output, " {}-{}{}", delimiters[0], '-', *arg.short_, delimiters[1]);
if (arg.long_)
os << ' ' << delimiters[0] << "--" << *arg.long_ << delimiters[1];
fmt::print (output, " {}--{}{}", delimiters[0], "--", *arg.long_, delimiters[1]);
}
for (auto const &arg: m_positional) {
for (auto const &arg: positional) {
auto const &delimiters = arg.required ? REQUIRED : OPTIONAL;
os << ' ' << delimiters[0] << arg.name << delimiters[1];
fmt::print (output, " {}{}{}", delimiters[0], arg.name, delimiters[1]);
}
os << '\n';
fmt::print (output, "\n");
}
//-----------------------------------------------------------------------------
void
parser::usage (int argc, char const * const* argv, std::ostream &os) const
{
::usage (argc, argv, m_positional, m_keyword, os);
}
//-----------------------------------------------------------------------------
void
parser::usage (int argc, char const * const* argv, FILE *fp) const
{
::usage (argc, argv, m_positional, m_keyword, fp);
}

View File

@ -22,6 +22,7 @@ namespace cruft::cmdopt2 {
positional& add (positional const&) &;
keyword& add (keyword const&) &;
void usage (int argc, char const * const* argv, FILE*) const;
void usage (int argc, char const * const* argv, std::ostream&) const;
private: