Compare commits
10 Commits
6569bbb5bb
...
e8d0687f44
Author | SHA1 | Date | |
---|---|---|---|
![]() |
e8d0687f44 | ||
![]() |
cbd549f737 | ||
![]() |
d0ea138f8b | ||
![]() |
d437ff26c0 | ||
![]() |
73e1d1a71a | ||
![]() |
661d569657 | ||
![]() |
193219ac50 | ||
![]() |
a132c7d925 | ||
![]() |
837761df94 | ||
![]() |
a10a98bc25 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,2 +1 @@
|
||||
build
|
||||
.vscode
|
||||
build
|
4
.vscode/settings.json
vendored
Normal file
4
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"C_Cpp.clang_format_fallbackStyle": "Google",
|
||||
"C_Cpp.clang_format_style": "{ColumnLimit: 100}"
|
||||
}
|
@@ -1,3 +1,5 @@
|
||||
# copyright Carl Pearson, 2022
|
||||
|
||||
# 3.0: version
|
||||
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
|
||||
|
||||
|
202
LICENSE
Normal file
202
LICENSE
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
103
README.md
103
README.md
@@ -6,7 +6,7 @@ Simple single-file header-only CLI option parsing for C++ that does not require
|
||||
|
||||
## Getting Started
|
||||
|
||||
Download the latest [`argparse.hpp`](https://raw.githubusercontent.com/cwpearson/argparse/latest/include/argparse/argparse.hpp) and include it in your project.
|
||||
Download the latest [`argparse.hpp`](https://raw.githubusercontent.com/cwpearson/argparse/master/include/argparse/argparse.hpp) and include it in your project.
|
||||
|
||||
## Example
|
||||
|
||||
@@ -16,19 +16,18 @@ Download the latest [`argparse.hpp`](https://raw.githubusercontent.com/cwpearson
|
||||
int main(int argc, char **argv) {
|
||||
|
||||
// A parser object
|
||||
Parser p;
|
||||
argparse::Parser p;
|
||||
|
||||
// Program data corresponding to flags, options, and positional arguments
|
||||
bool verbose = false;
|
||||
std::string toPrint;
|
||||
std::string maybePrint;
|
||||
int repeats = 1;
|
||||
int repeats = 2;
|
||||
|
||||
// Inform the parser of the program data. It will do type-specific conversion
|
||||
// from string.
|
||||
// Inform the parser of the program data. It will do type-specific conversionfrom string.
|
||||
|
||||
// An option invoked with `--repeat N`
|
||||
p.add_option(repeats, "--repeat");
|
||||
p.add_option(repeats, "--repeat")->help("how many times to repeat first argument");
|
||||
// A flag invoked with `--verbose` or `-v`
|
||||
p.add_flag(verbose, "--verbose", "-v");
|
||||
// a required positional argument (position 1)
|
||||
@@ -42,6 +41,12 @@ int main(int argc, char **argv) {
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// If help was requested, print it
|
||||
if (p.need_help()) {
|
||||
std::cerr << p.help();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Execute the program logic
|
||||
if (verbose) {
|
||||
std::cerr << "about to print '" << toPrint << "' " << repeats << " times";
|
||||
@@ -65,24 +70,29 @@ int main(int argc, char **argv) {
|
||||
|
||||
## Adding Options
|
||||
|
||||
Options may be `int`, `size_t`, `float`, `double`, or `std::string` and currently support long strings.
|
||||
They are invoked like `--long-opt value` (not `--long-opt=value`).
|
||||
Options may be `int32_t`, `int64_t`, `size_t`, `float`, `double`, or `std::string`.
|
||||
They are invoked like `--long-opt value` (not `--long-opt=value`) or `-s value`, if provided.
|
||||
If they are not present, the value is not modified.
|
||||
|
||||
```c++
|
||||
Parser p;
|
||||
p.add_option(var1, "--long-opt")
|
||||
int var1 = 3; // a default value for var1
|
||||
argparse::Parser p;
|
||||
p.add_option(var1, "--long-opt");
|
||||
p.add_option(var2, "--long-opt, -s");
|
||||
p.add_option(var3, "--long-opt, -s")->help("a demo option");
|
||||
```
|
||||
|
||||
## Adding Flags
|
||||
|
||||
Flags are always `bool`s, and currently support long or short strings.
|
||||
The boolean variable is ALWAYS set to `true` if the flag is found.
|
||||
They are invoked like `--long-flag` (not `--long-flag=true` or `--long-flag true`).
|
||||
They are invoked like `--long-flag` (not `--long-flag=true` or `--long-flag true`) or `-s`, if provided.
|
||||
|
||||
```c++
|
||||
Parser p;
|
||||
argparse::Parser p;
|
||||
p.add_option(flag1, "--long-flag")
|
||||
p.add_option(flag2, "--antother-flag", "-s");
|
||||
p.add_option(flag2, "--another-flag", "-s");
|
||||
p.add_option(flag3, "--another-flag", "-s")->help("a demo flag");
|
||||
```
|
||||
|
||||
## Positional Arguments
|
||||
@@ -93,7 +103,7 @@ Use `required()` to require them.
|
||||
`add_positional()` returns a `PosnlBase *` that may be queried with `found()` to see if an optional positional argument was found.
|
||||
|
||||
```c++
|
||||
Parser p;
|
||||
argparse::Parser p;
|
||||
p.add_positional(var1)->required();
|
||||
auto something = p.add_positional(var2);
|
||||
if (something->found()) {
|
||||
@@ -101,26 +111,61 @@ if (something->found()) {
|
||||
}
|
||||
```
|
||||
|
||||
## Parsing
|
||||
Anything after `--` is considered a positional argument, unless `--` follows an option.
|
||||
Here, the first `--` is the value for `--option` and will be in `s1`.
|
||||
The second `--` marks the beginning of positional arguments. and the string `aa` will be in `s2`.
|
||||
|
||||
```c++
|
||||
Parser p;
|
||||
argparse::Parser p;
|
||||
std::string s1, s2;
|
||||
p.add_option(s1, "--option");
|
||||
p.add_positional(s2);
|
||||
std::cerr << s1;
|
||||
std::cerr << s2;
|
||||
```
|
||||
|
||||
```bash
|
||||
$ ./myexe --option -- -- aa
|
||||
--aa
|
||||
```
|
||||
|
||||
## Parsing
|
||||
```c++
|
||||
argparse::Parser p;
|
||||
// set up flags, arguments, and options
|
||||
p.parse(argc, argv);
|
||||
```
|
||||
|
||||
`parse()` returns something falsy if there is an error.
|
||||
|
||||
Parsing modifies `argc` and `argv` to remove consumed options by default.
|
||||
To disable, call `p->no_consume()`.
|
||||
|
||||
Parsing will silently skip unrecognized arguments.
|
||||
To error instead, call `p->no_unrecognized()`.
|
||||
|
||||
`Parser` provides a constructor that takes a string description.
|
||||
This description will be added to the usage string.
|
||||
```c++
|
||||
argparse::Parser p("a demo argparse CLI app");
|
||||
// set up flags, arguments, and options
|
||||
p.parse(argc, argv);
|
||||
```
|
||||
|
||||
## Useage Strings
|
||||
A `--help` and `-h` flag are automatically added.
|
||||
`parser::need_help()` returns true if either of those flags are provided.
|
||||
`parser::help()` returns a string that contains the help output.
|
||||
|
||||
```c++
|
||||
argparse::Parser p;
|
||||
if (p.need_help()) {
|
||||
std::cout << p.help();
|
||||
}
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- [x] Does not require `std::regex`
|
||||
- [x] allow (default) / disallow (`Parser::no_unrecognize()`) unrecognized options and flags
|
||||
- [x] allow (default) / disallow (`Parser::no_unrecognized()`) unrecognized options and flags
|
||||
- [x] optional/required (`PosnlBase::required()`) positional arguments
|
||||
- [x] flags with `-s`, `--long-flag` formats
|
||||
- [x] options with `--long-opt val` format
|
||||
@@ -128,16 +173,24 @@ To error instead, call `p->no_unrecognized()`.
|
||||
- [x] `--` to stop parsing options and flags
|
||||
- [x] modify `argc`/`argv` (disable with `Parser::no_consume()`)
|
||||
- Option/Positional Argument Types
|
||||
- [x] `int`
|
||||
- [x] `int32_t`
|
||||
- [x] `int64_t`
|
||||
- [x] `size_t`
|
||||
- [x] `float`
|
||||
- [x] `double`
|
||||
- [x] `std::string`
|
||||
- [x] Support short option strings
|
||||
- [x] Help string output
|
||||
|
||||
## Roadmap
|
||||
|
||||
- [ ] Reject duplicate flags / options at run time
|
||||
- [ ] Support short option strings
|
||||
- [ ] Help string output
|
||||
- [ ] support --long-option=value
|
||||
- [ ] have the last positional argument fill a vector with remaining
|
||||
- [ ] Runtime error if duplicate flags or options are defined
|
||||
- [ ] support `--long-option=value`
|
||||
- [ ] allow the last positional argument to fill an `std::vector`
|
||||
- [ ] improve help formatting
|
||||
|
||||
## License and Copyright
|
||||
|
||||
Copyright Carl Pearson 2022
|
||||
|
||||
Licensed under Apache 2.0 (see LICENSE for details).
|
@@ -1,3 +1,5 @@
|
||||
# copyright Carl Pearson, 2022
|
||||
|
||||
macro(add_args tgt)
|
||||
target_compile_options(
|
||||
${tgt}
|
||||
|
@@ -1,21 +1,22 @@
|
||||
// copyright Carl Pearson, 2022
|
||||
|
||||
#include "argparse/argparse.hpp"
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
|
||||
// A parser object
|
||||
Parser p;
|
||||
argparse::Parser p;
|
||||
|
||||
// Program data corresponding to flags, options, and positional arguments
|
||||
bool verbose = false;
|
||||
std::string toPrint;
|
||||
std::string maybePrint;
|
||||
int repeats = 1;
|
||||
int repeats = 2;
|
||||
|
||||
// Inform the parser of the program data. It will do type-specific conversion
|
||||
// from string.
|
||||
// Inform the parser of the program data. It will do type-specific conversionfrom string.
|
||||
|
||||
// An option invoked with `--repeat N`
|
||||
p.add_option(repeats, "--repeat");
|
||||
p.add_option(repeats, "--repeat")->help("how many times to repeat first argument");
|
||||
// A flag invoked with `--verbose` or `-v`
|
||||
p.add_flag(verbose, "--verbose", "-v");
|
||||
// a required positional argument (position 1)
|
||||
@@ -29,6 +30,12 @@ int main(int argc, char **argv) {
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// If help was requested, print it
|
||||
if (p.need_help()) {
|
||||
std::cerr << p.help();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Execute the program logic
|
||||
if (verbose) {
|
||||
std::cerr << "about to print '" << toPrint << "' " << repeats << " times";
|
||||
|
@@ -1,31 +1,78 @@
|
||||
// copyright Carl Pearson, 2022
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace argparse {
|
||||
|
||||
namespace detail {
|
||||
template <typename T> const char *type_str();
|
||||
template <> const char *type_str<int32_t>() { return "INT32"; }
|
||||
template <> const char *type_str<int64_t>() { return "INT64"; }
|
||||
template <> const char *type_str<std::string>() { return "STR"; }
|
||||
template <> const char *type_str<float>() { return "F32"; }
|
||||
template <> const char *type_str<double>() { return "F64"; }
|
||||
template <> const char *type_str<size_t>() { return "SIZE_T"; }
|
||||
} // namespace detail
|
||||
|
||||
class Parser;
|
||||
|
||||
/* Interface for an object representing a command-line option
|
||||
*/
|
||||
class OptionBase {
|
||||
friend class Parser;
|
||||
|
||||
public:
|
||||
virtual void set_val(const std::string &valStr) = 0;
|
||||
/* return the short and long options
|
||||
*/
|
||||
virtual const std::string &short_str() = 0;
|
||||
virtual const std::string &long_str() = 0;
|
||||
|
||||
/* return the help string
|
||||
*/
|
||||
virtual const std::string &help_str() = 0;
|
||||
|
||||
/* set help string
|
||||
*/
|
||||
virtual void help(const std::string &s) = 0;
|
||||
|
||||
private:
|
||||
/* a string representing the type of the option (INT, STR, FLOAT)
|
||||
*/
|
||||
virtual const char *type_str() = 0;
|
||||
|
||||
/* set the value provided to this option
|
||||
*/
|
||||
virtual void set_val(const std::string &valStr) = 0;
|
||||
};
|
||||
|
||||
template <typename T> class Option : public OptionBase {
|
||||
std::string short_;
|
||||
std::string long_;
|
||||
std::string help_;
|
||||
T *val_;
|
||||
|
||||
public:
|
||||
Option(T &val, const std::string &l) : long_(l), val_(&val) {}
|
||||
void set_val(const std::string &val) override { set_val((T *)nullptr, val); }
|
||||
const std::string &long_str() override {
|
||||
return long_;
|
||||
}
|
||||
Option(T &val, const std::string &l, const std::string &s = "")
|
||||
: long_(l), short_(s), val_(&val) {}
|
||||
const std::string &long_str() override { return long_; }
|
||||
const std::string &short_str() override { return short_; }
|
||||
const std::string &help_str() override { return help_; }
|
||||
|
||||
void help(const std::string &s) { help_ = s; }
|
||||
|
||||
private:
|
||||
/* uses a T* = nullpointer to disambiguate the call
|
||||
*/
|
||||
const char *type_str() override { return detail::type_str<T>(); }
|
||||
void set_val(const std::string &val) override { set_val((T *)nullptr, val); }
|
||||
|
||||
/* how to parse supported types
|
||||
*/
|
||||
void set_val(size_t *, const std::string &val) { // convert to size_t
|
||||
*val_ = std::stoull(val);
|
||||
}
|
||||
@@ -35,7 +82,10 @@ private:
|
||||
void set_val(float *, const std::string &val) { // convert to float
|
||||
*val_ = std::stof(val);
|
||||
}
|
||||
void set_val(int *, const std::string &val) { // convert to int
|
||||
void set_val(int32_t *, const std::string &val) { // convert to int32_t
|
||||
*val_ = std::stoi(val);
|
||||
}
|
||||
void set_val(int64_t *, const std::string &val) { // convert to int64_t
|
||||
*val_ = std::stoi(val);
|
||||
}
|
||||
void set_val(std::string *, const std::string &val) { // convert to string
|
||||
@@ -43,6 +93,8 @@ private:
|
||||
}
|
||||
};
|
||||
|
||||
/* Represents a command-line flag
|
||||
*/
|
||||
class Flag {
|
||||
std::string long_;
|
||||
std::string short_;
|
||||
@@ -57,21 +109,22 @@ public:
|
||||
|
||||
void set() const noexcept { *val_ = true; }
|
||||
|
||||
void help(const std::string &s) {
|
||||
help_ = s;
|
||||
}
|
||||
void help(const std::string &s) { help_ = s; }
|
||||
|
||||
const std::string &help_str() const noexcept {
|
||||
return help_;
|
||||
}
|
||||
const std::string &help_str() const noexcept { return help_; }
|
||||
};
|
||||
|
||||
class PosnlBase {
|
||||
friend class Parser;
|
||||
|
||||
public:
|
||||
virtual bool is_required() = 0;
|
||||
virtual PosnlBase *required() = 0;
|
||||
virtual void set_val(const std::string &val) = 0;
|
||||
virtual bool found() = 0;
|
||||
|
||||
private:
|
||||
virtual const char *type_str() = 0;
|
||||
};
|
||||
|
||||
template <typename T> class Positional : public PosnlBase {
|
||||
@@ -91,17 +144,17 @@ public:
|
||||
|
||||
// use nullpointer type to disambiguate call
|
||||
// https://stackoverflow.com/questions/5512910/explicit-specialization-of-template-class-member-function
|
||||
void set_val(const std::string &val) {
|
||||
void set_val(const std::string &val) {
|
||||
found_ = true;
|
||||
set_val((T *)nullptr, val);
|
||||
set_val((T *)nullptr, val);
|
||||
}
|
||||
|
||||
bool found() override {return found_; }
|
||||
bool found() override { return found_; }
|
||||
|
||||
private:
|
||||
// https://stackoverflow.com/questions/5512910/explicit-specialization-of-template-class-member-function
|
||||
template <typename C>
|
||||
void get_as(C *, const std::string &val) { // to be overridden
|
||||
const char *type_str() override { return detail::type_str<T>(); }
|
||||
|
||||
template <typename C> void get_as(C *, const std::string &val) { // to be overridden
|
||||
}
|
||||
void set_val(size_t *, const std::string &val) { // convert to size_t
|
||||
*val_ = std::stoull(val);
|
||||
@@ -112,7 +165,10 @@ private:
|
||||
void set_val(float *, const std::string &val) { // convert to float
|
||||
*val_ = std::stof(val);
|
||||
}
|
||||
void set_val(int *, const std::string &val) { // convert to int
|
||||
void set_val(int32_t *, const std::string &val) { // convert to int32_t
|
||||
*val_ = std::stoi(val);
|
||||
}
|
||||
void set_val(int64_t *, const std::string &val) { // convert to int64_t
|
||||
*val_ = std::stoi(val);
|
||||
}
|
||||
void set_val(std::string *, const std::string &val) { // convert to string
|
||||
@@ -124,13 +180,15 @@ class Parser {
|
||||
|
||||
std::string description_;
|
||||
bool noUnrecognized_; // error on unrecognized flags / opts
|
||||
bool help_; // help has been requested
|
||||
bool consume_; // remove consumed values from argc, argv
|
||||
bool help_; // help has been requested
|
||||
bool consume_; // remove consumed values from argc, argv
|
||||
|
||||
std::vector<OptionBase *> opts_;
|
||||
std::vector<Flag> flags_;
|
||||
std::vector<PosnlBase *> posnls_;
|
||||
|
||||
std::string argv0_; // will hold the name of the most recent parse(...)
|
||||
|
||||
static bool starts_with(const std::string &s, const std::string &prefix) {
|
||||
if (s.rfind(prefix, 0) == 0) {
|
||||
return true;
|
||||
@@ -140,8 +198,10 @@ class Parser {
|
||||
|
||||
OptionBase *match_opt(const char *arg) const {
|
||||
std::string sarg(arg);
|
||||
|
||||
// match options back-to-front to prefer later duplicates
|
||||
for (int64_t i = int64_t(opts_.size()) - 1; i >= 0; --i) {
|
||||
if (opts_[i]->long_str() == sarg) {
|
||||
if (opts_[i]->long_str() == sarg || opts_[i]->short_str() == sarg) {
|
||||
return opts_[i];
|
||||
}
|
||||
}
|
||||
@@ -150,6 +210,8 @@ class Parser {
|
||||
|
||||
Flag *match_flag(const char *arg) {
|
||||
std::string sarg(arg);
|
||||
|
||||
// match flags back-to-front to prefer later duplicates
|
||||
for (int64_t i = int64_t(flags_.size()) - 1; i >= 0; --i) {
|
||||
if (flags_[i].long_str() == sarg || flags_[i].short_str() == sarg) {
|
||||
return &flags_[i];
|
||||
@@ -159,29 +221,37 @@ class Parser {
|
||||
}
|
||||
|
||||
public:
|
||||
|
||||
Parser() : noUnrecognized_(false), help_(false), consume_(true) {
|
||||
Parser()
|
||||
: description_("an argparse-powered program"), noUnrecognized_(false), help_(false),
|
||||
consume_(true) {
|
||||
add_flag(help_, "--help", "-h")->help("Print help message");
|
||||
}
|
||||
Parser(const std::string &description) : description_(description), noUnrecognized_(false), help_(false), consume_(true) {
|
||||
}
|
||||
Parser(const std::string &description)
|
||||
: description_(description), noUnrecognized_(false), help_(false), consume_(true) {
|
||||
add_flag(help_, "--help", "-h")->help("Print help message");
|
||||
}
|
||||
}
|
||||
|
||||
bool parse(int &argc, char ** argv) {
|
||||
bool parse(int &argc, char **argv) {
|
||||
|
||||
std::vector<char*> newArgv;
|
||||
std::vector<char *> newArgv;
|
||||
if (argc > 0) {
|
||||
newArgv.push_back(argv[0]);
|
||||
|
||||
if (argv[0]) {
|
||||
argv0_ = argv[0];
|
||||
} else {
|
||||
argv0_ = "";
|
||||
}
|
||||
}
|
||||
|
||||
size_t pi = 0; // positional argument position
|
||||
size_t pi = 0; // positional argument position
|
||||
bool optsOkay = true; // okay to interpret as opt/flag
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
|
||||
|
||||
// try interpreting as a flag or option if it looks like one
|
||||
if (optsOkay && starts_with(argv[i], "-")) {
|
||||
// '--' indicates only positional arguments follow
|
||||
// the second '--' should be interpreted as a positional argument
|
||||
if (argv[i] == std::string("--")) {
|
||||
optsOkay = false;
|
||||
continue;
|
||||
@@ -228,12 +298,13 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
template <typename T> void add_option(T &val, const std::string &l) {
|
||||
opts_.push_back(new Option<T>(val, l));
|
||||
template <typename T>
|
||||
OptionBase *add_option(T &val, const std::string &l, const std::string &s = "") {
|
||||
opts_.push_back(new Option<T>(val, l, s));
|
||||
return opts_.back();
|
||||
}
|
||||
|
||||
Flag *add_flag(bool &val, const std::string &l, const std::string &s = "") {
|
||||
@@ -249,10 +320,26 @@ public:
|
||||
std::string help() const {
|
||||
std::stringstream ss;
|
||||
|
||||
ss << "Usage: " << argv0_ << " [OPTION]...";
|
||||
|
||||
for (auto &p : posnls_) {
|
||||
ss << " ";
|
||||
ss << (p->is_required() ? "" : "[");
|
||||
ss << p->type_str();
|
||||
ss << (p->is_required() ? "" : "]");
|
||||
}
|
||||
ss << "\n";
|
||||
|
||||
ss << description_ << "\n";
|
||||
|
||||
for (auto &o : opts_) {
|
||||
ss << o->long_str() << "\n";
|
||||
ss << " ";
|
||||
if (!o->short_str().empty()) {
|
||||
ss << o->short_str() << ", ";
|
||||
}
|
||||
ss << o->long_str() << "\t" << o->type_str();
|
||||
ss << "\t\t" << o->help_str();
|
||||
ss << "\n";
|
||||
}
|
||||
|
||||
for (auto &f : flags_) {
|
||||
@@ -265,18 +352,14 @@ public:
|
||||
}
|
||||
|
||||
/*! \brief error on unrecognized flags and options
|
||||
*/
|
||||
void no_unrecognized() {
|
||||
noUnrecognized_ = true;
|
||||
}
|
||||
*/
|
||||
void no_unrecognized() { noUnrecognized_ = true; }
|
||||
|
||||
/*! \brief don't modify argc/argv
|
||||
*/
|
||||
void no_consume() {
|
||||
consume_ = false;
|
||||
}
|
||||
*/
|
||||
void no_consume() { consume_ = false; }
|
||||
|
||||
bool need_help() const noexcept {
|
||||
return help_;
|
||||
}
|
||||
bool need_help() const noexcept { return help_; }
|
||||
};
|
||||
|
||||
} // namespace argparse
|
@@ -1,3 +1,5 @@
|
||||
# copyright Carl Pearson, 2022
|
||||
|
||||
macro(add_args tgt)
|
||||
target_compile_options(
|
||||
${tgt}
|
||||
|
@@ -1,3 +1,5 @@
|
||||
// copyright Carl Pearson, 2022
|
||||
|
||||
#include "catch2/catch.hpp"
|
||||
|
||||
#include <iostream>
|
||||
@@ -6,22 +8,36 @@
|
||||
|
||||
TEST_CASE("argparse") {
|
||||
|
||||
SECTION("no args") {
|
||||
char **argv = nullptr;
|
||||
int argc = 0;
|
||||
argparse::Parser p;
|
||||
REQUIRE(p.parse(argc, argv));
|
||||
}
|
||||
|
||||
SECTION("null argv[0]") {
|
||||
char *argv[] = {nullptr};
|
||||
int argc = sizeof(argv) / sizeof(argv[0]);
|
||||
argparse::Parser p;
|
||||
REQUIRE(p.parse(argc, argv));
|
||||
}
|
||||
|
||||
SECTION("types") {
|
||||
char *argv[] = {
|
||||
"some-exe", "--campi", "--f", "10", "1.7", "1.8",
|
||||
"some-exe", "--campi", "--f", "10", "1.7", "1.8",
|
||||
"--", // stop looking for options
|
||||
"--a string",
|
||||
"-6",
|
||||
"--a string", "-6",
|
||||
};
|
||||
int argc = sizeof(argv) / sizeof(argv[0]);
|
||||
|
||||
Parser p;
|
||||
argparse::Parser p;
|
||||
|
||||
bool campi = false;
|
||||
size_t x;
|
||||
double d;
|
||||
float f;
|
||||
int i;
|
||||
int64_t i64;
|
||||
std::string s;
|
||||
p.add_flag(campi, "--campi");
|
||||
p.add_positional(x);
|
||||
@@ -29,6 +45,7 @@ TEST_CASE("argparse") {
|
||||
p.add_positional(f);
|
||||
p.add_positional(s);
|
||||
p.add_positional(i);
|
||||
p.add_positional(i64);
|
||||
REQUIRE(p.parse(argc, argv));
|
||||
|
||||
REQUIRE(campi == true);
|
||||
@@ -42,21 +59,13 @@ TEST_CASE("argparse") {
|
||||
REQUIRE(argc == 2); // does not use --f or some-exe
|
||||
}
|
||||
|
||||
SECTION("no args") {
|
||||
char *argv[] = {nullptr};
|
||||
int argc = sizeof(argv) / sizeof(argv[0]);
|
||||
Parser p;
|
||||
REQUIRE(p.parse(argc, argv));
|
||||
}
|
||||
|
||||
|
||||
SECTION("description") {
|
||||
char *argv[] = {
|
||||
"some-exe",
|
||||
};
|
||||
int argc = sizeof(argv) / sizeof(argv[0]);
|
||||
|
||||
Parser p("a test program");
|
||||
argparse::Parser p("a test program");
|
||||
REQUIRE(p.parse(argc, argv));
|
||||
}
|
||||
|
||||
@@ -64,7 +73,7 @@ TEST_CASE("argparse") {
|
||||
char *argv[] = {"some-exe"};
|
||||
int argc = sizeof(argv) / sizeof(argv[0]);
|
||||
|
||||
Parser p;
|
||||
argparse::Parser p;
|
||||
p.no_unrecognized();
|
||||
REQUIRE(p.parse(argc, argv));
|
||||
}
|
||||
@@ -73,7 +82,7 @@ TEST_CASE("argparse") {
|
||||
char *argv[] = {"some-exe", "-f"};
|
||||
int argc = sizeof(argv) / sizeof(argv[0]);
|
||||
|
||||
Parser p;
|
||||
argparse::Parser p;
|
||||
p.no_unrecognized();
|
||||
REQUIRE(false == p.parse(argc, argv));
|
||||
}
|
||||
@@ -85,7 +94,7 @@ TEST_CASE("argparse") {
|
||||
std::string a;
|
||||
std::string b;
|
||||
|
||||
Parser p;
|
||||
argparse::Parser p;
|
||||
p.add_positional(a)->required();
|
||||
p.add_positional(b)->required();
|
||||
REQUIRE(false == p.parse(argc, argv));
|
||||
@@ -95,24 +104,16 @@ TEST_CASE("argparse") {
|
||||
char *argv[] = {"some-exe", "-h"};
|
||||
int argc = sizeof(argv) / sizeof(argv[0]);
|
||||
|
||||
std::string a;
|
||||
std::string b;
|
||||
|
||||
Parser p;
|
||||
argparse::Parser p;
|
||||
REQUIRE(true == p.parse(argc, argv));
|
||||
REQUIRE(p.need_help());
|
||||
|
||||
std::cerr << p.help() << "\n";
|
||||
}
|
||||
|
||||
SECTION("--help") {
|
||||
char *argv[] = {"some-exe", "--help"};
|
||||
int argc = sizeof(argv) / sizeof(argv[0]);
|
||||
|
||||
std::string a;
|
||||
std::string b;
|
||||
|
||||
Parser p;
|
||||
argparse::Parser p;
|
||||
REQUIRE(true == p.parse(argc, argv));
|
||||
REQUIRE(p.need_help());
|
||||
}
|
||||
@@ -121,12 +122,45 @@ TEST_CASE("argparse") {
|
||||
char *argv[] = {"some-exe", "--help", "--"};
|
||||
int argc = sizeof(argv) / sizeof(argv[0]);
|
||||
|
||||
std::string a;
|
||||
std::string b;
|
||||
|
||||
Parser p;
|
||||
argparse::Parser p;
|
||||
REQUIRE(true == p.parse(argc, argv));
|
||||
REQUIRE(p.need_help());
|
||||
}
|
||||
|
||||
SECTION("double --") {
|
||||
char *argv[] = {"some-exe", "--flag", "--", "--", "aa"};
|
||||
int argc = sizeof(argv) / sizeof(argv[0]);
|
||||
|
||||
std::string a, b;
|
||||
bool flag = false;
|
||||
|
||||
argparse::Parser p;
|
||||
p.add_flag(flag, "--flag");
|
||||
p.add_positional(a);
|
||||
p.add_positional(b);
|
||||
|
||||
REQUIRE(true == p.parse(argc, argv));
|
||||
REQUIRE(!p.need_help());
|
||||
|
||||
REQUIRE(a == "--");
|
||||
REQUIRE(b == "aa");
|
||||
REQUIRE(flag == true);
|
||||
}
|
||||
|
||||
SECTION("-- in option") {
|
||||
char *argv[] = {"some-exe", "--option", "--", "--", "aa"};
|
||||
int argc = sizeof(argv) / sizeof(argv[0]);
|
||||
|
||||
std::string a, option;
|
||||
|
||||
argparse::Parser p;
|
||||
p.add_option(option, "--option");
|
||||
p.add_positional(a);
|
||||
|
||||
REQUIRE(true == p.parse(argc, argv));
|
||||
REQUIRE(!p.need_help());
|
||||
|
||||
REQUIRE(a == "aa");
|
||||
REQUIRE(option == "--");
|
||||
}
|
||||
}
|
||||
|
@@ -1,2 +1,4 @@
|
||||
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
|
||||
// copyright Carl Pearson, 2022
|
||||
|
||||
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
|
||||
#include "catch2/catch.hpp"
|
||||
|
Reference in New Issue
Block a user