1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
|
#include "file_io.hh"
#include "option.hh"
#include "sanity.hh"
#include "ui.hh"
using std::map;
using std::pair;
using std::set;
using std::string;
using std::vector;
namespace option {
option_error::option_error(std::string const & str)
: std::invalid_argument((F("option error: %s") % str).str())
{}
unknown_option::unknown_option(std::string const & opt)
: option_error((F("unknown option '%s'") % opt).str())
{}
missing_arg::missing_arg(std::string const & opt)
: option_error((F("missing argument to option '%s'") % opt).str())
{}
extra_arg::extra_arg(std::string const & opt)
: option_error((F("option '%s' does not take an argument") % opt).str())
{}
bad_arg::bad_arg(std::string const & opt, std::string const & arg)
: option_error((F("bad argument '%s' to option '%s'") % arg % opt).str())
{}
bad_arg::bad_arg(std::string const & opt,
std::string const & arg,
std::string const & reason)
: option_error((F("bad argument '%s' to option '%s': %s")
% arg % opt % reason).str())
{}
bad_arg_internal::bad_arg_internal(string const & str)
: reason(str)
{}
void splitname(string const & from, string & name, string & n)
{
// from looks like "foo" or "foo,f"
string::size_type comma = from.find(',');
name = from.substr(0, comma);
if (comma != string::npos)
n = from.substr(comma+1, 1);
else
n = "";
// "o" is equivalent to ",o"; it gives an option
// with only a short name
if (name.size() == 1)
{
I(n.empty());
n = name;
name = "";
}
}
concrete_option::concrete_option()
: has_arg(false)
{}
concrete_option::concrete_option(std::string const & names,
std::string const & desc,
bool arg,
boost::function<void (std::string)> set,
boost::function<void ()> reset)
{
description = desc;
splitname(names, longname, shortname);
I(!description.empty() || !longname.empty() || !shortname.empty());
// If an option has a name (ie, can be set), it must have a setter function
I(set || (longname.empty() && shortname.empty()));
has_arg = arg;
setter = set;
resetter = reset;
}
bool concrete_option::operator<(concrete_option const & other) const
{
if (longname != other.longname)
return longname < other.longname;
if (shortname != other.shortname)
return shortname < other.shortname;
return description < other.description;
}
concrete_option_set
operator | (concrete_option const & a, concrete_option const & b)
{
return concrete_option_set(a) | b;
}
concrete_option_set::concrete_option_set()
{}
concrete_option_set::concrete_option_set(std::set<concrete_option> const & other)
: options(other)
{}
concrete_option_set::concrete_option_set(concrete_option const & opt)
{
options.insert(opt);
}
// essentially the opposite of std::bind1st
class discard_argument
{
boost::function<void()> functor;
public:
discard_argument(boost::function<void()> const & from)
: functor(from)
{}
void operator()(std::string const &)
{ return functor(); }
};
concrete_option_set &
concrete_option_set::operator()(string const & names,
string const & desc,
boost::function<void ()> set,
boost::function<void ()> reset)
{
options.insert(concrete_option(names, desc, false, discard_argument(set), reset));
return *this;
}
concrete_option_set &
concrete_option_set::operator()(string const & names,
string const & desc,
boost::function<void (string)> set,
boost::function<void ()> reset)
{
options.insert(concrete_option(names, desc, true, set, reset));
return *this;
}
concrete_option_set
concrete_option_set::operator | (concrete_option_set const & other) const
{
concrete_option_set combined;
std::set_union(options.begin(), options.end(),
other.options.begin(), other.options.end(),
std::inserter(combined.options, combined.options.begin()));
return combined;
}
void concrete_option_set::reset() const
{
for (std::set<concrete_option>::const_iterator i = options.begin();
i != options.end(); ++i)
{
if (i->resetter)
i->resetter();
}
}
static void
tokenize_for_command_line(string const & from, vector<string> & to)
{
// Unfortunately, the tokenizer in basic_io is too format-specific
to.clear();
enum quote_type {none, one, two};
string cur;
quote_type type = none;
bool have_tok(false);
for (string::const_iterator i = from.begin(); i != from.end(); ++i)
{
if (*i == '\'')
{
if (type == none)
type = one;
else if (type == one)
type = none;
else
{
cur += *i;
have_tok = true;
}
}
else if (*i == '"')
{
if (type == none)
type = two;
else if (type == two)
type = none;
else
{
cur += *i;
have_tok = true;
}
}
else if (*i == '\\')
{
if (type != one)
++i;
N(i != from.end(), F("Invalid escape in --xargs file"));
cur += *i;
have_tok = true;
}
else if (string(" \n\t").find(*i) != string::npos)
{
if (type == none)
{
if (have_tok)
to.push_back(cur);
cur.clear();
have_tok = false;
}
else
{
cur += *i;
have_tok = true;
}
}
else
{
cur += *i;
have_tok = true;
}
}
if (have_tok)
to.push_back(cur);
}
void concrete_option_set::from_command_line(int argc, char const * const * argv)
{
vector<string> arguments;
for (int i = 1; i < argc; ++i)
arguments.push_back(argv[i]);
from_command_line(arguments, true);
}
static concrete_option const &
getopt(map<string, concrete_option> const & by_name, string const & name)
{
map<string, concrete_option>::const_iterator i = by_name.find(name);
if (i != by_name.end())
return i->second;
else
throw unknown_option(name);
}
static map<string, concrete_option>
get_by_name(std::set<concrete_option> const & options)
{
map<string, concrete_option> by_name;
for (std::set<concrete_option>::const_iterator i = options.begin();
i != options.end(); ++i)
{
if (!i->longname.empty())
by_name.insert(make_pair(i->longname, *i));
if (!i->shortname.empty())
by_name.insert(make_pair(i->shortname, *i));
}
return by_name;
}
void concrete_option_set::from_command_line(std::vector<std::string> & args,
bool allow_xargs)
{
map<string, concrete_option> by_name = get_by_name(options);
bool seen_dashdash = false;
for (unsigned int i = 0; i < args.size(); ++i)
{
concrete_option o;
string name, arg;
bool separate_arg(false);
if (idx(args,i) == "--" || seen_dashdash)
{
if (!seen_dashdash)
{
seen_dashdash = true;
allow_xargs = false;
continue;
}
name = "--";
o = getopt(by_name, name);
arg = idx(args,i);
}
else if (idx(args,i).substr(0,2) == "--")
{
string::size_type equals = idx(args,i).find('=');
if (equals == string::npos)
name = idx(args,i).substr(2);
else
name = idx(args,i).substr(2, equals-2);
o = getopt(by_name, name);
if (!o.has_arg && equals != string::npos)
throw extra_arg(name);
if (o.has_arg)
{
if (equals == string::npos)
{
separate_arg = true;
if (i+1 == args.size())
throw missing_arg(name);
arg = idx(args,i+1);
}
else
arg = idx(args,i).substr(equals+1);
}
}
else if (idx(args,i).substr(0,1) == "-")
{
name = idx(args,i).substr(1,1);
o = getopt(by_name, name);
if (!o.has_arg && idx(args,i).size() != 2)
throw extra_arg(name);
if (o.has_arg)
{
if (idx(args,i).size() == 2)
{
separate_arg = true;
if (i+1 == args.size())
throw missing_arg(name);
arg = idx(args,i+1);
}
else
arg = idx(args,i).substr(2);
}
}
else
{
name = "--";
o = getopt(by_name, name);
arg = idx(args,i);
}
if (allow_xargs && (name == "xargs" || name == "@"))
{
// expand the --xargs in place
data dat;
read_data_for_command_line(arg, dat);
vector<string> fargs;
tokenize_for_command_line(dat(), fargs);
args.erase(args.begin() + i);
if (separate_arg)
args.erase(args.begin() + i);
args.insert(args.begin()+i, fargs.begin(), fargs.end());
--i;
}
else
{
if (separate_arg)
++i;
try
{
if (o.setter)
o.setter(arg);
}
catch (boost::bad_lexical_cast)
{
throw bad_arg(o.longname, arg);
}
catch (bad_arg_internal & e)
{
if (e.reason == "")
throw bad_arg(o.longname, arg);
else
throw bad_arg(o.longname, arg, e.reason);
}
}
}
}
void concrete_option_set::from_key_value_pairs(vector<pair<string, string> > const & keyvals)
{
map<string, concrete_option> by_name = get_by_name(options);
for (vector<pair<string, string> >::const_iterator i = keyvals.begin();
i != keyvals.end(); ++i)
{
string const & key(i->first);
string const & value(i->second);
concrete_option o = getopt(by_name, key);
try
{
if (o.setter)
o.setter(value);
}
catch (boost::bad_lexical_cast)
{
throw bad_arg(o.longname, value);
}
catch (bad_arg_internal & e)
{
if (e.reason == "")
throw bad_arg(o.longname, value);
else
throw bad_arg(o.longname, value, e.reason);
}
}
}
static vector<string> wordwrap(string str, unsigned int width)
{
vector<string> out;
while (str.size() > width)
{
string::size_type pos = str.find_last_of(" ", width);
if (pos == string::npos)
{ // bah. we have to break a word
out.push_back(str.substr(0, width));
str = str.substr(width);
}
else
{
out.push_back(str.substr(0, pos));
str = str.substr(pos+1);
}
}
out.push_back(str);
return out;
}
// Get the non-description part of the usage string,
// looks like "--long [ -s ] <arg>".
static string usagestr(concrete_option const & opt)
{
string out;
if (opt.longname == "--")
return "";
if (!opt.longname.empty() && !opt.shortname.empty())
out = "--" + opt.longname + " [ -" + opt.shortname + " ]";
else if (!opt.longname.empty())
out = "--" + opt.longname;
else if (!opt.shortname.empty())
out = "-" + opt.shortname;
else
return "";
if (opt.has_arg)
return out + " <arg>";
else
return out;
}
std::string concrete_option_set::get_usage_str() const
{
unsigned int namelen = 0; // the longest option name string
for (std::set<concrete_option>::const_iterator i = options.begin();
i != options.end(); ++i)
{
string names = usagestr(*i);
if (names.size() > namelen)
namelen = names.size();
}
// " --long [ -s ] <arg> description goes here"
// ^ ^^ ^^ ^^ ^
// | | \ namelen / | | \ descwidth /| <- edge of screen
// ^^^^ ^^^^
// pre_indent space
string result;
int pre_indent = 2; // empty space on the left
int space = 2; // space after the longest option, before the description
int termwidth = guess_terminal_width();
int descindent = pre_indent + namelen + space;
int descwidth = termwidth - descindent;
for (std::set<concrete_option>::const_iterator i = options.begin();
i != options.end(); ++i)
{
string names = usagestr(*i);
if (names.empty())
continue;
vector<string> desclines = wordwrap(i->description, descwidth);
result += string(pre_indent, ' ')
+ names + string(namelen - names.size(), ' ')
+ string(space, ' ');
vector<string>::const_iterator line = desclines.begin();
if (line != desclines.end())
{
result += *line + "\n";
++line;
}
else // no description
result += "\n";
for (; line != desclines.end(); ++line)
result += string(descindent, ' ') + *line + "\n";
}
return result;
}
} // namespace option
#ifdef BUILD_UNIT_TESTS
#include "unit_tests.hh"
UNIT_TEST(option, concrete_options)
{
bool b = false;
string s;
int i = -1;
vector<string> v;
option::concrete_option_set os;
os("--", "", option::setter(v), option::resetter(v))
("bool,b", "", option::setter(b), option::resetter(b, false))
("s", "", option::setter(s))
("int", "", option::setter(i));
{
char const * cmdline[] = {"progname", "pos", "-s", "str ing", "--int", "10",
"--int", "45", "--", "--bad", "foo", "-b"};
os.from_command_line(12, cmdline);
}
BOOST_CHECK(!b);
BOOST_CHECK(i == 45);
BOOST_CHECK(s == "str ing");
BOOST_CHECK(v.size() == 4);// pos --bad foo -b
os.reset();
BOOST_CHECK(v.empty());
{
vector<string> cmdline;
cmdline.push_back("--bool");
cmdline.push_back("-s");
cmdline.push_back("-s");
cmdline.push_back("foo");
os.from_command_line(cmdline);
}
BOOST_CHECK(b);
BOOST_CHECK(s == "-s");
BOOST_CHECK(v.size() == 1);
BOOST_CHECK(v[0] == "foo");
os.reset();
BOOST_CHECK(!b);
{
char const * cmdline[] = {"progname", "--bad_arg", "x"};
BOOST_CHECK_THROW(os.from_command_line(3, cmdline), option::unknown_option);
}
{
char const * cmdline[] = {"progname", "--bool=x"};
BOOST_CHECK_THROW(os.from_command_line(2, cmdline), option::extra_arg);
}
{
char const * cmdline[] = {"progname", "-bx"};
BOOST_CHECK_THROW(os.from_command_line(2, cmdline), option::extra_arg);
}
{
char const * cmdline[] = {"progname", "-s"};
BOOST_CHECK_THROW(os.from_command_line(2, cmdline), option::missing_arg);
}
{
char const * cmdline[] = {"progname", "--int=x"};
BOOST_CHECK_THROW(os.from_command_line(2, cmdline), option::bad_arg);
}
}
#endif // BUILD_UNIT_TESTS
// Local Variables:
// mode: C++
// fill-column: 76
// c-file-style: "gnu"
// indent-tabs-mode: nil
// End:
// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s:
|