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
|
#ifndef ZYPP_TOOLS_ARGPARSE_H
#define ZYPP_TOOLS_ARGPARSE_H
#include <iosfwd>
#include <string>
#include <exception>
#include <unordered_map>
#include <unordered_set>
#include <vector>
//#include <regex> seems to be bad with gcc < 4.9
#include <zypp-core/base/Regex.h>
///////////////////////////////////////////////////////////////////
/// Simple arg parser for tools
/// \code
/// argparse::Options options;
/// options.add()
/// ( "help,h", "Print help and exit." )
/// ( "root", "Use the system located below ROOTDIR.", argparse::Option::Arg::required )
/// ;
/// auto result = options.parse( argc, argv );
///
/// if ( result.count( "root" ) )
/// sysRoot = result["root"].arg();
/// \endcode
namespace argparse
{
using zypp::str::regex;
using zypp::str::smatch;
using zypp::str::regex_match;
///////////////////////////////////////////////////////////////////
/// Exception thrown when defining Options or parsing.
class OptionException : public std::exception
{
public:
OptionException( std::string msg_r )
: _msg { std::move(msg_r) }
{}
OptionException( std::string msg_r, const std::string & msg2_r )
: _msg { std::move(msg_r) }
{ if ( ! msg2_r.empty() ) _msg += msg2_r; }
const char* what() const noexcept override
{ return _msg.c_str(); }
private:
std::string _msg;
};
///////////////////////////////////////////////////////////////////
/// Option description (TBD define arg consumer)
class Option
{
public:
enum class Arg { none, required, optional };
public:
Option( std::string descr_r, Arg hasarg_r )
: _descr { std::move(descr_r) }
, _hasarg { hasarg_r }
{
if ( hasarg_r == Arg::optional )
throw OptionException( "Not yet implemented: Option::Arg::optional" );
}
const std::string & descr() const
{ return _descr; }
Arg hasarg() const
{ return _hasarg; }
private:
std::string _descr;
Arg _hasarg;
};
class ParsedOptions;
///////////////////////////////////////////////////////////////////
/// Map of option names -> option descriptions.
class Options
{
typedef std::unordered_map<std::string, std::shared_ptr<const Option>> OptionMap;
public:
Options()
{}
public:
class Injector
{
public:
Injector( OptionMap & optmap_r )
: _optmap { optmap_r }
{}
Injector & operator()( const std::string & names_r, std::string descr_r, Option::Arg hasarg_r = Option::Arg::none )
{
smatch result;
if ( regex_match( names_r, result, regex("([[:alnum:]][-_[:alnum:]]+)(,([[:alnum:]]))?") ) )
{
auto opt = std::make_shared<const Option>( std::move(descr_r), hasarg_r );
add( result[1], opt );
if ( ! result[3].empty() )
add( result[3], opt );
}
else
throw OptionException( "Illegal option names: ", names_r );
return *this;
}
private:
void add( std::string name_r, std::shared_ptr<const Option> opt_r )
{
if ( _optmap.count( name_r ) )
throw OptionException( "Duplicate option name: ", name_r );
_optmap[name_r] = opt_r;
}
private:
OptionMap & _optmap;
};
Injector add()
{ return Injector( _optmap ); }
public:
ParsedOptions parse( int argc, char * argv[] ) const;
public:
std::ostream & dumpOn( std::ostream & str_r ) const
{
str_r << "OPTIONS:";
if ( ! _optmap.empty() )
{
std::unordered_map<std::shared_ptr<const Option>, std::string> unify;
for ( const auto & p : _optmap )
{
std::string & t { unify[p.second] };
if ( t.empty() )
t = (p.first.length()>1?"--":"-")+p.first;
else if ( p.first.length() > 1 )
t = "--"+p.first+", "+t;
else
t = t+", -"+p.first;
}
boost::format fmt( "\n %1% %|30t|%2%" );
for ( const auto & p : unify )
{
fmt % p.second % p.first->descr();
str_r << fmt.str();
}
}
else
{
str_r << " This command accepts no options.";
}
return str_r;
}
private:
OptionMap _optmap;
};
inline std::ostream & operator<<( std::ostream & str_r, const Options & obj_r )
{ return obj_r.dumpOn( str_r ); }
///////////////////////////////////////////////////////////////////
/// Parsed option incl. option args value (by now just stores the string)
class OptionValue
{
public:
OptionValue( std::shared_ptr<const Option> opt_r )
: _opt { opt_r }
{}
OptionValue( std::shared_ptr<const Option> opt_r, std::string arg_r )
: _opt { opt_r }
, _arg { std::make_shared<std::string>( std::move(arg_r) ) }
{}
const std::string & arg() const
{
if ( ! _arg )
throw std::domain_error( "No arg value" );
return *_arg;
}
private:
std::shared_ptr<const Option> _opt;
std::shared_ptr<std::string> _arg;
};
///////////////////////////////////////////////////////////////////
/// Parsed options and positional args
class ParsedOptions
{
typedef std::unordered_map<std::string, std::shared_ptr<const Option>> OptionMap;
typedef std::unordered_map<std::shared_ptr<const Option>, OptionValue> ResultMap;
public:
ParsedOptions( const OptionMap & optmap_r, int argc, char * argv[] )
: _optmap { optmap_r }
{ parse( argc, argv ); }
public:
size_t count( const std::string & optname_r ) const
{
auto iter = _optmap.find( optname_r );
if ( iter == _optmap.end() )
return 0;
auto resiter = _options.find( iter->second );
return( resiter == _options.end() ? 0 : 1 );
}
const OptionValue & operator[]( const std::string & optname_r ) const
{
return requireOptValByName( optname_r );
}
const std::vector<std::string> & positionals() const
{ return _positionals; }
private:
void parse( int argc, char * argv[] )
{
bool collectpositional = false;
for ( --argc,++argv; argc; --argc,++argv )
{
if ( (*argv)[0] == '-' && !collectpositional )
{
if ( (*argv)[1] == '-' )
{
if ( (*argv)[2] == '\0' )
{
// -- rest are positional...
collectpositional = true;
}
else
{
// --longopt
parseoptl( (*argv)+2, argc, argv );
}
}
else
{
// -s(hortopt)
parseopts( (*argv)+1, argc, argv );
}
}
else
{
// positional
_positionals.push_back( *argv );
}
}
}
private:
std::string dashed( std::string name_r ) const
{ return name_r.insert( 0, name_r.size()>1?"--":"-" ); }
void parseoptl( const std::string & name_r, int & argc, char **& argv )
{
if ( name_r.length() < 2 )
throw OptionException( "Illegal long opt: --", name_r );
parseopt( name_r, argc, argv );
}
void parseopts( const std::string & name_r, int & argc, char **& argv )
{
if ( name_r.length() != 1 )
throw OptionException( "Illegal short opt: -", name_r );
parseopt( name_r, argc, argv );
}
void parseopt( const std::string & name_r, int & argc, char **& argv )
{
auto opt = requireOptByName( name_r );
auto iter = _options.find( opt );
if ( iter != _options.end() )
throw OptionException( "Multiple occurrences of option: ", dashed( name_r ) );
if ( opt->hasarg() != Option::Arg::none )
{
if ( opt->hasarg() == Option::Arg::optional )
throw OptionException( "Not yet implemented: Option::Arg::optional" ); // i.e. '--opt=arg'
if ( argc < 2 )
throw OptionException( "Missing argument for option: ", dashed( name_r ) );
--argc,++argv;
moveToResult( opt, OptionValue( opt, *argv ) );
}
else
moveToResult( opt, OptionValue( opt ) );
}
void moveToResult( std::shared_ptr<const Option> opt_r, OptionValue && value_r )
{ _options.insert( std::make_pair( opt_r, std::move(value_r) ) ); }
std::shared_ptr<const Option> requireOptByName( const std::string & name_r ) const
{
auto iter = _optmap.find( name_r );
if ( iter == _optmap.end() )
throw OptionException( "Unknown option: ", dashed( name_r ) );
return iter->second;
}
const OptionValue & requireOptValByName( const std::string & name_r ) const
{
auto iter = _options.find( requireOptByName( name_r ) );
if ( iter == _options.end() )
throw OptionException( "Option not present: ", dashed( name_r ) );
return iter->second;
}
private:
const OptionMap & _optmap;
ResultMap _options;
std::vector<std::string> _positionals;
};
inline ParsedOptions Options::parse( int argc, char * argv[] ) const
{ return ParsedOptions( _optmap, argc, argv ); }
} // namespace argparse
///////////////////////////////////////////////////////////////////
#endif // ZYPP_TOOLS_ARGPARSE_H
|