RavEngine
Loading...
Searching...
No Matches
options.h
1//----------------------------------------------------------------------------//
2// //
3// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation //
4// and distributed under the MIT License (MIT). //
5// //
6// Copyright (c) Guillaume Blanc //
7// //
8// Permission is hereby granted, free of charge, to any person obtaining a //
9// copy of this software and associated documentation files (the "Software"), //
10// to deal in the Software without restriction, including without limitation //
11// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
12// and/or sell copies of the Software, and to permit persons to whom the //
13// Software is furnished to do so, subject to the following conditions: //
14// //
15// The above copyright notice and this permission notice shall be included in //
16// all copies or substantial portions of the Software. //
17// //
18// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
19// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
20// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
21// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
22// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
23// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
24// DEALINGS IN THE SOFTWARE. //
25// //
26//----------------------------------------------------------------------------//
27
28#ifndef OZZ_OZZ_OPTIONS_OPTIONS_H_
29#define OZZ_OZZ_OPTIONS_OPTIONS_H_
30
31// Implements a command line option processing utility. It helps with command
32// line parsing by converting arguments to c++ objects of type bool, int, float
33// or const char* c string.
34// Unlike getogt(), program options can be scattered in the source files (a la
35// google-gflags). Options are collected by a parser which then automatically
36// generate the help/usage screen based on registered options.
37//
38// This library is made of two c++ file (.h/.cc) with no other dependency.
39//
40// To set an option from the command line, use the form --option=value for
41// non-boolean options, and --option/--nooption for booleans.
42// For example, "--var=46" will set "var" variable to 46. If "var" type is not
43// compatible with the specified argument (in this case an integer, a float or a
44// string), then the parser displays the help message and requires application
45// to exit.
46//
47// Boolean options can be set using different syntax:
48// - to set a boolean option to true: "--var", "--var=true", "--var=t",
49// "--var=yes", "--var=y", "--var=1".
50// - to set a boolean option to false: "--novar", "--var=false", "--var=f",
51// "--var=no", "--var=n", "--var=0".
52// Consistently using single-form --option/--nooption is recommended though.
53//
54// Specifying an option (in the command line) that has not been registered is
55// an error, it will require the application to exit.
56//
57// As in getopt() and gflags, -- by itself terminates flags processing. So in:
58// "foo -f1=1 -- -f2=2", f1 is considered but -f2 is not.
59//
60// Parsing is invoked through ozz::options::ParseCommandLine function, providing
61// argc and argv arguments of the main function. This function also takes as
62// argument two strings to specify the version and usage message.
63//
64// To declare/register a new option, use OZZ_OPTIONS_DECLARE_* like macros.
65// Supported options types are bool, int, float and string (c string).
66// OZZ_OPTIONS_DECLARE_* macros arguments allow to give the option a:
67// - name, used in the code to read option value.
68// - description, used by the help screen.
69// - default value.
70// - required flag, that specifies if the option is optional.
71// So for example, in order to define a boolean "verbose" option, that is false
72// by default and optional (ie: not required):
73// OZZ_OPTIONS_DECLARE_BOOL(verbose, "Display verbose output", false, false);
74// This option can then be referenced from the code using OPTIONS_verbose c++
75// global variable, that implement an automatic cast operator to the option's
76// type (bool in this case).
77//
78// The parser also integrates built-in options:
79// --help displays the help screen, that is automatically generated based on the
80// registered options.
81// --version displays executable's version.
82
83#include "ozz/options/export.h"
84#include "ozz/base/containers/string.h"
85
86namespace ozz {
87namespace options {
88
89// Eumerates options parsing results.
90enum ParseResult {
91 // Command line was parsed successfully.
92 kSuccess,
93 // Command line was parsed successfully, but an argument (like --help) was
94 // specified and requires application to exit.
95 kExitSuccess,
96 // Command line parsing failed because of an invalid option or syntax. See
97 // std::cout output for more details.
98 kExitFailure,
99};
100
101// Parses all registered options using the command line specified with (_argc,
102// _argv) arguments. Options are registered using OZZ_OPTIONS_DECLARE_* macros.
103// Valid command line syntax is explained on top of this options.h file and
104// displayed by the help/usage screen.
105// ParseCommandLine expects that _argc >= 1 and _argv[0] is the executable path.
106// _version and _usage are used to respectively set the executable version and
107// usage string in case that the help/usage screen is displayed (--help).
108// _version and _usage are not copied, ParseCommandLine caller is in charge of
109// maintaining their allocation during application lifetime.
110// See ParseResult for more details about returned values.
111OZZ_OPTIONS_DLL ParseResult ParseCommandLine(int _argc,
112 const char* const* _argv,
113 const char* _version,
114 const char* _usage);
115
116// Get the executable path that was extracted from the last call to
117// ParseCommandLine.
118// If ParseCommandLine has never been called, then ParsedExecutablePath
119// returns a default empty string.
120OZZ_OPTIONS_DLL ozz::string ParsedExecutablePath();
121
122// Get the executable name that was extracted from the last call to
123// ParseCommandLine.
124// If ParseCommandLine has never been called, then ParsedExecutableName
125// returns a default empty string.
126OZZ_OPTIONS_DLL const char* ParsedExecutableName();
127
128// Get the executable usage that was extracted from the last call to
129// ParseCommandLine.
130// If ParseCommandLine has never been called, then ParsedExecutableUsage
131// returns a default empty string.
132OZZ_OPTIONS_DLL const char* ParsedExecutableUsage();
133
134#define OZZ_OPTIONS_DECLARE_BOOL(_name, _help, _default, _required) \
135 OZZ_OPTIONS_DECLARE_VARIABLE(ozz::options::BoolOption, _name, _help, \
136 _default, _required)
137#define OZZ_OPTIONS_DECLARE_BOOL_FN(_name, _help, _default, _required, _fn) \
138 OZZ_OPTIONS_DECLARE_VARIABLE_FN(ozz::options::BoolOption, _name, _help, \
139 _default, _required, _fn)
140
141#define OZZ_OPTIONS_DECLARE_INT(_name, _help, _default, _required) \
142 OZZ_OPTIONS_DECLARE_VARIABLE(ozz::options::IntOption, _name, _help, \
143 _default, _required)
144#define OZZ_OPTIONS_DECLARE_INT_FN(_name, _help, _default, _required, _fn) \
145 OZZ_OPTIONS_DECLARE_VARIABLE_FN(ozz::options::IntOption, _name, _help, \
146 _default, _required, _fn)
147
148#define OZZ_OPTIONS_DECLARE_FLOAT(_name, _help, _default, _required) \
149 OZZ_OPTIONS_DECLARE_VARIABLE(ozz::options::FloatOption, _name, _help, \
150 _default, _required)
151#define OZZ_OPTIONS_DECLARE_FLOAT_FN(_name, _help, _default, _required, _fn) \
152 OZZ_OPTIONS_DECLARE_VARIABLE_FN(ozz::options::FloatOption, _name, _help, \
153 _default, _required, _fn)
154
155#define OZZ_OPTIONS_DECLARE_STRING(_name, _help, _default, _required) \
156 OZZ_OPTIONS_DECLARE_VARIABLE(ozz::options::StringOption, _name, _help, \
157 _default, _required)
158#define OZZ_OPTIONS_DECLARE_STRING_FN(_name, _help, _default, _required, _fn) \
159 OZZ_OPTIONS_DECLARE_VARIABLE_FN(ozz::options::StringOption, _name, _help, \
160 _default, _required, _fn)
161
162#define OZZ_OPTIONS_DECLARE_VARIABLE(_type, _name, _help, _default, _required) \
163 /* Instantiates a registrer for an option of type _type with name _name */ \
164 static ozz::options::internal::Registrer<_type> OPTIONS_##_name( \
165 #_name, _help, _default, _required);
166#define OZZ_OPTIONS_DECLARE_VARIABLE_FN(_type, _name, _help, _default, \
167 _required, _fn) \
168 /* Instantiates a registrer for an option of type _type with name _name */ \
169 static ozz::options::internal::Registrer<_type> OPTIONS_##_name( \
170 #_name, _help, _default, _required, _fn);
171
172// Defines option interface.
173class OZZ_OPTIONS_DLL Option {
174 public:
175 // Returns option's name.
176 const char* name() const { return name_; }
177
178 // Returns help string.
179 const char* help() const { return help_; }
180
181 // A required option is satisfied if it was successfully parsed from the
182 // command line. Non required option are always satisfied.
183 bool statisfied() const { return parsed_ || !required_; }
184
185 // Returns true if the option is required.
186 bool required() const { return required_; }
187
188 // Calls validation function if one is set.
189 // Returns true if no function is set, or the function returns true.
190 bool Validate(int _argc);
191
192 // Parse the command line and set the option's value.
193 // Returns true if argument parsing succeeds, false if argument doesn't match
194 // or was already parsed (in case of an argument specified more than once).
195 bool Parse(const char* _argv);
196
197 // Restores default value.
198 void RestoreDefault();
199
200 // Outputs default value as a string.
201 virtual ozz::string FormatDefault() const = 0;
202
203 // Outputs type of value as a c string.
204 virtual const char* FormatType() const = 0;
205
206 // Implements the sorting operator.
207 bool operator<(const Option& _option) const { return name_ < _option.name_; }
208
209 protected:
210 // Declares validation function prototype.
211 // _option is the option to validate.
212 // _argc the number of argument processed.
213 // *_exit can be set to true to require application to exit. This flag is
214 // relevant only if the function does not return false. Application will
215 // exit anyway if false is returned.
216 typedef bool (*ValidateFn)(const Option& _option, int _argc);
217
218 // Construct an option.
219 // _name and _help are set to an empty c string if nullptr.
220 Option(const char* _name, const char* _help, bool _required,
221 ValidateFn _validate = nullptr);
222
223 // Destructor.
224 virtual ~Option();
225
226 // Parse the command line and set the option value.
227 virtual bool ParseImpl(const char* _argv) = 0;
228
229 // Restores default value typed implementation.
230 virtual void RestoreDefaultImpl() = 0;
231
232 private:
233 // Option's name.
234 const char* name_;
235
236 // Option's help message.
237 const char* help_;
238
239 // Is this option required?
240 bool required_;
241
242 // Was this option successfully parsed from the command line.
243 bool parsed_;
244
245 // Validate function. nullptr if no function is set.
246 ValidateFn validate_;
247};
248
249// Defines a strongly typed option class
250template <typename _Type>
251class OZZ_OPTIONS_DLL TypedOption : public Option {
252 public:
253 // Lets the type be known.
254 typedef _Type Type;
255
256 // Defines an option.
257 TypedOption(const char* _name, const char* _help, _Type _default,
258 bool _required, Option::ValidateFn _validate = nullptr)
259 : Option(_name, _help, _required, _validate),
260 default_(_default),
261 value_(_default) {}
262
263 virtual ~TypedOption() {}
264
265 // Implicit conversion to the option type.
266 operator _Type() const { return value_; }
267
268 // Explicit getter.
269 const _Type& value() const { return value_; }
270
271 // Get the default value.
272 const _Type& default_value() const { return default_; }
273
274 private:
275 // Parse the command line and set the option value.
276 virtual bool ParseImpl(const char* _argv);
277
278 // Restores default value implementation.
279 virtual void RestoreDefaultImpl() { value_ = default_; }
280
281 // Outputs default value as a string.
282 virtual ozz::string FormatDefault() const;
283
284 // Outputs type of value as a string.
285 virtual const char* FormatType() const;
286
287 // Default option's value.
288 _Type default_;
289
290 // Current option's value.
291 _Type value_;
292};
293
294// Declares all available option types.
299
300// Declares the option parser class.
301// Option are registered by the parser and updated when command line arguments
302// are parsed.
303class OZZ_OPTIONS_DLL Parser {
304 public:
305 // Construct a parser with only built-in options.
306 Parser();
307
308 // Destroys the parser. Options does not need to be unregistered.
309 ~Parser();
310
311 // Parses the command line against all registered options.
312 // _argv arguments are parser until the end to the first "--" argument found.
313 // Note that _argv arguments memory allocations must remains valid for the
314 // life of parser, as some arguments like string options or executable path
315 // and name will be pointed by the parser (ie: not copied).
316 // See ParseResult for more details about returned values.
317 ParseResult Parse(int _argc, const char* const* _argv);
318
319 // Displays the help screen that is automatically built from all registered
320 // options. Executable name is only available if ::Parse() was called with a
321 // valid argv[0].
322 void Help();
323
324 // Registers a new option in this parser.
325 // Registered options are updated when Parse() is called.
326 // Returns true on success or false if:
327 // - _option is not a valid option (ex: bad name...), or if an
328 // option with the same name already exists.
329 // - _option si nullptr.
330 // - more than kMaxOptions were registered.
331 bool RegisterOption(Option* _option);
332
333 // Unregisters an option that was successfully registered using
334 // ::RegisterOption().
335 // Returns true if no more option is registered.
336 bool UnregisterOption(Option* _option);
337
338 // Get the maximum number of options that can be registered.
339 // This excludes built-in options.
340 int max_options() const;
341
342 // Set executable usage string.
343 // Note that _usage string will not be copied but rather pointed. This means
344 // that _usage allocation must remain valid for all the parser's life.
345 void set_usage(const char* _usage);
346
347 // Get executable usage string.
348 const char* usage() const;
349
350 // Set executable version string.
351 // Note that _usage string will not be copied but rather pointed. This means
352 // that _usage allocation must remain valid for all the parser's life.
353 void set_version(const char* _version);
354
355 // Get executable version string.
356 const char* version() const;
357
358 // Returns the path of the executable that was extracted from argument 0.
359 ozz::string executable_path() const;
360
361 // Returns the name of the executable that was extracted from argument 0.
362 const char* executable_name() const;
363
364 private:
365 // Get end of registered options array.
366 Option** options_end() { return options_ + options_count_; }
367
368 // Collection of registered options.
369 Option* options_[32];
370
371 // Number of registered options, including built-in options.
372 int options_count_;
373
374 // Number of built-in options.
375 int builtin_options_count_;
376
377 // The path of the executable, extracted from the first argument.
378 const char* executable_path_begin_;
379 const char* executable_path_end_;
380
381 // The name of the executable, extracted from the first argument.
382 const char* executable_name_;
383
384 // Executable version set with ::set_version().
385 const char* version_;
386
387 // Executable usage set with ::set_usage().
388 const char* usage_;
389
390 // Built-in version option.
391 BoolOption builtin_version_;
392
393 // Built-in help option.
394 BoolOption builtin_help_;
395};
396
397namespace internal {
398// Automatically registers itself to the global parser.
399template <typename _Option>
400class Registrer : public _Option {
401 public:
402 Registrer(const char* _name, const char* _help,
403 typename _Option::Type _default, bool _required,
404 typename _Option::ValidateFn _fn = nullptr);
405 virtual ~Registrer();
406};
407} // namespace internal
408} // namespace options
409} // namespace ozz
410#endif // OZZ_OZZ_OPTIONS_OPTIONS_H_
Definition options.h:173
Definition options.h:303
Definition options.h:251