Squashed 'libs/CommService/' content from commit 7ccc0fc

git-subtree-dir: libs/CommService
git-subtree-split: 7ccc0fce88bbc5969df060058cf0fb57abe3bcf9
This commit is contained in:
Henry Winkel
2022-09-15 09:53:53 +02:00
commit cc67e4840f
799 changed files with 179487 additions and 0 deletions

View File

@@ -0,0 +1,483 @@
{
"projectName": "CLI11",
"projectOwner": "CLIUtils",
"repoType": "github",
"repoHost": "https://github.com",
"files": [
"README.md"
],
"imageSize": 100,
"commit": true,
"commitConvention": "atom",
"contributors": [
{
"login": "henryiii",
"name": "Henry Schreiner",
"avatar_url": "https://avatars1.githubusercontent.com/u/4616906?v=4",
"profile": "http://iscinumpy.gitlab.io",
"contributions": [
"bug",
"doc",
"code"
]
},
{
"login": "phlptp",
"name": "Philip Top",
"avatar_url": "https://avatars0.githubusercontent.com/u/20667153?v=4",
"profile": "https://github.com/phlptp",
"contributions": [
"bug",
"doc",
"code"
]
},
{
"login": "cbachhuber",
"name": "Christoph Bachhuber",
"avatar_url": "https://avatars0.githubusercontent.com/u/27212661?v=4",
"profile": "https://www.linkedin.com/in/cbachhuber/",
"contributions": [
"example",
"code"
]
},
{
"login": "lambdafu",
"name": "Marcus Brinkmann",
"avatar_url": "https://avatars1.githubusercontent.com/u/1138455?v=4",
"profile": "https://lambdafu.net/",
"contributions": [
"bug",
"code"
]
},
{
"login": "SkyToGround",
"name": "Jonas Nilsson",
"avatar_url": "https://avatars1.githubusercontent.com/u/58835?v=4",
"profile": "https://github.com/SkyToGround",
"contributions": [
"bug",
"code"
]
},
{
"login": "dvj",
"name": "Doug Johnston",
"avatar_url": "https://avatars2.githubusercontent.com/u/77217?v=4",
"profile": "https://github.com/dvj",
"contributions": [
"bug",
"code"
]
},
{
"login": "lczech",
"name": "Lucas Czech",
"avatar_url": "https://avatars0.githubusercontent.com/u/4741887?v=4",
"profile": "http://lucas-czech.de",
"contributions": [
"bug",
"code"
]
},
{
"login": "rafiw",
"name": "Rafi Wiener",
"avatar_url": "https://avatars3.githubusercontent.com/u/3034707?v=4",
"profile": "https://github.com/rafiw",
"contributions": [
"bug",
"code"
]
},
{
"login": "mensinda",
"name": "Daniel Mensinger",
"avatar_url": "https://avatars3.githubusercontent.com/u/3407462?v=4",
"profile": "https://github.com/mensinda",
"contributions": [
"platform"
]
},
{
"login": "jbriales",
"name": "Jesus Briales",
"avatar_url": "https://avatars1.githubusercontent.com/u/6850478?v=4",
"profile": "https://github.com/jbriales",
"contributions": [
"code",
"bug"
]
},
{
"login": "seanfisk",
"name": "Sean Fisk",
"avatar_url": "https://avatars0.githubusercontent.com/u/410322?v=4",
"profile": "https://seanfisk.com/",
"contributions": [
"bug",
"code"
]
},
{
"login": "fpeng1985",
"name": "fpeng1985",
"avatar_url": "https://avatars1.githubusercontent.com/u/87981?v=4",
"profile": "https://github.com/fpeng1985",
"contributions": [
"code"
]
},
{
"login": "almikhayl",
"name": "almikhayl",
"avatar_url": "https://avatars2.githubusercontent.com/u/6747040?v=4",
"profile": "https://github.com/almikhayl",
"contributions": [
"code",
"platform"
]
},
{
"login": "andrew-hardin",
"name": "Andrew Hardin",
"avatar_url": "https://avatars0.githubusercontent.com/u/16496326?v=4",
"profile": "https://github.com/andrew-hardin",
"contributions": [
"code"
]
},
{
"login": "SX91",
"name": "Anton",
"avatar_url": "https://avatars2.githubusercontent.com/u/754754?v=4",
"profile": "https://github.com/SX91",
"contributions": [
"code"
]
},
{
"login": "helmesjo",
"name": "Fred Helmesjö",
"avatar_url": "https://avatars0.githubusercontent.com/u/2501070?v=4",
"profile": "https://github.com/helmesjo",
"contributions": [
"bug",
"code"
]
},
{
"login": "skannan89",
"name": "Kannan",
"avatar_url": "https://avatars0.githubusercontent.com/u/11918764?v=4",
"profile": "https://github.com/skannan89",
"contributions": [
"bug",
"code"
]
},
{
"login": "kraj",
"name": "Khem Raj",
"avatar_url": "https://avatars3.githubusercontent.com/u/465279?v=4",
"profile": "http://himvis.com",
"contributions": [
"code"
]
},
{
"login": "mogigoma",
"name": "Mak Kolybabi",
"avatar_url": "https://avatars2.githubusercontent.com/u/130862?v=4",
"profile": "https://www.mogigoma.com/",
"contributions": [
"doc"
]
},
{
"login": "msoeken",
"name": "Mathias Soeken",
"avatar_url": "https://avatars0.githubusercontent.com/u/1998245?v=4",
"profile": "http://msoeken.github.io",
"contributions": [
"doc"
]
},
{
"login": "nathanhourt",
"name": "Nathan Hourt",
"avatar_url": "https://avatars2.githubusercontent.com/u/271977?v=4",
"profile": "https://github.com/nathanhourt",
"contributions": [
"bug",
"code"
]
},
{
"login": "pleroux0",
"name": "Paul le Roux",
"avatar_url": "https://avatars2.githubusercontent.com/u/39619854?v=4",
"profile": "https://github.com/pleroux0",
"contributions": [
"code",
"platform"
]
},
{
"login": "chfast",
"name": "Paweł Bylica",
"avatar_url": "https://avatars1.githubusercontent.com/u/573380?v=4",
"profile": "https://github.com/chfast",
"contributions": [
"platform"
]
},
{
"login": "peterazmanov",
"name": "Peter Azmanov",
"avatar_url": "https://avatars0.githubusercontent.com/u/15322318?v=4",
"profile": "https://github.com/peterazmanov",
"contributions": [
"code"
]
},
{
"login": "delpinux",
"name": "Stéphane Del Pino",
"avatar_url": "https://avatars0.githubusercontent.com/u/35096584?v=4",
"profile": "https://github.com/delpinux",
"contributions": [
"code"
]
},
{
"login": "metopa",
"name": "Viacheslav Kroilov",
"avatar_url": "https://avatars2.githubusercontent.com/u/3974178?v=4",
"profile": "https://github.com/metopa",
"contributions": [
"code"
]
},
{
"login": "ChristosT",
"name": "christos",
"avatar_url": "https://avatars0.githubusercontent.com/u/6725596?v=4",
"profile": "http://cs.odu.edu/~ctsolakis",
"contributions": [
"code"
]
},
{
"login": "deining",
"name": "deining",
"avatar_url": "https://avatars3.githubusercontent.com/u/18169566?v=4",
"profile": "https://github.com/deining",
"contributions": [
"doc"
]
},
{
"login": "elszon",
"name": "elszon",
"avatar_url": "https://avatars0.githubusercontent.com/u/2971495?v=4",
"profile": "https://github.com/elszon",
"contributions": [
"code"
]
},
{
"login": "ncihnegn",
"name": "ncihnegn",
"avatar_url": "https://avatars3.githubusercontent.com/u/12021721?v=4",
"profile": "https://github.com/ncihnegn",
"contributions": [
"code"
]
},
{
"login": "nurelin",
"name": "nurelin",
"avatar_url": "https://avatars3.githubusercontent.com/u/5276274?v=4",
"profile": "https://github.com/nurelin",
"contributions": [
"code"
]
},
{
"login": "ryan4729",
"name": "ryan4729",
"avatar_url": "https://avatars3.githubusercontent.com/u/40183301?v=4",
"profile": "https://github.com/ryan4729",
"contributions": [
"test"
]
},
{
"login": "slurps-mad-rips",
"name": "Isabella Muerte",
"avatar_url": "https://avatars0.githubusercontent.com/u/63051?v=4",
"profile": "https://izzys.casa",
"contributions": [
"platform"
]
},
{
"login": "KOLANICH",
"name": "KOLANICH",
"avatar_url": "https://avatars1.githubusercontent.com/u/240344?v=4",
"profile": "https://github.com/KOLANICH",
"contributions": [
"platform"
]
},
{
"login": "jgerityneurala",
"name": "James Gerity",
"avatar_url": "https://avatars2.githubusercontent.com/u/57360646?v=4",
"profile": "https://github.com/jgerityneurala",
"contributions": [
"doc"
]
},
{
"login": "jsoref",
"name": "Josh Soref",
"avatar_url": "https://avatars0.githubusercontent.com/u/2119212?v=4",
"profile": "https://github.com/jsoref",
"contributions": [
"tool"
]
},
{
"login": "geir-t",
"name": "geir-t",
"avatar_url": "https://avatars3.githubusercontent.com/u/35292136?v=4",
"profile": "https://github.com/geir-t",
"contributions": [
"platform"
]
},
{
"login": "certik",
"name": "Ondřej Čertík",
"avatar_url": "https://avatars3.githubusercontent.com/u/20568?v=4",
"profile": "https://ondrejcertik.com/",
"contributions": [
"bug"
]
},
{
"login": "samhocevar",
"name": "Sam Hocevar",
"avatar_url": "https://avatars2.githubusercontent.com/u/245089?v=4",
"profile": "http://sam.hocevar.net/",
"contributions": [
"code"
]
},
{
"login": "rcurtin",
"name": "Ryan Curtin",
"avatar_url": "https://avatars0.githubusercontent.com/u/1845039?v=4",
"profile": "http://www.ratml.org/",
"contributions": [
"doc"
]
},
{
"login": "mbhall88",
"name": "Michael Hall",
"avatar_url": "https://avatars3.githubusercontent.com/u/20403931?v=4",
"profile": "https://mbh.sh",
"contributions": [
"doc"
]
},
{
"login": "ferdymercury",
"name": "ferdymercury",
"avatar_url": "https://avatars3.githubusercontent.com/u/10653970?v=4",
"profile": "https://github.com/ferdymercury",
"contributions": [
"doc"
]
},
{
"login": "jakoblover",
"name": "Jakob Lover",
"avatar_url": "https://avatars0.githubusercontent.com/u/14160441?v=4",
"profile": "https://github.com/jakoblover",
"contributions": [
"code"
]
},
{
"login": "ZeeD26",
"name": "Dominik Steinberger",
"avatar_url": "https://avatars2.githubusercontent.com/u/2487468?v=4",
"profile": "https://github.com/ZeeD26",
"contributions": [
"code"
]
},
{
"login": "dfleury2",
"name": "D. Fleury",
"avatar_url": "https://avatars1.githubusercontent.com/u/4805384?v=4",
"profile": "https://github.com/dfleury2",
"contributions": [
"code"
]
},
{
"login": "dbarowy",
"name": "Dan Barowy",
"avatar_url": "https://avatars3.githubusercontent.com/u/573142?v=4",
"profile": "https://github.com/dbarowy",
"contributions": [
"doc"
]
},
{
"login": "paddy-hack",
"name": "Olaf Meeuwissen",
"avatar_url": "https://avatars.githubusercontent.com/u/6804372?v=4",
"profile": "https://github.com/paddy-hack",
"contributions": [
"code"
]
},
{
"login": "dryleev",
"name": "dryleev",
"avatar_url": "https://avatars.githubusercontent.com/u/83670813?v=4",
"profile": "https://github.com/dryleev",
"contributions": [
"code"
]
},
{
"login": "AnticliMaxtic",
"name": "Max",
"avatar_url": "https://avatars.githubusercontent.com/u/43995389?v=4",
"profile": "https://github.com/AnticliMaxtic",
"contributions": [
"code"
]
},
{
"login": "alexdewar",
"name": "Alex Dewar",
"avatar_url": "https://avatars.githubusercontent.com/u/23149834?v=4",
"profile": "https://profiles.sussex.ac.uk/p281168-alex-dewar/publications",
"contributions": [
"code"
]
}
],
"contributorsPerLine": 7,
"skipCi": true
}

38
libs/CLI11/.appveyor.yml Normal file
View File

@@ -0,0 +1,38 @@
version: 2.2.0.{build}
branches:
only:
- main
- v1
install:
- git submodule update --init --recursive
- py -3 --version
- set PATH=C:\Python38-x64;C:\Python38-x64\Scripts;%PATH%
- cmake --version
- python --version
- python -m pip --version
- python -m pip install conan
- conan user
- conan --version
build_script:
- mkdir build
- cd build
- ps:
cmake .. -DCLI11_WARNINGS_AS_ERRORS=ON -DCLI11_SINGLE_FILE_TESTS=ON
-DCMAKE_BUILD_TYPE=Debug -DCMAKE_GENERATOR="Visual Studio 14 2015"
- ps: cmake --build .
- cd ..
- conan create . CLIUtils/CLI11
test_script:
- cd build
- ps: ctest --output-on-failure -C Debug
notifications:
- provider: Webhook
url: https://webhooks.gitter.im/e/0185e91c5d989a476d7b
on_build_success: false
on_build_failure: true
on_build_status_changed: true

View File

@@ -0,0 +1,13 @@
steps:
- task: CMake@1
inputs:
cmakeArgs:
.. -DCLI11_WARNINGS_AS_ERRORS=ON -DCLI11_SINGLE_FILE=$(cli11.single)
-DCMAKE_CXX_STANDARD=$(cli11.std)
-DCLI11_SINGLE_FILE_TESTS=$(cli11.single)
-DCMAKE_BUILD_TYPE=$(cli11.build_type) $(cli11.options)
displayName: "Configure"
- script: cmake --build .
displayName: "Build"
workingDirectory: build

View File

@@ -0,0 +1,17 @@
steps:
# Note that silkeh/clang does not include ca-certificates, so check the shasum for verification
- bash: |
wget --no-check-certificate "https://cmake.org/files/v3.14/cmake-3.14.3-Linux-x86_64.tar.gz"
echo "29faa62fb3a0b6323caa3d9557e1a5f1205614c0d4c5c2a9917f16a74f7eff68 cmake-3.14.3-Linux-x86_64.tar.gz" | shasum -sca 256
displayName: Download CMake
- task: ExtractFiles@1
inputs:
archiveFilePatterns: "cmake*.tar.gz"
destinationFolder: "cmake_program"
displayName: Extract CMake
- bash:
echo
"##vso[task.prependpath]$(Build.SourcesDirectory)/cmake_program/cmake-3.14.3-Linux-x86_64/bin"
displayName: Add CMake to PATH

View File

@@ -0,0 +1,9 @@
steps:
- script: ctest --output-on-failure -C $(cli11.build_type) -T test
displayName: "Test"
workingDirectory: build
- task: PublishTestResults@2
inputs:
testResultsFormat: "cTest"
testResultsFiles: "**/Test.xml"

View File

@@ -0,0 +1,25 @@
#!/bin/env sh
# (Source me)
set -evx
#DOXYGEN_URL="http://doxygen.nl/files/doxygen-1.8.17.src.tar.gz"
DOXYGEN_URL="https://github.com/doxygen/doxygen/archive/Release_1_8_15.tar.gz"
cd "${DEPS_DIR}"
if [[ ! -f "${DEPS_DIR}/doxygen/build/bin/doxygen" ]] ; then
echo "Downloading Doxygen"
mkdir -p doxygen
travis_retry wget --no-check-certificate --quiet -O - "${DOXYGEN_URL}" | tar --strip-components=1 -xz -C doxygen
cd doxygen
mkdir -p build
cd build
cmake ..
make -j2
fi
export PATH="${DEPS_DIR}/doxygen/build/bin:${PATH}"
cd "${TRAVIS_BUILD_DIR}"
set +evx

View File

@@ -0,0 +1,17 @@
#!/bin/env sh
# (Source me)
set -evx
LCOV_URL="http://ftp.de.debian.org/debian/pool/main/l/lcov/lcov_1.13.orig.tar.gz"
cd "${DEPS_DIR}"
if [[ ! -f "${DEPS_DIR}/lcov/bin/lcov" ]] ; then
echo "Downloading lcov"
mkdir -p lcov
travis_retry wget --no-check-certificate --quiet -O - "${LCOV_URL}" | tar --strip-components=1 -xz -C lcov
fi
export PATH="${DEPS_DIR}/lcov/bin:${PATH}"
cd "${TRAVIS_BUILD_DIR}"
set +evx

23
libs/CLI11/.ci/make_and_test.sh Executable file
View File

@@ -0,0 +1,23 @@
#!/usr/bin/env bash
echo -en "travis_fold:start:script.build\\r"
echo "Building..."
STD="$1"
shift
set -evx
mkdir -p build
cd build
cmake .. -DCLI11_WARNINGS_AS_ERRORS=ON -DCLI11_SINGLE_FILE=ON -DCMAKE_CXX_STANDARD="$STD" -DCLI11_SINGLE_FILE_TESTS=ON -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_COMPILER_LAUNCHER=ccache $@
cmake --build . -- -j2
set +evx
echo -en "travis_fold:end:script.build\\r"
echo -en "travis_fold:start:script.test\\r"
echo "Testing..."
set -evx
ctest --output-on-failure
set +evx
echo -en "travis_fold:end:script.test\\r"

27
libs/CLI11/.ci/run_codecov.sh Executable file
View File

@@ -0,0 +1,27 @@
#!/usr/bin/env bash
echo -en "travis_fold:start:script.build\\r"
echo "Building..."
set -evx
cd "${TRAVIS_BUILD_DIR}"
mkdir -p build
cd build
cmake .. -DCLI11_SINGLE_FILE_TESTS=OFF -DCLI11_EXAMPLES=OFF -DCMAKE_BUILD_TYPE=Coverage
cmake --build . -- -j2
cmake --build . --target CLI11_coverage
set +evx
echo -en "travis_fold:end:script.build\\r"
echo -en "travis_fold:start:script.lcov\\r"
echo "Capturing and uploading LCov..."
set -evx
lcov --directory . --capture --output-file coverage.info # capture coverage info
lcov --remove coverage.info '*/tests/*' '*/examples/*' '*gtest*' '*gmock*' '/usr/*' --output-file coverage.info # filter out system
lcov --list coverage.info #debug info
# Uploading report to CodeCov
bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports"
set +evx
echo -en "travis_fold:end:script.lcov\\r"

86
libs/CLI11/.clang-format Normal file
View File

@@ -0,0 +1,86 @@
Language: Cpp
BasedOnStyle: LLVM
# AccessModifierOffset: -2
# AlignAfterOpenBracket: Align
# AlignConsecutiveAssignments: false
# AlignConsecutiveDeclarations: false
# AlignEscapedNewlinesLeft: false
# AlignOperands: true
# AlignTrailingComments: true
# AllowAllParametersOfDeclarationOnNextLine: true
# AllowShortBlocksOnASingleLine: false
# AllowShortCaseLabelsOnASingleLine: false
# AllowShortFunctionsOnASingleLine: All
# AllowShortIfStatementsOnASingleLine: false
# AllowShortLoopsOnASingleLine: false
# AlwaysBreakAfterDefinitionReturnType: None
# AlwaysBreakAfterReturnType: None
# AlwaysBreakBeforeMultilineStrings: false
# AlwaysBreakTemplateDeclarations: false
BinPackArguments: false
BinPackParameters: false
# BraceWrapping:
# AfterClass: false
# AfterControlStatement: false
# AfterEnum: false
# AfterFunction: false
# AfterNamespace: false
# AfterObjCDeclaration: false
# AfterStruct: false
# AfterUnion: false
# BeforeCatch: false
# BeforeElse: false
# IndentBraces: false
# BreakBeforeBinaryOperators: None
# BreakBeforeBraces: Attach
# BreakBeforeTernaryOperators: true
# BreakConstructorInitializersBeforeComma: false
# BreakAfterJavaFieldAnnotations: false
# BreakStringLiterals: true
ColumnLimit: 120
# CommentPragmas: '^ IWYU pragma:'
# ConstructorInitializerAllOnOneLineOrOnePerLine: false
# ConstructorInitializerIndentWidth: 4
# ContinuationIndentWidth: 4
# Cpp11BracedListStyle: true
# DerivePointerAlignment: false
# DisableFormat: false
# ExperimentalAutoDetectBinPacking: false
# ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
# IncludeIsMainRegex: '$'
# IndentCaseLabels: false
IndentWidth: 4
# IndentWrappedFunctionNames: false
# JavaScriptQuotes: Leave
# JavaScriptWrapImports: true
# KeepEmptyLinesAtTheStartOfBlocks: true
# MacroBlockBegin: ''
# MacroBlockEnd: ''
# MaxEmptyLinesToKeep: 1
# NamespaceIndentation: None
# ObjCBlockIndentWidth: 2
# ObjCSpaceAfterProperty: false
# ObjCSpaceBeforeProtocolList: true
# PenaltyBreakBeforeFirstCallParameter: 19
# PenaltyBreakComment: 300
# PenaltyBreakFirstLessLess: 120
# PenaltyBreakString: 1000
# PenaltyExcessCharacter: 1000000
# PenaltyReturnTypeOnItsOwnLine: 60
# PointerAlignment: Right
# ReflowComments: true
SortIncludes: true
# SpaceAfterCStyleCast: false
# SpaceAfterTemplateKeyword: true
# SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: Never
# SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
# SpacesInAngles: false
# SpacesInContainerLiterals: true
# SpacesInCStyleCastParentheses: false
# SpacesInParentheses: false
# SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 4
UseTab: Never

17
libs/CLI11/.clang-tidy Normal file
View File

@@ -0,0 +1,17 @@
# Checks that will be implemented in future PRs:
# performance-unnecessary-value-param, hints to ~110 issues. Be careful with implementing the suggested changes of this one, as auto-fixes may break the code
FormatStyle: file
Checks: >
-*, google-*, -google-runtime-references, llvm-include-order,
llvm-namespace-comment, misc-throw-by-value-catch-by-reference, modernize*,
-modernize-use-trailing-return-type, readability-container-size-empty,
WarningsAsErrors: "*"
HeaderFilterRegex: ".*hpp"
CheckOptions:
- key: google-readability-braces-around-statements.ShortStatementLines
value: "3"

View File

@@ -0,0 +1,6 @@
format:
line_width: 99
# Causes a few issues - can be solved later, possibly.
markup:
enable_markup: false

3
libs/CLI11/.codecov.yml Normal file
View File

@@ -0,0 +1,3 @@
ignore:
- "tests"
- "examples"

13
libs/CLI11/.editorconfig Normal file
View File

@@ -0,0 +1,13 @@
root = true
[*]
indent_style = space
insert_final_newline = true
end_of_line = lf
trim_trailing_whitespace = true
[*.cpp,*.hpp,*.py]
indent_size = 4
[*.yml]
indent_size = 2

102
libs/CLI11/.github/CONTRIBUTING.md vendored Normal file
View File

@@ -0,0 +1,102 @@
# Contributing
Thanks for considering to write a Pull Request (PR) for CLI11! Here are a few
guidelines to get you started:
Make sure you are comfortable with the license; all contributions are licensed
under the original license.
## Adding functionality
Make sure any new functions you add are are:
- Documented by `///` documentation for Doxygen
- Mentioned in the instructions in the README, though brief mentions are okay
- Explained in your PR (or previously explained in an Issue mentioned in the PR)
- Completely covered by tests
In general, make sure the addition is well thought out and does not increase the
complexity of CLI11 needlessly.
## Things you should know
- Once you make the PR, tests will run to make sure your code works on all
supported platforms
- The test coverage is also measured, and that should remain 100%
- Formatting should be done with pre-commit, otherwise the format check will not
pass. However, it is trivial to apply this to your PR, so don't worry about
this check. If you do want to run it, see below.
- Everything must pass clang-tidy as well, run with `-DCLI11_CLANG_TIDY=ON` (if
you set `-DCLI11_CLANG_TIDY_OPTIONS="-fix"`, make sure you use a single
threaded build process, or just build one example target).
- Your changes must also conform to most of the
[Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html)
rules checked by [cpplint](https://github.com/cpplint/cpplint). For unused
cpplint filters and justifications, see [CPPLINT.cfg](/CPPLINT.cfg).
## Pre-commit
Format is handled by pre-commit. You should install it (or use
[pipx](https://pypa.github.io/pipx/)):
```bash
python3 -m pip install pre-commit
```
Then, you can run it on the items you've added to your staging area, or all
files:
```bash
pre-commit run
# OR
pre-commit run --all-files
```
And, if you want to always use it, you can install it as a git hook (hence the
name, pre-commit):
```bash
pre-commit install
```
## For developers releasing to Conan.io
This is now done by the CI system on tagged releases. Previously, the steps to
make a Conan.io release were:
```bash
conan remove '*' # optional, I like to be clean
conan create . cliutils/stable
conan upload "*" -r cli11 --all
```
Here I've assumed that the remote is `cli11`.
## For maintainers: remember to add contributions
In a commit to a PR, just add
"`@all-contributors please add <username> for <contributions>`" or similar (see
<https://allcontributors.org>). Use `code` for code, `bug` if an issue was
submitted, `platform` for packaging stuff, and `doc` for documentation updates.
To run locally, do:
```bash
yarn add --dev all-contributors-cli
yarn all-contributors add username code,bug
```
## For maintainers: Making a release
Remember to replace the emoji in the readme, being careful not to replace the
ones in all-contributors if any overlap.
Steps:
- Update changelog if needed
- Update the version in `.appveyor.yml` and `include/CLI/Version.hpp`.
- Find and replace in README (new minor/major release only):
- Replace " 🆕" and "🆕 " with "" (ignores the description line)
- Check for `\/\/$` (vi syntax) to catch leftover `// 🆕`
- Replace "🚧" with "🆕" (manually ignore the description line)
- Make a release in the GitHub UI, use a name such as "Version X.Y(.Z): Title"

View File

@@ -0,0 +1,25 @@
name: Quick CMake config
description: "Runs CMake 3.4+ (if already setup)"
inputs:
args:
description: "Other arguments"
required: false
default: ""
cmake-version:
description: "The CMake version to run"
required: true
runs:
using: composite
steps:
- name: CMake ${{ inputs.cmake-version }}
uses: jwlawson/actions-setup-cmake@v1.12
with:
cmake-version: "${{ inputs.cmake-version }}"
- run: |
mkdir -p build-tmp
touch build-tmp/tmp
rm -r build-tmp/*
(cd build-tmp && cmake .. ${{ inputs.args }})
rm -r build-tmp
shell: bash

16
libs/CLI11/.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,16 @@
version: 2
updates:
# Maintain dependencies for GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
ignore:
# Official actions have moving tags like v1
# that are used, so they don't need updates here
- dependency-name: "actions/checkout"
- dependency-name: "actions/setup-python"
- dependency-name: "actions/cache"
- dependency-name: "actions/upload-artifact"
- dependency-name: "actions/download-artifact"
- dependency-name: "actions/labeler"

4
libs/CLI11/.github/labeler_merged.yml vendored Normal file
View File

@@ -0,0 +1,4 @@
needs changelog:
- all: ["!CHANGELOG.md"]
needs README:
- all: ["!README.md"]

57
libs/CLI11/.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,57 @@
name: Build
on:
push:
branches:
- main
- v*
tags:
- "*"
pull_request:
jobs:
single-header:
name: Single header
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: true
- uses: actions/setup-python@v2
- name: Prepare CMake config
run: cmake -S . -B build -DCLI11_SINGLE_FILE=ON
- name: Make package
run: cmake --build build --target package_source
- name: Copy source packages
run: |
mkdir -p CLI11-Source
cp build/CLI11-*-Source.* CLI11-Source
cp build/CLI11-*-Source.* .
- name: Make header
run: cmake --build build --target CLI11-generate-single-file
- name: Copy file to main folder
run: cp build/include/CLI11.hpp CLI11.hpp
- uses: actions/upload-artifact@v2
with:
name: CLI11.hpp
path: CLI11.hpp
- uses: actions/upload-artifact@v2
with:
name: CLI11-Source
path: CLI11-Source
- name: Release
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
with:
files: |
CLI11.hpp
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -0,0 +1,15 @@
name: PR merged
on:
pull_request_target:
types: [closed]
jobs:
label-merged:
name: Changelog needed
runs-on: ubuntu-latest
if: github.event.pull_request.merged == true
steps:
- uses: actions/labeler@main
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
configuration-path: .github/labeler_merged.yml

184
libs/CLI11/.github/workflows/tests.yml vendored Normal file
View File

@@ -0,0 +1,184 @@
name: Tests
on:
push:
branches:
- main
- v*
pull_request:
jobs:
cuda-build:
name: CUDA build only
runs-on: ubuntu-latest
container: nvidia/cuda:10.2-devel-ubuntu18.04
steps:
- uses: actions/checkout@v1
with:
submodules: true
- name: Add wget
run: apt-get update && apt-get install -y wget
- name: Get cmake
uses: jwlawson/actions-setup-cmake@v1.12
- name: Configure
run: cmake -S . -B build -DCLI11_CUDA_TESTS=ON
- name: Build
run: cmake --build build -j2
boost-build:
name: Boost build
runs-on: ubuntu-latest
container: zouzias/boost:1.76.0
steps:
- uses: actions/checkout@v1
with:
submodules: true
- name: Add deps
run: apt-get update && apt-get install make
- name: Get CMake
uses: jwlawson/actions-setup-cmake@v1.12
- name: Configure
run: cmake -S . -B build -DCLI11_BOOST=ON
- name: Build
run: cmake --build build -j2
- name: Run tests
run: ctest --output-on-failure
working-directory: build
meson-build:
name: Meson build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Prepare commands
run: |
pipx install meson
pipx install ninja
- name: Configure
run: meson setup build-meson . -Dtests=true
- name: Build
run: meson compile -C build-meson
cmake-config:
name: CMake config check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Check CMake 3.4
with:
cmake-version: "3.4"
uses: ./.github/actions/quick_cmake
- name: Check CMake 3.5
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.5"
if: success() || failure()
- name: Check CMake 3.6
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.6"
if: success() || failure()
- name: Check CMake 3.7
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.7"
if: success() || failure()
- name: Check CMake 3.8
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.8"
if: success() || failure()
- name: Check CMake 3.9
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.9"
if: success() || failure()
- name: Check CMake 3.10
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.10"
if: success() || failure()
- name: Check CMake 3.11 (full)
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.11"
args: -DCLI11_SANITIZERS=ON -DCLI11_BUILD_EXAMPLES_JSON=ON
if: success() || failure()
- name: Check CMake 3.12
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.12"
if: success() || failure()
- name: Check CMake 3.13
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.13"
if: success() || failure()
- name: Check CMake 3.14
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.14"
if: success() || failure()
- name: Check CMake 3.15
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.15"
if: success() || failure()
- name: Check CMake 3.16
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.16"
if: success() || failure()
- name: Check CMake 3.17
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.17"
if: success() || failure()
- name: Check CMake 3.18
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.18"
if: success() || failure()
- name: Check CMake 3.19
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.19"
if: success() || failure()
- name: Check CMake 3.20
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.20"
if: success() || failure()
- name: Check CMake 3.21 (full)
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.21"
args: -DCLI11_SANITIZERS=ON -DCLI11_BUILD_EXAMPLES_JSON=ON
if: success() || failure()
- name: Check CMake 3.22 (full)
uses: ./.github/actions/quick_cmake
with:
cmake-version: "3.22"
args: -DCLI11_SANITIZERS=ON -DCLI11_BUILD_EXAMPLES_JSON=ON
if: success() || failure()

15
libs/CLI11/.gitignore vendored Normal file
View File

@@ -0,0 +1,15 @@
a.out*
*.swp
/*build*
/test_package/build
/Makefile
/CMakeFiles/*
/cmake_install.cmake
/*.kdev4
/html/*
!/meson.build
/node_modules/*
/package.json
/yarn.lock
/CLI11.hpp

View File

@@ -0,0 +1,86 @@
ci:
autoupdate_commit_msg: "chore(deps): pre-commit.ci autoupdate"
autofix_commit_msg: "style: pre-commit.ci fixes"
repos:
- repo: https://github.com/psf/black
rev: 22.3.0
hooks:
- id: black
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.3.0
hooks:
- id: check-added-large-files
- id: check-case-conflict
- id: check-merge-conflict
- id: check-symlinks
- id: check-yaml
- id: end-of-file-fixer
- id: mixed-line-ending
- id: trailing-whitespace
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: v14.0.5
hooks:
- id: clang-format
types_or: [c++, c, cuda]
- repo: https://github.com/cheshirekow/cmake-format-precommit
rev: v0.6.13
hooks:
- id: cmake-format
additional_dependencies: [pyyaml]
- repo: https://github.com/pre-commit/mirrors-prettier
rev: "v2.7.1"
hooks:
- id: prettier
types_or: [yaml, markdown, html, css, scss, javascript, json]
args: [--prose-wrap=always]
- repo: https://github.com/markdownlint/markdownlint
rev: v0.11.0
hooks:
- id: markdownlint
args: ["--style=scripts/mdlint_style.rb"]
- repo: local
hooks:
- id: remarklint
name: remarklint
language: node
entry: remark
types: [markdown]
args: ["--frail", "--quiet"]
additional_dependencies:
[
remark,
remark-lint,
remark-cli,
remark-preset-lint-recommended,
remark-lint-list-item-indent,
remark-lint-no-undefined-references,
]
- repo: local
hooks:
- id: disallow-caps
name: Disallow improper capitalization
language: pygrep
entry: PyBind|Numpy|Cmake|CCache|PyTest|Github
exclude: .pre-commit-config.yaml
- repo: local
hooks:
- id: avoid-msvc-macro
name: Avoid MSVC <=2017 min/max macro (use extra parens)
language: pygrep
entry: \b(min|max)\(
exclude: .pre-commit-config.yaml
- repo: https://github.com/codespell-project/codespell
rev: v2.1.0
hooks:
- id: codespell
args: ["-L", "atleast,ans,doub,inout"]

7
libs/CLI11/.remarkrc Normal file
View File

@@ -0,0 +1,7 @@
{
"plugins": [
"remark-preset-lint-recommended",
["remark-lint-list-item-indent", "space"],
["remark-lint-no-undefined-references", {"allow": ["^1"]}]
]
}

964
libs/CLI11/CHANGELOG.md Normal file
View File

@@ -0,0 +1,964 @@
# Changelog
## Version 2.2: Option and Configuration Flexibility
New features include support for output of an empty vector, a summing option
policy that can be applied more broadly, and an option to validate optional
arguments to discriminate from positional arguments. A new validator to check
for files on a default path is included to allow one or more default paths for
configuration files or other file arguments. A number of bug fixes and code
cleanup for various build configurations. Clean up of some error outputs and
extension of existing capability to new types or situations.
There is a possible minor breaking change in behavior of certain types which
wrapped an integer, such as `std::atomic<int>` or `std::optional<int>` when used
in a flag. The default behavior is now as a single argument value vs. summing
all the arguments. The default summing behavior is now restricted to pure
integral types, int64_t, int, uint32_t, etc. Use the new `sum` multi option
policy to revert to the older behavior. The summing behavior on wrapper types
was not originally intended.
- Add `MultiOptionPolicy::Sum` and refactor the `add_flag` to fix a bug when
using `std::optional<bool>` as type. [#709][]
- Add support for an empty vector result in TOML and as a default string.
[#660][]
- Add `.validate_optional_arguments()` to support discriminating positional
arguments from vector option arguments. [#668][]
- Add `CLI::FileOnDefaultPath` to check for files on a specified default path.
[#698][]
- Change default value display in help messages from `=XXXX` to `[XXXXX]` to
make it clearer. [#666][]
- Modify the Range Validator to support additional types and clean up the error
output. [#690][]
- Bugfix: The trigger on parse modifier did not work on positional argument.s
[#713][]
- Bugfix: The single header file generation was missing custom namespace
generation. [#707][]
- Bugfix: Clean up File Error handling in the argument processing. [#678][]
- Bugfix: Fix a stack overflow error if nameless commands had fallthrough.
[#665][]
- Bugfix: A subcommand callback could be executed multiple times if it was a
member of an option group. [#666][]
- Bugfix: Fix an issue with vectors of multi argument types where partial
argument sets did not result in an error. [#661][]
- Bugfix: Fix an issue with type the template matching on C++20 and add some CI
builds for C++20. [#663][]
- Bugfix: Fix typo in C++20 detection on MSVC. [#706][]
- Bugfix: An issue where the detection of RTTI being disabled on certain MSVC
platforms did not disable the use of dynamic cast calls. [#666][]
- Bugfix: Resolve strict-overflow warning on some GCC compilers. [#666][]
- Backend: Add additional tests concerning the use of aliases for option groups
in config files. [#666][]
- Build: Add support for testing in meson and cleanup symbolic link generation.
[#701][], [#697][]
- Build: Support building in WebAssembly. [#679][]
[#660]: https://github.com/CLIUtils/CLI11/pull/660
[#661]: https://github.com/CLIUtils/CLI11/pull/661
[#663]: https://github.com/CLIUtils/CLI11/pull/663
[#665]: https://github.com/CLIUtils/CLI11/pull/665
[#666]: https://github.com/CLIUtils/CLI11/pull/666
[#668]: https://github.com/CLIUtils/CLI11/pull/668
[#678]: https://github.com/CLIUtils/CLI11/pull/678
[#679]: https://github.com/CLIUtils/CLI11/pull/679
[#690]: https://github.com/CLIUtils/CLI11/pull/690
[#697]: https://github.com/CLIUtils/CLI11/pull/697
[#698]: https://github.com/CLIUtils/CLI11/pull/698
[#701]: https://github.com/CLIUtils/CLI11/pull/701
[#706]: https://github.com/CLIUtils/CLI11/pull/706
[#707]: https://github.com/CLIUtils/CLI11/pull/707
[#709]: https://github.com/CLIUtils/CLI11/pull/709
[#713]: https://github.com/CLIUtils/CLI11/pull/713
## Version 2.1: Names and callbacks
The name restrictions for options and subcommands are now much looser, allowing
a wider variety of characters than before, even spaces can be used (use quotes
to include a space in most shells). The default configuration parser was
improved, allowing your configuration to sit in a larger file. And option
callbacks have a few new settings, allowing them to be run even if the option is
not passed, or every time the option is parsed.
- Option/subcommand name restrictions have been relaxed. Most characters are now
allowed. [#627][]
- The config parser can accept streams, specify a specific section, and inline
comment characters are supported [#630][]
- `force_callback` & `trigger_on_parse` added, allowing a callback to always run
on parse even if not present or every time the option is parsed [#631][]
- Bugfix(cmake): Only add `CONFIGURE_DEPENDS` if CLI11 is the main project
[#633][]
- Bugfix(cmake): Ensure the cmake/pkg-config files install to a arch independent
path [#635][]
- Bugfix: The single header file generation was missing the include guard.
[#620][]
[#620]: https://github.com/CLIUtils/CLI11/pull/620
[#627]: https://github.com/CLIUtils/CLI11/pull/627
[#630]: https://github.com/CLIUtils/CLI11/pull/630
[#631]: https://github.com/CLIUtils/CLI11/pull/631
[#633]: https://github.com/CLIUtils/CLI11/pull/633
[#635]: https://github.com/CLIUtils/CLI11/pull/635
### Version 2.1.1: Quick Windows fix
- A collision with `min`/`max` macros on Windows has been fixed. [#642][]
- Tests pass with Boost again [#646][]
- Running the pre-commit hooks in development no longer requires docker for
clang-format [#647][]
[#642]: https://github.com/CLIUtils/CLI11/pull/642
[#646]: https://github.com/CLIUtils/CLI11/pull/646
[#647]: https://github.com/CLIUtils/CLI11/pull/647
## Version 2.1.2: Better subproject builds
- Use `main` for the main branch of the repository [#657][]
- Bugfix(cmake): Enforce at least C++11 when using CMake target [#656][]
- Build: Don't run doxygen and CTest includes if a submodule [#656][]
- Build: Avoid a warning on CMake 3.22 [#656][]
- Build: Support compiling the tests with an external copy of Catch2 [#653][]
[#653]: https://github.com/CLIUtils/CLI11/pull/653
[#656]: https://github.com/CLIUtils/CLI11/pull/656
[#657]: https://github.com/CLIUtils/CLI11/pull/657
## Version 2.0: Simplification
This version focuses on cleaning up deprecated functionality, and some minor
default changes. The config processing is TOML compliant now. Atomics and
complex numbers are directly supported, along with other container improvements.
A new version flag option has finally been added. Subcommands are significantly
improved with new features and bugfixes for corner cases. This release contains
a lot of backend cleanup, including a complete overhaul of the testing system
and single file generation system.
- Built-in config format is TOML compliant now [#435][]
- Support multiline TOML [#528][]
- Support for configurable quotes [#599][]
- Support short/positional options in config mode [#443][]
- More powerful containers, support for `%%` separator [#423][]
- Support atomic types [#520][] and complex types natively [#423][]
- Add a type validator `CLI::TypeValidator<TYPE>` [#526][]
- Add a version flag easily [#452][], with help message [#601][]
- Support `->silent()` on subcommands. [#529][]
- Add alias section to help for subcommands [#545][]
- Allow quotes to specify a program name [#605][]
- Backend: redesigned MakeSingleFiles to have a higher level of manual control,
to support future features. [#546][]
- Backend: moved testing from GTest to Catch2 [#574][]
- Bugfix: avoid duplicated and missed calls to the final callback [#584][]
- Bugfix: support embedded newlines in more places [#592][]
- Bugfix: avoid listing helpall as a required flag [#530][]
- Bugfix: avoid a clash with WINDOWS define [#563][]
- Bugfix: the help flag didn't get processed when a config file was required
[#606][]
- Bugfix: fix description of non-configurable subcommands in config [#604][]
- Build: support pkg-config [#523][]
> ### Converting from CLI11 1.9
>
> - Removed deprecated set commands, use validators instead. [#565][]
> - The final "defaulted" bool has been removed, use `->capture_default_str()`
> instead. Use `app.option_defaults()->always_capture_default()` to set this
> for all future options. [#597][]
> - Use `add_option` on a complex number instead of `add_complex`, which has
> been removed.
[#423]: https://github.com/CLIUtils/CLI11/pull/423
[#435]: https://github.com/CLIUtils/CLI11/pull/435
[#443]: https://github.com/CLIUtils/CLI11/pull/443
[#452]: https://github.com/CLIUtils/CLI11/pull/452
[#520]: https://github.com/CLIUtils/CLI11/pull/520
[#523]: https://github.com/CLIUtils/CLI11/pull/523
[#526]: https://github.com/CLIUtils/CLI11/pull/526
[#528]: https://github.com/CLIUtils/CLI11/pull/528
[#529]: https://github.com/CLIUtils/CLI11/pull/529
[#530]: https://github.com/CLIUtils/CLI11/pull/530
[#545]: https://github.com/CLIUtils/CLI11/pull/545
[#546]: https://github.com/CLIUtils/CLI11/pull/546
[#563]: https://github.com/CLIUtils/CLI11/pull/563
[#565]: https://github.com/CLIUtils/CLI11/pull/565
[#574]: https://github.com/CLIUtils/CLI11/pull/574
[#584]: https://github.com/CLIUtils/CLI11/pull/584
[#592]: https://github.com/CLIUtils/CLI11/pull/592
[#597]: https://github.com/CLIUtils/CLI11/pull/597
[#599]: https://github.com/CLIUtils/CLI11/pull/599
[#601]: https://github.com/CLIUtils/CLI11/pull/601
[#604]: https://github.com/CLIUtils/CLI11/pull/604
[#605]: https://github.com/CLIUtils/CLI11/pull/605
[#606]: https://github.com/CLIUtils/CLI11/pull/606
## Version 1.9: Config files and cleanup
Config file handling was revamped to fix common issues, and now supports reading
[TOML](https://github.com/toml-lang/toml).
Adding options is significantly more powerful with support for things like
`std::tuple` and `std::array`, including with transforms. Several new
configuration options were added to facilitate a wider variety of apps. GCC 4.7
is no longer supported.
- Config files refactored, supports TOML (may become default output in 2.0)
[#362][]
- Added two template parameter form of `add_option`, allowing `std::optional` to
be supported without a special import [#285][]
- `string_view` now supported in reasonable places [#300][], [#285][]
- `immediate_callback`, `final_callback`, and `parse_complete_callback` added to
support controlling the App callback order [#292][], [#313][]
- Multiple positional arguments maintain order if `positionals_at_end` is set.
[#306][]
- Pair/tuple/array now supported, and validators indexed to specific components
in the objects [#307][], [#310][]
- Footer callbacks supported [#309][]
- Subcommands now support needs (including nameless subcommands) [#317][]
- More flexible type size, more useful `add_complex` [#325][], [#370][]
- Added new validators `CLI::NonNegativeNumber` and `CLI::PositiveNumber`
[#342][]
- Transform now supports arrays [#349][]
- Option groups can be hidden [#356][]
- Add `CLI::deprecate_option` and `CLI::retire_option` functions [#358][]
- More flexible and safer Option `default_val` [#387][]
- Backend: Cleaner type traits [#286][]
- Backend: File checking updates [#341][]
- Backend: Using pre-commit to format, checked in GitHub Actions [#336][]
- Backend: Clang-tidy checked again, CMake option now `CL11_CLANG_TIDY` [#390][]
- Backend: Warning cleanup, more checks from klocwork [#350][], Effective C++
[#354][], clang-tidy [#360][], CUDA NVCC [#365][], cross compile [#373][],
sign conversion [#382][], and cpplint [#400][]
- Docs: CLI11 Tutorial now hosted in the same repository [#304][], [#318][],
[#374][]
- Bugfix: Fixed undefined behavior in `checked_multiply` [#290][]
- Bugfix: `->check()` was adding the name to the wrong validator [#320][]
- Bugfix: Resetting config option works properly [#301][]
- Bugfix: Hidden flags were showing up in error printout [#333][]
- Bugfix: Enum conversion no longer broken if stream operator added [#348][]
- Build: The meson build system supported [#299][]
- Build: GCC 4.7 is no longer supported, due mostly to GoogleTest. GCC 4.8+ is
now required. [#160][]
- Build: Restructured significant portions of CMake build system [#394][]
> ### Converting from CLI11 1.8
>
> - Some deprecated methods dropped
> - `add_set*` should be replaced with `->check`/`->transform` and
> `CLI::IsMember` since 1.8
> - `get_defaultval` was replaced by `get_default_str` in 1.8
> - The true/false 4th argument to `add_option` is expected to be removed in
> 2.0, use `->capture_default_str()` since 1.8
[#160]: https://github.com/CLIUtils/CLI11/pull/160
[#285]: https://github.com/CLIUtils/CLI11/pull/285
[#286]: https://github.com/CLIUtils/CLI11/pull/286
[#290]: https://github.com/CLIUtils/CLI11/pull/290
[#292]: https://github.com/CLIUtils/CLI11/pull/292
[#299]: https://github.com/CLIUtils/CLI11/pull/299
[#300]: https://github.com/CLIUtils/CLI11/pull/300
[#301]: https://github.com/CLIUtils/CLI11/pull/301
[#304]: https://github.com/CLIUtils/CLI11/pull/304
[#306]: https://github.com/CLIUtils/CLI11/pull/306
[#307]: https://github.com/CLIUtils/CLI11/pull/307
[#309]: https://github.com/CLIUtils/CLI11/pull/309
[#310]: https://github.com/CLIUtils/CLI11/pull/310
[#313]: https://github.com/CLIUtils/CLI11/pull/313
[#317]: https://github.com/CLIUtils/CLI11/pull/317
[#318]: https://github.com/CLIUtils/CLI11/pull/318
[#320]: https://github.com/CLIUtils/CLI11/pull/320
[#325]: https://github.com/CLIUtils/CLI11/pull/325
[#333]: https://github.com/CLIUtils/CLI11/pull/333
[#336]: https://github.com/CLIUtils/CLI11/pull/336
[#341]: https://github.com/CLIUtils/CLI11/pull/341
[#342]: https://github.com/CLIUtils/CLI11/pull/342
[#348]: https://github.com/CLIUtils/CLI11/pull/348
[#349]: https://github.com/CLIUtils/CLI11/pull/349
[#350]: https://github.com/CLIUtils/CLI11/pull/350
[#354]: https://github.com/CLIUtils/CLI11/pull/354
[#356]: https://github.com/CLIUtils/CLI11/pull/356
[#358]: https://github.com/CLIUtils/CLI11/pull/358
[#360]: https://github.com/CLIUtils/CLI11/pull/360
[#362]: https://github.com/CLIUtils/CLI11/pull/362
[#365]: https://github.com/CLIUtils/CLI11/pull/365
[#370]: https://github.com/CLIUtils/CLI11/pull/370
[#373]: https://github.com/CLIUtils/CLI11/pull/373
[#374]: https://github.com/CLIUtils/CLI11/pull/374
[#382]: https://github.com/CLIUtils/CLI11/pull/382
[#387]: https://github.com/CLIUtils/CLI11/pull/387
[#390]: https://github.com/CLIUtils/CLI11/pull/390
[#394]: https://github.com/CLIUtils/CLI11/pull/394
[#400]: https://github.com/CLIUtils/CLI11/pull/400
### Version 1.9.1: Backporting fixes
This is a patch version that backports fixes from the development of 2.0.
- Support relative inclusion [#475][]
- Fix cases where spaces in paths could break CMake support [#471][]
- Fix an issue with string conversion [#421][]
- Cross-compiling improvement for Conan.io [#430][]
- Fix option group default propagation [#450][]
- Fix for C++20 [#459][]
- Support compiling with RTTI off [#461][]
[#421]: https://github.com/CLIUtils/CLI11/pull/421
[#430]: https://github.com/CLIUtils/CLI11/pull/430
[#450]: https://github.com/CLIUtils/CLI11/pull/450
[#459]: https://github.com/CLIUtils/CLI11/pull/459
[#461]: https://github.com/CLIUtils/CLI11/pull/461
[#471]: https://github.com/CLIUtils/CLI11/pull/471
[#475]: https://github.com/CLIUtils/CLI11/pull/475
## Version 1.8: Transformers, default strings, and flags
Set handling has been completely replaced by a new backend that works as a
Validator or Transformer. This provides a single interface instead of the 16
different functions in App. It also allows ordered collections to be used,
custom functions for filtering, and better help and error messages. You can also
use a collection of pairs (like `std::map`) to transform the match into an
output. Also new are inverted flags, which can cancel or reduce the count of
flags, and can also support general flag types. A new `add_option_fn` lets you
more easily program CLI11 options with the types you choose. Vector options now
support a custom separator. Apps can now be composed with unnamed subcommand
support. The final bool "defaults" flag when creating options has been replaced
by `->capture_default_str()` (ending an old limitation in construction made this
possible); the old method is still available but may be removed in future
versions.
- Replaced default help capture: `.add_option("name", value, "", True)` becomes
`.add_option("name", value)->capture_default_str()` [#242][]
- Added `.always_capture_default()` [#242][]
- New `CLI::IsMember` validator replaces set validation [#222][]
- `IsMember` also supports container of pairs, transform allows modification of
result [#228][]
- Added new Transformers, `CLI::AsNumberWithUnit` and `CLI::AsSizeValue`
[#253][]
- Much more powerful flags with different values [#211][], general types
[#235][]
- `add_option` now supports bool due to unified bool handling [#211][]
- Support for composable unnamed subcommands [#216][]
- Reparsing is better supported with `.remaining_for_passthrough()` [#265][]
- Custom vector separator using `->delimiter(char)` [#209][], [#221][], [#240][]
- Validators added for IP4 addresses and positive numbers [#210][] and numbers
[#262][]
- Minimum required Boost for optional Optionals has been corrected to 1.61
[#226][]
- Positionals can stop options from being parsed with `app.positionals_at_end()`
[#223][]
- Added `validate_positionals` [#262][]
- Positional parsing is much more powerful [#251][], duplicates supported
[#247][]
- Validators can be negated with `!` [#230][], and now handle tname functions
[#228][]
- Better enum support and streaming helper [#233][] and [#228][]
- Cleanup for shadow warnings [#232][]
- Better alignment on multiline descriptions [#269][]
- Better support for aarch64 [#266][]
- Respect `BUILD_TESTING` only if CLI11 is the main project; otherwise,
`CLI11_TESTING` must be used [#277][]
- Drop auto-detection of experimental optional and boost::optional; must be
enabled explicitly (too fragile) [#277][] [#279][]
> ### Converting from CLI11 1.7
>
> - `.add_option(..., true)` should be replaced by
> `.add_option(...)->capture_default_str()` or
> `app.option_defaults()->always_capture_default()` can be used
> - `app.add_set("--name", value, {"choice1", "choice2"})` should become
> `app.add_option("--name", value)->check(CLI::IsMember({"choice1", "choice2"}))`
> - The `_ignore_case` version of this can be replaced by adding
> `CLI::ignore_case` to the argument list in `IsMember`
> - The `_ignore_underscore` version of this can be replaced by adding
> `CLI::ignore_underscore` to the argument list in `IsMember`
> - The `_ignore_case_underscore` version of this can be replaced by adding both
> functions listed above to the argument list in `IsMember`
> - If you want an exact match to the original choice after one of the modifier
> functions matches, use `->transform` instead of `->check`
> - The `_mutable` versions of this can be replaced by passing a pointer or
> shared pointer into `IsMember`
> - An error with sets now produces a `ValidationError` instead of a
> `ConversionError`
[#209]: https://github.com/CLIUtils/CLI11/pull/209
[#210]: https://github.com/CLIUtils/CLI11/pull/210
[#211]: https://github.com/CLIUtils/CLI11/pull/211
[#216]: https://github.com/CLIUtils/CLI11/pull/216
[#221]: https://github.com/CLIUtils/CLI11/pull/221
[#222]: https://github.com/CLIUtils/CLI11/pull/222
[#223]: https://github.com/CLIUtils/CLI11/pull/223
[#226]: https://github.com/CLIUtils/CLI11/pull/226
[#228]: https://github.com/CLIUtils/CLI11/pull/228
[#230]: https://github.com/CLIUtils/CLI11/pull/230
[#232]: https://github.com/CLIUtils/CLI11/pull/232
[#233]: https://github.com/CLIUtils/CLI11/pull/233
[#235]: https://github.com/CLIUtils/CLI11/pull/235
[#240]: https://github.com/CLIUtils/CLI11/pull/240
[#242]: https://github.com/CLIUtils/CLI11/pull/242
[#247]: https://github.com/CLIUtils/CLI11/pull/247
[#251]: https://github.com/CLIUtils/CLI11/pull/251
[#253]: https://github.com/CLIUtils/CLI11/pull/253
[#262]: https://github.com/CLIUtils/CLI11/pull/262
[#265]: https://github.com/CLIUtils/CLI11/pull/265
[#266]: https://github.com/CLIUtils/CLI11/pull/266
[#269]: https://github.com/CLIUtils/CLI11/pull/269
[#277]: https://github.com/CLIUtils/CLI11/pull/277
[#279]: https://github.com/CLIUtils/CLI11/pull/279
## Version 1.7: Parse breakup
The parsing procedure now maps much more sensibly to complex, nested subcommand
structures. Each phase of the parsing happens on all subcommands before moving
on with the next phase of the parse. This allows several features, like required
environment variables, to work properly even through subcommand boundaries.
Passing the same subcommand multiple times is better supported. Several new
features were added as well, including Windows style option support, parsing
strings directly, and ignoring underscores in names. Adding a set that you plan
to change later must now be done with `add_mutable_set`.
- Support Windows style options with `->allow_windows_style_options`. [#187][]
On by default on Windows. [#190][]
- Added `parse(string)` to split up and parse a command-line style string
directly. [#186][]
- Added `ignore_underscore` and related functions, to ignore underscores when
matching names. [#185][]
- The default INI Config will now add quotes to strings with spaces [#195][]
- The default message now will mention the help-all flag also if present
[#197][]
- Added `->description` to set Option descriptions [#199][]
- Mutating sets (introduced in Version 1.6) now have a clear add method,
`add_mutable_set*`, since the set reference should not expire [#200][]
- Subcommands now track how many times they were parsed in a parsing process.
`count()` with no arguments will return the number of times a subcommand was
encountered. [#178][]
- Parsing is now done in phases: `shortcurcuits`, `ini`, `env`, `callbacks`, and
`requirements`; all subcommands complete a phase before moving on. [#178][]
- Calling parse multiple times is now officially supported without `clear`
(automatic). [#178][]
- Dropped the mostly undocumented `short_circuit` property, as help flag parsing
is a bit more complex, and the default callback behavior of options now works
properly. [#179][]
- Use the standard `BUILD_TESTING` over `CLI11_TESTING` if defined [#183][]
- Cleanup warnings [#191][]
- Remove deprecated names: `set_footer`, `set_name`, `set_callback`, and
`set_type_name`. Use without the `set_` instead. [#192][]
> ### Converting from CLI11 1.6
>
> - `->short_circuit()` is no longer needed, just remove it if you were using
> it - raising an exception will happen in the proper place now without it.
> - `->add_set*` becomes `->add_mutable_set*` if you were using the editable set
> feature
> - `footer`, `name`, `callback`, and `type_name` must be used instead of the
> `set_*` versions (deprecated previously).
[#178]: https://github.com/CLIUtils/CLI11/pull/178
[#183]: https://github.com/CLIUtils/CLI11/pull/183
[#185]: https://github.com/CLIUtils/CLI11/pull/185
[#186]: https://github.com/CLIUtils/CLI11/pull/186
[#187]: https://github.com/CLIUtils/CLI11/pull/187
[#190]: https://github.com/CLIUtils/CLI11/pull/190
[#191]: https://github.com/CLIUtils/CLI11/pull/191
[#192]: https://github.com/CLIUtils/CLI11/pull/192
[#197]: https://github.com/CLIUtils/CLI11/pull/197
[#195]: https://github.com/CLIUtils/CLI11/issues/195
[#199]: https://github.com/CLIUtils/CLI11/pull/199
[#200]: https://github.com/CLIUtils/CLI11/pull/200
### Version 1.7.1: Quick patch
This version provides a quick patch for a (correct) warning from GCC 8 for the
windows options code.
- Fix for Windows style option parsing [#201][]
- Improve `add_subcommand` when throwing an exception [#204][]
- Better metadata for Conan package [#202][]
[#201]: https://github.com/CLIUtils/CLI11/pull/201
[#202]: https://github.com/CLIUtils/CLI11/pull/202
[#204]: https://github.com/CLIUtils/CLI11/pull/204
## Version 1.6: Formatting help
Added a new formatting system [#109][]. You can now set the formatter on Apps.
This has also simplified the internals of Apps and Options a bit by separating
most formatting code.
- Added `CLI::Formatter` and `formatter` slot for apps, inherited.
- `FormatterBase` is the minimum required.
- `FormatterLambda` provides for the easy addition of an arbitrary function.
- Added `help_all` support (not added by default).
Changes to the help system (most normal users will not notice this):
- Renamed `single_name` to `get_name(false, false)` (the default).
- The old `get_name()` is now `get_name(false, true)`.
- The old `get_pname()` is now `get_name(true, false)`.
- Removed `help_*` functions.
- Protected function `_has_help_positional` removed.
- `format_help` can now be chained.
- Added getters for the missing parts of options (help no longer uses any
private parts).
- Help flags now use new `short_circuit` property to simplify parsing. [#121][]
New for Config file reading and writing [#121][]:
- Overridable, bidirectional Config.
- ConfigINI provided and used by default.
- Renamed ini to config in many places.
- Has `config_formatter()` and `get_config_formatter()`.
- Dropped prefix argument from `config_to_str`.
- Added `ConfigItem`.
- Added an example of a custom config format using [nlohmann/json][]. [#138][]
Validators are now much more powerful [#118][], all built in validators upgraded
to the new form:
- A subclass of `CLI::Validator` is now also accepted.
- They now can set the type name to things like `PATH` and `INT in [1-4]`.
- Validators can be combined with `&` and `|`.
- Old form simple validators are still accepted.
Other changes:
- Fixing `parse(args)`'s `args` setting and ordering after parse. [#141][]
- Replaced `set_custom_option` with `type_name` and `type_size` instead of
`set_custom_option`. Methods return `this`. [#136][]
- Dropped `set_` on Option's `type_name`, `default_str`, and `default_val`.
[#136][]
- Removed `set_` from App's `failure_message`, `footer`, `callback`, and `name`.
[#136][]
- Fixed support `N<-1` for `type_size`. [#140][]
- Added `->each()` to make adding custom callbacks easier. [#126][]
- Allow empty options `add_option("-n",{})` to be edited later with `each`
[#142][]
- Added filter argument to `get_subcommands`, `get_options`; use empty filter
`{}` to avoid filtering.
- Added `get_groups()` to get groups.
- Better support for manual options with `get_option`, `set_results`, and
`empty`. [#119][]
- `lname` and `sname` have getters, added `const get_parent`. [#120][]
- Using `add_set` will now capture L-values for sets, allowing further
modification. [#113][]
- Dropped duplicate way to run `get_type_name` (`get_typeval`).
- Removed `requires` in favor of `needs` (deprecated in last version). [#112][]
- Const added to argv. [#126][]
Backend and testing changes:
- Internally, `type_name` is now a lambda function; for sets, this reads the set
live. [#116][]
- Cleaner tests without `app.reset()` (and `reset` is now `clear`). [#141][]
- Better CMake policy handling. [#110][]
- Includes are properly sorted. [#120][]
- Testing (only) now uses submodules. [#111][]
[#109]: https://github.com/CLIUtils/CLI11/pull/109
[#110]: https://github.com/CLIUtils/CLI11/pull/110
[#111]: https://github.com/CLIUtils/CLI11/pull/111
[#112]: https://github.com/CLIUtils/CLI11/pull/112
[#113]: https://github.com/CLIUtils/CLI11/issues/113
[#116]: https://github.com/CLIUtils/CLI11/pull/116
[#118]: https://github.com/CLIUtils/CLI11/pull/118
[#119]: https://github.com/CLIUtils/CLI11/pull/119
[#120]: https://github.com/CLIUtils/CLI11/pull/120
[#121]: https://github.com/CLIUtils/CLI11/pull/121
[#126]: https://github.com/CLIUtils/CLI11/pull/126
[#136]: https://github.com/CLIUtils/CLI11/pull/136
[#138]: https://github.com/CLIUtils/CLI11/pull/138
[#140]: https://github.com/CLIUtils/CLI11/pull/140
[#141]: https://github.com/CLIUtils/CLI11/pull/141
[#142]: https://github.com/CLIUtils/CLI11/pull/142
[nlohmann/json]: https://github.com/nlohmann/json
### Version 1.6.1: Platform fixes
This version provides a few fixes for special cases, such as mixing with
`Windows.h` and better defaults for systems like Hunter. The one new feature is
the ability to produce "branded" single file output for providing custom
namespaces or custom macro names.
- Added fix and test for including Windows.h [#145][]
- No longer build single file by default if main project, supports systems stuck
on Python 2.6 [#149][], [#151][]
- Branding support for single file output [#150][]
[#145]: https://github.com/CLIUtils/CLI11/pull/145
[#149]: https://github.com/CLIUtils/CLI11/pull/149
[#150]: https://github.com/CLIUtils/CLI11/pull/150
[#151]: https://github.com/CLIUtils/CLI11/pull/151
### Version 1.6.2: Help-all
This version fixes some formatting bugs with help-all. It also adds fixes for
several warnings, including an experimental optional error on Clang 7. Several
smaller fixes.
- Fixed help-all formatting [#163][]
- Printing help-all on nested command now fixed (App)
- Missing space after help-all restored (Default formatter)
- More detail printed on help all (Default formatter)
- Help-all subcommands get indented with inner blank lines removed (Default
formatter)
- `detail::find_and_replace` added to utilities
- Fixed CMake install as subproject with `CLI11_INSTALL` flag. [#156][]
- Fixed warning about local variable hiding class member with MSVC [#157][]
- Fixed compile error with default settings on Clang 7 and libc++ [#158][]
- Fixed special case of `--help` on subcommands (general fix planned for 1.7)
[#168][]
- Removing an option with links [#179][]
[#156]: https://github.com/CLIUtils/CLI11/issues/156
[#157]: https://github.com/CLIUtils/CLI11/issues/157
[#158]: https://github.com/CLIUtils/CLI11/issues/158
[#163]: https://github.com/CLIUtils/CLI11/pull/163
[#168]: https://github.com/CLIUtils/CLI11/issues/168
[#179]: https://github.com/CLIUtils/CLI11/pull/179
## Version 1.5: Optionals
This version introduced support for optionals, along with clarification and
examples of custom conversion overloads. Enums now have been dropped from the
automatic conversion system, allowing explicit protection for out-of-range ints
(or a completely custom conversion). This version has some internal cleanup and
improved support for the newest compilers. Several bugs were fixed, as well.
Note: This is the final release with `requires`, please switch to `needs`.
- Fix unlimited short options eating two values before checking for positionals
when no space present [#90][]
- Symmetric exclude text when excluding options, exclude can be called multiple
times [#64][]
- Support for `std::optional`, `std::experimental::optional`, and
`boost::optional` added if `__has_include` is supported [#95][]
- All macros/CMake variables now start with `CLI11_` instead of just `CLI_`
[#95][]
- The internal stream was not being cleared before use in some cases. Fixed.
[#95][]
- Using an enum now requires explicit conversion overload [#97][]
- The separator `--` now is removed when it ends unlimited arguments [#100][]
Other, non-user facing changes:
- Added `Macros.hpp` with better C++ mode discovery [#95][]
- Deprecated macros added for all platforms
- C++17 is now tested on supported platforms [#95][]
- Informational printout now added to CTest [#95][]
- Better single file generation [#95][]
- Added support for GTest on MSVC 2017 (but not in C++17 mode, will need next
version of GTest)
- Types now have a specific size, separate from the expected number - cleaner
and more powerful internally [#92][]
- Examples now run as part of testing [#99][]
[#64]: https://github.com/CLIUtils/CLI11/issues/64
[#90]: https://github.com/CLIUtils/CLI11/issues/90
[#92]: https://github.com/CLIUtils/CLI11/issues/92
[#95]: https://github.com/CLIUtils/CLI11/pull/95
[#97]: https://github.com/CLIUtils/CLI11/pull/97
[#99]: https://github.com/CLIUtils/CLI11/pull/99
[#100]: https://github.com/CLIUtils/CLI11/pull/100
### Version 1.5.1: Access
This patch release adds better access to the App programmatically, to assist
with writing custom converters to other formats. It also improves the help
output, and uses a new feature in CLI11 1.5 to fix an old "quirk" in the way
unlimited options and positionals interact.
- Make mixing unlimited positionals and options more intuitive [#102][]
- Add missing getters `get_options` and `get_description` to App [#105][]
- The app name now can be set, and will override the auto name if present
[#105][]
- Add `(REQUIRED)` for required options [#104][]
- Print simple name for Needs/Excludes [#104][]
- Use Needs instead of Requires in help print [#104][]
- Groups now are listed in the original definition order [#106][]
[#102]: https://github.com/CLIUtils/CLI11/issues/102
[#104]: https://github.com/CLIUtils/CLI11/pull/104
[#105]: https://github.com/CLIUtils/CLI11/pull/105
[#106]: https://github.com/CLIUtils/CLI11/pull/106
### Version 1.5.2: LICENSE in single header mode
This is a quick patch release that makes LICENSE part of the single header file,
making it easier to include. Minor cleanup from codacy. No significant code
changes from 1.5.1.
### Version 1.5.3: Compiler compatibility
This version fixes older AppleClang compilers by removing the optimization for
casting. The minimum version of Boost Optional supported has been clarified to
be 1.58. CUDA 7.0 NVCC is now supported.
### Version 1.5.4: Optionals
This version fixes the optional search in the single file version; some macros
were not yet defined when it did the search. You can define the
`CLI11_*_OPTIONAL` macros to 0 if needed to eliminate the search.
## Version 1.4: More feedback
This version adds lots of smaller fixes and additions after the refactor in
version 1.3. More ways to download and use CLI11 in CMake have been added. INI
files have improved support.
- Lexical cast is now more strict than before [#68][] and fails on overflow
[#84][]
- Added `get_parent()` to access the parent from a subcommand
- Added `ExistingPath` validator [#73][]
- `app.allow_ini_extras()` added to allow extras in INI files [#70][]
- Multiline INI comments now supported
- Descriptions can now be written with `config_to_str` [#66][]
- Double printing of error message fixed [#77][]
- Renamed `requires` to `needs` to avoid C++20 keyword [#75][], [#82][]
- MakeSingleHeader now works if outside of git [#78][]
- Adding install support for CMake [#79][], improved support for `find_package`
[#83][], [#84][]
- Added support for Conan.io [#83][]
[#70]: https://github.com/CLIUtils/CLI11/issues/70
[#75]: https://github.com/CLIUtils/CLI11/issues/75
[#84]: https://github.com/CLIUtils/CLI11/pull/84
[#83]: https://github.com/CLIUtils/CLI11/pull/83
[#82]: https://github.com/CLIUtils/CLI11/pull/82
[#79]: https://github.com/CLIUtils/CLI11/pull/79
[#78]: https://github.com/CLIUtils/CLI11/pull/78
[#77]: https://github.com/CLIUtils/CLI11/pull/77
[#73]: https://github.com/CLIUtils/CLI11/pull/73
[#68]: https://github.com/CLIUtils/CLI11/pull/68
[#66]: https://github.com/CLIUtils/CLI11/pull/66
## Version 1.3: Refactor
This version focused on refactoring several key systems to ensure correct
behavior in the interaction of different settings. Most caveats about features
only working on the main App have been addressed, and extra arguments have been
reworked. Inheritance of defaults makes configuring CLI11 much easier without
having to subclass. Policies add new ways to handle multiple arguments to match
your favorite CLI programs. Error messages and help messages are better and more
flexible. Several bugs and odd behaviors in the parser have been fixed.
- Added a version macro, `CLI11_VERSION`, along with `*_MAJOR`, `*_MINOR`, and
`*_PATCH`, for programmatic access to the version.
- Reworked the way defaults are set and inherited; explicit control given to
user with `->option_defaults()`
[#48](https://github.com/CLIUtils/CLI11/pull/48)
- Hidden options now are based on an empty group name, instead of special
"hidden" keyword [#48](https://github.com/CLIUtils/CLI11/pull/48)
- `parse` no longer returns (so `CLI11_PARSE` is always usable)
[#37](https://github.com/CLIUtils/CLI11/pull/37)
- Added `remaining()` and `remaining_size()`
[#37](https://github.com/CLIUtils/CLI11/pull/37)
- `allow_extras` and `prefix_command` are now valid on subcommands
[#37](https://github.com/CLIUtils/CLI11/pull/37)
- Added `take_last` to only take last value passed
[#40](https://github.com/CLIUtils/CLI11/pull/40)
- Added `multi_option_policy` and shortcuts to provide more control than just a
take last policy [#59](https://github.com/CLIUtils/CLI11/pull/59)
- More detailed error messages in a few cases
[#41](https://github.com/CLIUtils/CLI11/pull/41)
- Footers can be added to help [#42](https://github.com/CLIUtils/CLI11/pull/42)
- Help flags are easier to customize
[#43](https://github.com/CLIUtils/CLI11/pull/43)
- Subcommand now support groups [#46](https://github.com/CLIUtils/CLI11/pull/46)
- `CLI::RuntimeError` added, for easy exit with error codes
[#45](https://github.com/CLIUtils/CLI11/pull/45)
- The clang-format script is now no longer "hidden"
[#48](https://github.com/CLIUtils/CLI11/pull/48)
- The order is now preserved for subcommands (list and callbacks)
[#49](https://github.com/CLIUtils/CLI11/pull/49)
- Tests now run individually, utilizing CMake 3.10 additions if possible
[#50](https://github.com/CLIUtils/CLI11/pull/50)
- Failure messages are now customizable, with a shorter default
[#52](https://github.com/CLIUtils/CLI11/pull/52)
- Some improvements to error codes
[#53](https://github.com/CLIUtils/CLI11/pull/53)
- `require_subcommand` now offers a two-argument form and negative values on the
one-argument form are more useful
[#51](https://github.com/CLIUtils/CLI11/pull/51)
- Subcommands no longer match after the max required number is obtained
[#51](https://github.com/CLIUtils/CLI11/pull/51)
- Unlimited options no longer prioritize over remaining/unlimited positionals
[#51](https://github.com/CLIUtils/CLI11/pull/51)
- Added `->transform` which modifies the string parsed
[#54](https://github.com/CLIUtils/CLI11/pull/54)
- Changed of API in validators to `void(std::string &)` (const for users),
throwing providing nicer errors
[#54](https://github.com/CLIUtils/CLI11/pull/54)
- Added `CLI::ArgumentMismatch` [#56](https://github.com/CLIUtils/CLI11/pull/56)
and fixed missing failure if one arg expected
[#55](https://github.com/CLIUtils/CLI11/issues/55)
- Support for minimum unlimited expected arguments
[#56](https://github.com/CLIUtils/CLI11/pull/56)
- Single internal arg parse function
[#56](https://github.com/CLIUtils/CLI11/pull/56)
- Allow options to be disabled from INI file, rename `add_config` to
`set_config` [#60](https://github.com/CLIUtils/CLI11/pull/60)
> ### Converting from CLI11 1.2
>
> - `app.parse` no longer returns a vector. Instead, use `app.remaining(true)`.
> - `"hidden"` is no longer a special group name, instead use `""`
> - Validators API has changed to return an error string; use `.empty()` to get
> the old bool back
> - Use `.set_help_flag` instead of accessing the help pointer directly
> (discouraged, but not removed yet)
> - `add_config` has been renamed to `set_config`
> - Errors thrown in some cases are slightly more specific
## Version 1.2: Stability
This release focuses on making CLI11 behave properly in corner cases, and with
config files on the command line. This includes fixes for a variety of reported
issues. A few features were added to make life easier, as well; such as a new
flag callback and a macro for the parse command.
- Added functional form of flag
[#33](https://github.com/CLIUtils/CLI11/pull/33), automatic on C++14
- Fixed Config file search if passed on command line
[#30](https://github.com/CLIUtils/CLI11/issues/30)
- Added `CLI11_PARSE(app, argc, argv)` macro for simple parse commands (does not
support returning arg)
- The name string can now contain spaces around commas
[#29](https://github.com/CLIUtils/CLI11/pull/29)
- `set_default_str` now only sets string, and `set_default_val` will evaluate
the default string given [#26](https://github.com/CLIUtils/CLI11/issues/26)
- Required positionals now take priority over subcommands
[#23](https://github.com/CLIUtils/CLI11/issues/23)
- Extra requirements enforced by Travis
## Version 1.1: Feedback
This release incorporates feedback from the release announcement. The examples
are slowly being expanded, some corner cases improved, and some new
functionality for tricky parsing situations.
- Added simple support for enumerations, allow non-printable objects
[#12](https://github.com/CLIUtils/CLI11/issues/12)
- Added `app.parse_order()` with original parse order
([#13](https://github.com/CLIUtils/CLI11/issues/13),
[#16](https://github.com/CLIUtils/CLI11/pull/16))
- Added `prefix_command()`, which is like `allow_extras` but instantly stops and
returns. ([#8](https://github.com/CLIUtils/CLI11/issues/8),
[#17](https://github.com/CLIUtils/CLI11/pull/17))
- Removed Windows warning ([#10](https://github.com/CLIUtils/CLI11/issues/10),
[#20](https://github.com/CLIUtils/CLI11/pull/20))
- Some improvements to CMake, detect Python and no dependencies on Python 2
(like Python 3) ([#18](https://github.com/CLIUtils/CLI11/issues/18),
[#21](https://github.com/CLIUtils/CLI11/pull/21))
## Version 1.0: Official release
This is the first stable release for CLI11. Future releases will try to remain
backward compatible and will follow semantic versioning if possible. There were
a few small changes since version 0.9:
- Cleanup using `clang-tidy` and `clang-format`
- Small improvements to Timers, easier to subclass Error
- Move to 3-Clause BSD license
## Version 0.9: Polish
This release focused on cleaning up the most exotic compiler warnings, fixing a
few oddities of the config parser, and added a more natural method to check
subcommands.
- Better CMake named target (CLI11)
- More warnings added, fixed
- Ini output now includes `=false` when `default_also` is true
- Ini no longer lists the help pointer
- Added test for inclusion in multiple files and linking, fixed issues (rarely
needed for CLI, but nice for tools)
- Support for complex numbers
- Subcommands now test true/false directly or with `->parsed()`, cleaner parse
## Version 0.8: CLIUtils
This release moved the repository to the CLIUtils main organization.
- Moved to CLIUtils on GitHub
- Fixed docs build and a few links
## Version 0.7: Code coverage 100%
Lots of small bugs fixed when adding code coverage, better in edge cases. Much
more powerful ini support.
- Allow comments in ini files (lines starting with `;`)
- Ini files support flags, vectors, subcommands
- Added CodeCov code coverage reports
- Lots of small bugfixes related to adding tests to increase coverage to 100%
- Error handling now uses scoped enum in errors
- Reparsing rules changed a little to accommodate Ini files. Callbacks are now
called when parsing INI, and reset any time results are added.
- Adding extra utilities in full version only, `Timer` (not needed for parsing,
but useful for general CLI applications).
- Better support for custom `add_options` like functions.
## Version 0.6: Cleanup
Lots of cleanup and docs additions made it into this release. Parsing is simpler
and more robust; fall through option added and works as expected; much more
consistent variable names internally.
- Simplified parsing to use `vector<string>` only
- Fixed fallthrough, made it optional as well (default: off): `.fallthrough()`.
- Added string versions of `->requires()` and `->excludes()` for consistency.
- Renamed protected members for internal consistency, grouped docs.
- Added the ability to add a number to `.require_subcommand()`.
## Version 0.5: Windows support
- Allow `Hidden` options.
- Throw `OptionAlreadyAdded` errors for matching subcommands or options, with
ignore-case included, tests
- `->ignore_case()` added to subcommands, options, and `add_set_ignore_case`.
Subcommands inherit setting from parent App on creation.
- Subcommands now can be "chained", that is, left over arguments can now include
subcommands that then get parsed. Subcommands are now a list
(`get_subcommands`). Added `got_subcommand(App_or_name)` to check for
subcommands.
- Added `.allow_extras()` to disable error on failure. Parse returns a vector of
leftover options. Renamed error to `ExtrasError`, and now triggers on extra
options too.
- Added `require_subcommand` to `App`, to simplify forcing subcommands. Do
**not** do `add_subcommand()->require_subcommand`, since that is the
subcommand, not the main `App`.
- Added printout of ini file text given parsed options, skips flags.
- Support for quotes and spaces in ini files
- Fixes to allow support for Windows (added Appveyor) (Uses `-`, not `/` syntax)
## Version 0.4: Ini support
- Updates to help print
- Removed `run`, please use `parse` unless you subclass and add it
- Supports ini files mixed with command line, tested
- Added Range for further Plumbum compatibility
- Added function to print out ini file
## Version 0.3: Plumbum compatibility
- Added `->requires`, `->excludes`, and `->envname` from
[Plumbum](http://plumbum.readthedocs.io/en/latest/)
- Supports `->mandatory` from Plumbum
- More tests for help strings, improvements in formatting
- Support type and set syntax in positionals help strings
- Added help groups, with `->group("name")` syntax
- Added initial support for ini file reading with `add_config` option.
- Supports GCC 4.7 again
- Clang 3.5 now required for tests due to googlemock usage, 3.4 should still
work otherwise
- Changes `setup` for an explicit help bool in constructor/`add_subcommand`
## Version 0.2: Leaner and meaner
- Moved to simpler syntax, where `Option` pointers are returned and operated on
- Removed `make_` style options
- Simplified Validators, now only requires `->check(function)`
- Removed Combiners
- Fixed pointers to Options, stored in `unique_ptr` now
- Added `Option_p` and `App_p`, mostly for internal use
- Startup sequence, including help flag, can be modified by subclasses
## Version 0.1: First release
First release before major cleanup. Still has make syntax and combiners; very
clever syntax but not the best or most commonly expected way to work.

View File

@@ -0,0 +1 @@
CLI11 provides all the features you expect in a powerful command line parser, with a beautiful, minimal syntax and no dependencies beyond C++11. It is header only, and comes in a single file form for easy inclusion in projects. It is easy to use for small projects, but powerful enough for complex command line projects, and can be customized for frameworks.

69
libs/CLI11/CLI11.hpp.in Normal file
View File

@@ -0,0 +1,69 @@
// CLI11: Version {version}
// Originally designed by Henry Schreiner
// https://github.com/CLIUtils/CLI11
//
// This is a standalone header file generated by MakeSingleHeader.py in CLI11/scripts
// from: {git}
//
// CLI11 {version} Copyright (c) 2017-2022 University of Cincinnati, developed by Henry
// Schreiner under NSF AWARD 1414736. All rights reserved.
//
// Redistribution and use in source and binary forms of CLI11, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
// Standard combined includes:
{public_includes}
{version_hpp}
{macros_hpp}
{validators_hpp_filesystem}
namespace {namespace} {{
{string_tools_hpp}
{error_hpp}
{type_tools_hpp}
{split_hpp}
{config_fwd_hpp}
{validators_hpp}
{formatter_fwd_hpp}
{option_hpp}
{app_hpp}
{config_hpp}
{formatter_hpp}
}} // namespace {namespace}

331
libs/CLI11/CMakeLists.txt Normal file
View File

@@ -0,0 +1,331 @@
cmake_minimum_required(VERSION 3.4)
# Note: this is a header only library. If you have an older CMake than 3.4,
# just add the CLI11/include directory and that's all you need to do.
# Make sure users don't get warnings on a tested (3.4 to 3.22) version
# of CMake. For most of the policies, the new version is better (hence the change).
# We don't use the 3.4...3.21 syntax because of a bug in an older MSVC's
# built-in and modified CMake 3.11
if(${CMAKE_VERSION} VERSION_LESS 3.22)
cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION})
else()
cmake_policy(VERSION 3.22)
endif()
set(VERSION_REGEX "#define CLI11_VERSION[ \t]+\"(.+)\"")
# Read in the line containing the version
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/include/CLI/Version.hpp" VERSION_STRING
REGEX ${VERSION_REGEX})
# Pick out just the version
string(REGEX REPLACE ${VERSION_REGEX} "\\1" VERSION_STRING "${VERSION_STRING}")
# Add the project
project(
CLI11
LANGUAGES CXX
VERSION ${VERSION_STRING})
# Print the version number of CMake if this is the main project
if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME)
message(STATUS "CMake ${CMAKE_VERSION}")
find_package(Doxygen)
if(CMAKE_VERSION VERSION_LESS 3.10)
message(STATUS "CMake 3.10+ adds Doxygen support. Update CMake to build documentation")
elseif(NOT Doxygen_FOUND)
message(STATUS "Doxygen not found, building docs has been disabled")
endif()
include(CTest)
else()
if(NOT DEFINED BUILD_TESTING)
set(BUILD_TESTING OFF)
endif()
endif()
include(CMakeDependentOption)
include(GNUInstallDirs)
if(NOT CMAKE_VERSION VERSION_LESS 3.11)
include(FetchContent)
endif()
list(APPEND force-libcxx "CMAKE_CXX_COMPILER_ID STREQUAL \"Clang\"")
list(APPEND force-libcxx "CMAKE_SYSTEM_NAME STREQUAL \"Linux\"")
list(APPEND force-libcxx "CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME")
list(APPEND build-docs "CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME")
list(APPEND build-docs "NOT CMAKE_VERSION VERSION_LESS 3.11")
list(APPEND build-docs "Doxygen_FOUND")
# Necessary to support paths with spaces, see #457
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/docs")
set(docs_EXIST TRUE)
else()
set(docs_EXIST FALSE)
endif()
list(APPEND build-docs "docs_EXIST")
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/examples")
set(examples_EXIST TRUE)
else()
set(examples_EXIST FALSE)
endif()
option(CLI11_WARNINGS_AS_ERRORS "Turn all warnings into errors (for CI)")
option(CLI11_SINGLE_FILE "Generate a single header file")
cmake_dependent_option(CLI11_SANITIZERS "Download the sanitizers CMake config" OFF
"NOT CMAKE_VERSION VERSION_LESS 3.11" OFF)
cmake_dependent_option(CLI11_BUILD_DOCS "Build CLI11 documentation" ON "${build-docs}" OFF)
cmake_dependent_option(CLI11_BUILD_TESTS "Build CLI11 tests" ON
"BUILD_TESTING;CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME" OFF)
cmake_dependent_option(CLI11_BUILD_EXAMPLES "Build CLI11 examples" ON
"CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME;${examples_EXIST}" OFF)
cmake_dependent_option(CLI11_BUILD_EXAMPLES_JSON "Build CLI11 json example" OFF
"CLI11_BUILD_EXAMPLES;NOT CMAKE_VERSION VERSION_LESS 3.11" OFF)
cmake_dependent_option(CLI11_SINGLE_FILE_TESTS "Duplicate all the tests for a single file build"
OFF "BUILD_TESTING;CLI11_SINGLE_FILE" OFF)
cmake_dependent_option(CLI11_INSTALL "Install the CLI11 folder to include during install process"
ON "CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME" OFF)
cmake_dependent_option(
CLI11_FORCE_LIBCXX "Force clang to use libc++ instead of libstdc++ (Linux only)" OFF
"${force-libcxx}" OFF)
cmake_dependent_option(
CLI11_CUDA_TESTS "Build the tests with NVCC to check for warnings there - requires CMake 3.9+"
OFF "CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME" OFF)
cmake_dependent_option(
CLI11_CLANG_TIDY "Look for and use Clang-Tidy" OFF
"CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME;NOT CMAKE_VERSION VERSION_LESS 3.6" OFF)
set(CLI11_CLANG_TIDY_OPTIONS
""
CACHE STRING "Clang tidy options, such as -fix, semicolon separated")
if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND NOT DEFINED CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 11)
endif()
if(NOT DEFINED CMAKE_CXX_EXTENSIONS)
set(CMAKE_CXX_EXTENSIONS OFF)
endif()
if(NOT DEFINED CMAKE_CXX_STANDARD_REQUIRED)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
endif()
# Allow IDE's to group targets into folders
if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME)
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
endif()
# Special target that adds warnings. Is not exported.
add_library(CLI11_warnings INTERFACE)
set(unix-warnings -Wall -Wextra -pedantic -Wshadow -Wsign-conversion -Wswitch-enum)
# Buggy in GCC 4.8
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9)
list(APPEND unix-warnings -Weffc++)
endif()
target_compile_options(
CLI11_warnings
INTERFACE $<$<BOOL:${CLI11_FORCE_LIBCXX}>:-stdlib=libc++>
$<$<CXX_COMPILER_ID:MSVC>:/W4
$<$<BOOL:${CLI11_WARNINGS_AS_ERRORS}>:/WX>>
$<$<NOT:$<CXX_COMPILER_ID:MSVC>>:${unix-warnings}
$<$<BOOL:${CLI11_WARNINGS_AS_ERRORS}>:-Werror>>)
if(NOT CMAKE_VERSION VERSION_LESS 3.13)
target_link_options(CLI11_warnings INTERFACE $<$<BOOL:${CLI11_FORCE_LIBCXX}>:-stdlib=libc++>)
endif()
# Allow IDE's to group targets into folders
add_library(CLI11 INTERFACE)
add_library(CLI11::CLI11 ALIAS CLI11) # for add_subdirectory calls
# Duplicated because CMake adds the current source dir if you don't.
target_include_directories(CLI11 INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>)
if(CMAKE_VERSION VERSION_LESS 3.8)
# This might not be a complete list
target_compile_features(
CLI11
INTERFACE cxx_lambdas
cxx_nullptr
cxx_override
cxx_range_for
cxx_right_angle_brackets
cxx_strong_enums
cxx_constexpr
cxx_auto_type)
else()
target_compile_features(CLI11 INTERFACE cxx_std_11)
endif()
# To see in IDE, headers must be listed for target
set(header-patterns "${PROJECT_SOURCE_DIR}/include/CLI/*")
if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND NOT CMAKE_VERSION VERSION_LESS 3.12)
list(INSERT header-patterns 0 CONFIGURE_DEPENDS)
endif()
file(GLOB CLI11_headers ${header-patterns})
# Allow tests to be run on CUDA
if(CLI11_CUDA_TESTS)
enable_language(CUDA)
# Print out warning and error numbers
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Xcudafe --display_error_number")
endif()
# Prepare Clang-Tidy
if(CLI11_CLANG_TIDY)
find_program(
CLANG_TIDY_EXE
NAMES "clang-tidy"
DOC "Path to clang-tidy executable" REQUIRED)
set(DO_CLANG_TIDY "${CLANG_TIDY_EXE}" ${CLI11_CLANG_TIDY_OPTIONS})
endif()
# This folder should be installed
if(CLI11_INSTALL)
install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
# Make an export target
install(TARGETS CLI11 EXPORT CLI11Targets)
# Use find_package on the installed package
# Since we have no custom code, we can directly write this
# to Config.cmake (otherwise we'd have a custom config and would
# import Targets.cmake
# Add the version in a CMake readable way
configure_file("cmake/CLI11ConfigVersion.cmake.in" "CLI11ConfigVersion.cmake" @ONLY)
# Make version available in the install
install(FILES "${PROJECT_BINARY_DIR}/CLI11ConfigVersion.cmake"
DESTINATION "${CMAKE_INSTALL_DATADIR}/cmake/CLI11")
# Install the export target as a file
install(
EXPORT CLI11Targets
FILE CLI11Config.cmake
NAMESPACE CLI11::
DESTINATION "${CMAKE_INSTALL_DATADIR}/cmake/CLI11")
# Use find_package on the installed package
export(
TARGETS CLI11
NAMESPACE CLI11::
FILE CLI11Targets.cmake)
include(cmake/CLI11GeneratePkgConfig.cmake)
# Register in the user cmake package registry
export(PACKAGE CLI11)
endif()
if(CLI11_SINGLE_FILE)
# Single file test
if(CMAKE_VERSION VERSION_LESS 3.12)
find_package(PythonInterp REQUIRED)
add_executable(Python::Interpreter IMPORTED)
set_target_properties(Python::Interpreter PROPERTIES IMPORTED_LOCATION "${PYTHON_EXECUTABLE}"
VERSION "${PYTHON_VERSION_STRING}")
else()
find_package(
Python
COMPONENTS Interpreter
REQUIRED)
endif()
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/include")
add_custom_command(
OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/include/CLI11.hpp"
COMMAND
Python::Interpreter "${CMAKE_CURRENT_SOURCE_DIR}/scripts/MakeSingleHeader.py"
${CLI11_headers} --main "${CMAKE_CURRENT_SOURCE_DIR}/CLI11.hpp.in" --output
"${CMAKE_CURRENT_BINARY_DIR}/include/CLI11.hpp" --version "${CLI11_VERSION}"
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/include/CLI/CLI.hpp" ${CLI11_headers})
add_custom_target(CLI11-generate-single-file ALL
DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/include/CLI11.hpp")
set_property(TARGET CLI11-generate-single-file PROPERTY FOLDER "Scripts")
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/include/CLI11.hpp" DESTINATION include)
add_library(CLI11_SINGLE INTERFACE)
target_link_libraries(CLI11_SINGLE INTERFACE CLI11)
add_dependencies(CLI11_SINGLE CLI11-generate-single-file)
target_compile_definitions(CLI11_SINGLE INTERFACE -DCLI11_SINGLE_FILE)
target_include_directories(
CLI11_SINGLE INTERFACE $<BUILD_INTERFACE:${PROJECT_BINARY_DIR}/include/>
$<INSTALL_INTERFACE:include>)
endif()
if(CLI11_BUILD_TESTS)
include(CTest)
add_subdirectory(tests)
endif()
if(CLI11_BUILD_EXAMPLES)
add_subdirectory(examples)
endif()
if(CLI11_BUILD_DOCS)
add_subdirectory(docs)
endif()
# From a build system, this might not be included.
if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/book")
add_subdirectory(book)
endif()
# Packaging support
set(CPACK_PACKAGE_VENDOR "github.com/CLIUtils/CLI11")
set(CPACK_PACKAGE_CONTACT "https://${CPACK_PACKAGE_VENDOR}")
set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) # Automatic in CMake 3.12+
set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) # Automatic in CMake 3.12+
set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) # Automatic in CMake 3.12+
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Command line parser with simple and intuitive interface")
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/CLI11.CPack.Description.txt")
set(CPACK_SOURCE_GENERATOR "TGZ;ZIP")
# CPack collects *everything* except what's listed here.
set(CPACK_SOURCE_IGNORE_FILES
/.git
/dist
/.*build.*
/\\\\.DS_Store
/.*\\\\.egg-info
/var
/azure-pipelines.yml
/.ci
/docs
/examples
/test_package
/book
/.travis.yml
.swp
/.all-contributorsrc
/.appveyor.yml
/.pre-commit.*yaml)
set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "all")
set(CPACK_DEBIAN_COMPRESSION_TYPE "xz")
set(CPACK_DEBIAN_PACKAGE_NAME "libcli11-dev")
include(CPack)

13
libs/CLI11/CPPLINT.cfg Normal file
View File

@@ -0,0 +1,13 @@
set noparent
linelength=120 # As in .clang-format
# Unused filters
filter=-build/c++11 # Reports e.g. chrono and thread, which overlap with Chromium's API. Not applicable to general C++ projects.
filter=-build/include_order # Requires unusual include order that encourages creating not self-contained headers
filter=-readability/nolint # Conflicts with clang-tidy
filter=-readability/check # Catch uses CHECK(a == b) (Tests only)
filter=-build/namespaces # Currently using it for one test (Tests only)
filter=-runtime/references # Requires fundamental change of API, don't see need for this
filter=-whitespace/blank_line # Unnecessarily strict with blank lines that otherwise help with readability
filter=-whitespace/indent # Requires strange 3-space indent of private/protected/public markers
filter=-whitespace/parens,-whitespace/braces # Conflict with clang-format

25
libs/CLI11/LICENSE Normal file
View File

@@ -0,0 +1,25 @@
CLI11 2.2 Copyright (c) 2017-2022 University of Cincinnati, developed by Henry
Schreiner under NSF AWARD 1414736. All rights reserved.
Redistribution and use in source and binary forms of CLI11, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

1767
libs/CLI11/README.md Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,143 @@
# C/C++ with GCC
# Build your C/C++ project with GCC using make.
# Add steps that publish test results, save build artifacts, deploy, and more:
# https://docs.microsoft.com/azure/devops/pipelines/apps/c-cpp/gcc
trigger:
- main
- "v*"
pr:
- main
- "v*"
variables:
cli11.single: ON
cli11.std: 14
cli11.build_type: Debug
cli11.options: -DCLI11_EXAMPLES_JSON=ON
CMAKE_BUILD_PARALLEL_LEVEL: 4
jobs:
- job: ClangTidy
variables:
CXX_FLAGS: >
-Werror -Wcast-align -Wfloat-equal -Wimplicit-atomic-properties
-Wmissing-declarations -Woverlength-strings -Wshadow
-Wstrict-selector-match -Wundeclared-selector -Wunreachable-code
-std=c++11
cli11.options: -DCLI11_CLANG_TIDY=ON -DCLI11_CLANG_TIDY_OPTIONS="-fix"
cli11.std: 11
cli11.single: OFF
CMAKE_BUILD_PARALLEL_LEVEL: 1
pool:
vmImage: "ubuntu-latest"
container: silkeh/clang:8
steps:
- template: .ci/azure-cmake.yml
- template: .ci/azure-build.yml
- script: git diff --exit-code --color
displayName: Check tidy
- job: CppLint
pool:
vmImage: "ubuntu-latest"
container: sharaku/cpplint:latest
steps:
- bash: cpplint --counting=detailed --recursive examples include/CLI tests
displayName: Checking against google style guide
# TODO: Fix macOS error and windows warning in c++17 mode
- job: Native
strategy:
matrix:
Linux14:
vmImage: "ubuntu-latest"
macOS17:
vmImage: "macOS-latest"
cli11.std: 17
macOS11:
vmImage: "macOS-latest"
cli11.std: 11
Windows17:
vmImage: "vs2017-win2016"
cli11.std: 17
Windows11:
vmImage: "vs2017-win2016"
cli11.std: 11
Windowslatest:
vmImage: "windows-2019"
cli11.std: 20
cli11.options: -DCMAKE_CXX_FLAGS="/std:c++latest /EHsc"
Linux17nortti:
vmImage: "ubuntu-latest"
cli11.std: 17
cli11.options: -DCMAKE_CXX_FLAGS="-fno-rtti"
pool:
vmImage: $(vmImage)
steps:
- template: .ci/azure-build.yml
- template: .ci/azure-test.yml
- job: Meson
pool:
vmImage: "ubuntu-latest"
steps:
- task: UsePythonVersion@0
inputs:
versionSpec: "3.7"
- script: python3 -m pip install meson ninja
displayName: install meson
- script: mkdir tests/mesonTest/subprojects
displayName: generate test directories
- script: ln -s "$(pwd)" tests/mesonTest/subprojects/CLI11
displayName: generate CLI11 symlink
- script: meson build
displayName: Run meson to generate build
workingDirectory: tests/mesonTest
- script: ninja -C tests/mesonTest/build
displayName: Build with Ninja
- script: ./tests/mesonTest/build/main --help
displayName: Run help
- job: Docker
variables:
cli11.single: OFF
pool:
vmImage: "ubuntu-latest"
strategy:
matrix:
gcc9:
containerImage: gcc:9
cli11.std: 17
cli11.options: -DCMAKE_CXX_FLAGS="-Wstrict-overflow=5"
gcc11:
containerImage: gcc:11
cli11.std: 20
gcc8:
containerImage: gcc:8
cli11.std: 17
gcc4.8:
containerImage: gcc:4.8
cli11.std: 11
cli11.options:
clang3.4:
containerImage: silkeh/clang:3.4
cli11.std: 11
clang8:
containerImage: silkeh/clang:8
cli11.std: 14
cli11.options: -DCLI11_FORCE_LIBCXX=ON
clang8_17:
containerImage: silkeh/clang:8
cli11.std: 17
cli11.options: -DCLI11_FORCE_LIBCXX=ON
clang10_20:
containerImage: silkeh/clang:10
cli11.std: 20
cli11.options: -DCLI11_FORCE_LIBCXX=ON -DCMAKE_CXX_FLAGS=-std=c++20
container: $[ variables['containerImage'] ]
steps:
- template: .ci/azure-cmake.yml
- template: .ci/azure-build.yml
- template: .ci/azure-test.yml

20
libs/CLI11/book/.gitignore vendored Normal file
View File

@@ -0,0 +1,20 @@
# Node rules:
## Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
## Dependency directory
## Commenting this out is preferred by some people, see
## https://docs.npmjs.com/misc/faq#should-i-check-my-node_modules-folder-into-git
node_modules
# Book build output
_book
# eBook build output
*.epub
*.mobi
*.pdf
a.out
*build*

View File

@@ -0,0 +1,7 @@
set(book_sources README.md SUMMARY.md)
file(
GLOB book_chapters
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
chapters/*.md)
add_custom_target(cli_book SOURCES ${book_sources} ${book_chapters})

94
libs/CLI11/book/README.md Normal file
View File

@@ -0,0 +1,94 @@
# CLI11: An introduction
This gitbook is designed to provide an introduction to using the CLI11 library
to write your own command line programs. The library is designed to be clean,
intuitive, but powerful. There are no requirements beyond C++11 support (and
even `<regex>` support not required). It works on Mac, Linux, and Windows, and
has 100% test coverage on all three systems. You can simply drop in a single
header file (`CLI11.hpp` available in [releases][]) to use CLI11 in your own
application. Other ways to integrate it into a build system are listed in the
[README][].
The library was inspired the Python libraries [Plumbum][] and [Click][], and
incorporates many of their user friendly features. The library is extensively
documented, with a [friendly introduction][readme], this tutorial book, and more
technical [API docs][].
> Feel free to contribute to [this documentation here][cli11tutorial] if
> something can be improved!
The syntax is simple and scales from a basic application to a massive physics
analysis with multiple models and many parameters and switches. For example,
this is a simple program that has an optional parameter that defaults to 0:
```term
gitbook $ ./a.out
Parameter value: 0
gitbook $ ./a.out -p 4
Parameter value: 4
gitbook $ ./a.out --help
App description
Usage: ./a.out [OPTIONS]
Options:
-h,--help Print this help message and exit
-p INT Parameter
```
Like any good command line application, help is provided. This program can be
implemented in 10 lines:
[include](code/intro.cpp)
[Source code](https://github.com/CLIUtils/CLI11/blob/main/book/code/intro.cpp)
Unlike some other libraries, this is enough to exit correctly and cleanly if
help is requested or if incorrect arguments are passed. You can try this example
out for yourself. To compile with GCC:
```term
gitbook:examples $ c++ -std=c++11 intro.cpp
```
Much more complicated options are handled elegantly:
```cpp
std::string file;
app.add_option("-f,--file", file, "Require an existing file")
->required()
->check(CLI::ExistingFile);
```
You can use any valid type; the above example could have used a
`boost::file_system` file instead of a `std::string`. The value is a real value
and does not require any special lookups to access. You do not have to risk
typos by repeating the values after parsing like some libraries require. The
library also handles positional arguments, flags, fixed or unlimited repeating
options, interdependent options, flags, custom validators, help groups, and
more.
You can use subcommands, as well. Subcommands support callback lambda functions
when parsed, or they can be checked later. You can infinitely nest subcommands,
and each is a full `App` instance, supporting everything listed above.
Reading/producing `.ini` files for configuration is also supported, as is using
environment variables as input. The base `App` can be subclassed and customized
for use in a toolkit (like [GooFit][]). All the standard shell idioms, like
`--`, work as well.
CLI11 was developed at the [University of Cincinnati][] in support of the
[GooFit][] library under [NSF Award 1414736][nsf 1414736]. It was featured in a
[DIANA/HEP][] meeting at CERN. Please give it a try! Feedback is always welcome.
[goofit]: https://github.com/GooFit/GooFit
[diana/hep]: https://diana-hep.org
[cli11tutorial]: https://cliutils.github.io/CLI11/book
[releases]: https://github.com/CLIUtils/CLI11/releases
[api docs]: https://cliutils.github.io/CLI11
[readme]: https://github.com/CLIUtils/CLI11/blob/main/README.md
[nsf 1414736]: https://nsf.gov/awardsearch/showAward?AWD_ID=1414736
[university of cincinnati]: https://www.uc.edu
[plumbum]: https://plumbum.readthedocs.io/en/latest/
[click]: https://click.palletsprojects.com

View File

@@ -0,0 +1,15 @@
# Summary
- [Introduction](/README.md)
- [Installation](/chapters/installation.md)
- [Basics](/chapters/basics.md)
- [Flags](/chapters/flags.md)
- [Options](/chapters/options.md)
- [Validators](/chapters/validators.md)
- [Subcommands and the App](/chapters/subcommands.md)
- [An advanced example](/chapters/an-advanced-example.md)
- [Configuration files](/chapters/config.md)
- [Formatting help output](/chapters/formatting.md)
- [Toolkits](/chapters/toolkits.md)
- [Advanced topics](/chapters/advanced-topics.md)
- [Internals](/chapters/internals.md)

12
libs/CLI11/book/book.json Normal file
View File

@@ -0,0 +1,12 @@
{
"title": "CLI11 Tutorial",
"description": "A set of examples and detailed information about CLI11",
"author": "Henry Schreiner",
"plugins": ["include-codeblock", "term", "hints"],
"pluginsConfig": {
"include-codeblock": {
"unindent": true,
"fixlang": true
}
}
}

View File

@@ -0,0 +1,152 @@
# Advanced topics
## Environment variables
Environment variables can be used to fill in the value of an option:
```cpp
std::string opt;
app.add_option("--my_option", opt)->envname("MY_OPTION");
```
If not given on the command line, the environment variable will be checked and
read from if it exists. All the standard tools, like default and required, work
as expected. If passed on the command line, this will ignore the environment
variable.
## Needs/excludes
You can set a network of requirements. For example, if flag a needs flag b but
cannot be given with flag c, that would be:
```cpp
auto a = app.add_flag("-a");
auto b = app.add_flag("-b");
auto c = app.add_flag("-c");
a->needs(b);
a->excludes(c);
```
CLI11 will make sure your network of requirements makes sense, and will throw an
error immediately if it does not.
## Custom option callbacks
You can make a completely generic option with a custom callback. For example, if
you wanted to add a complex number (already exists, so please don't actually do
this):
```cpp
CLI::Option *
add_option(CLI::App &app, std::string name, cx &variable, std::string description = "", bool defaulted = false) {
CLI::callback_t fun = [&variable](CLI::results_t res) {
double x, y;
bool worked = CLI::detail::lexical_cast(res[0], x) && CLI::detail::lexical_cast(res[1], y);
if(worked)
variable = cx(x, y);
return worked;
};
CLI::Option *opt = app.add_option(name, fun, description, defaulted);
opt->set_custom_option("COMPLEX", 2);
if(defaulted) {
std::stringstream out;
out << variable;
opt->set_default_str(out.str());
}
return opt;
}
```
Then you could use it like this:
```cpp
std::complex<double> comp{0, 0};
add_option(app, "-c,--complex", comp);
```
## Custom converters
You can add your own converters to allow CLI11 to accept more option types in
the standard calls. These can only be used for "single" size options (so
complex, vector, etc. are a separate topic). If you set up a custom
`istringstream& operator <<` overload before include CLI11, you can support
different conversions. If you place this in the CLI namespace, you can even keep
this from affecting the rest of your code. Here's how you could add
`boost::optional` for a compiler that does not have `__has_include`:
```cpp
// CLI11 already does this if __has_include is defined
#ifndef __has_include
#include <boost/optional.hpp>
// Use CLI namespace to avoid the conversion leaking into your other code
namespace CLI {
template <typename T> std::istringstream &operator>>(std::istringstream &in, boost::optional<T> &val) {
T v;
in >> v;
val = v;
return in;
}
}
#endif
#include <CLI11.hpp>
```
This is an example of how to use the system only; if you are just looking for a
way to activate `boost::optional` support on older compilers, you should define
`CLI11_BOOST_OPTIONAL` before including a CLI11 file, you'll get the
`boost::optional` support.
## Custom converters and type names: std::chrono example
An example of adding a custom converter and typename for `std::chrono` follows:
```cpp
namespace CLI
{
template <typename T, typename R>
std::istringstream &operator>>(std::istringstream &in, std::chrono::duration<T,R> &val)
{
T v;
in >> v;
val = std::chrono::duration<T,R>(v);
return in;
}
template <typename T, typename R>
std::stringstream &operator<<(std::stringstream &in, std::chrono::duration<T,R> &val)
{
in << val.count();
return in;
}
}
#include <CLI/CLI.hpp>
namespace CLI
{
namespace detail
{
template <>
constexpr const char *type_name<std::chrono::hours>()
{
return "TIME [H]";
}
template <>
constexpr const char *type_name<std::chrono::minutes>()
{
return "TIME [MIN]";
}
}
}
```
Thanks to Olivier Hartmann for the example.

View File

@@ -0,0 +1,39 @@
# Making a git clone
Let's try our hand at a little `git` clone, called `geet`. It will just print
it's intent, rather than running actual code, since it's just a demonstration.
Let's start by adding an app and requiring 1 subcommand to run:
[include:"Intro"](../code/geet.cpp)
Now, let's define the first subcommand, `add`, along with a few options:
[include:"Add"](../code/geet.cpp)
Now, let's add `commit`:
[include:"Commit"](../code/geet.cpp)
All that's need now is the parse call. We'll print a little message after the
code runs, and then return:
[include:"Parse"](../code/geet.cpp)
[Source code](https://github.com/CLIUtils/CLI11/tree/main/book/code/geet.cpp)
If you compile and run:
```term
gitbook:examples $ c++ -std=c++11 geet.cpp -o geet
```
You'll see it behaves pretty much like `git`.
## Multi-file App parse code
This example could be made much nicer if it was split into files, one per
subcommand. If you simply use shared pointers instead of raw values in the
lambda capture, you can tie the lifetime to the lambda function lifetime. CLI11
has a
[multifile example](https://github.com/CLIUtils/CLI11/tree/main/examples/subcom_in_files)
in its example folder.

View File

@@ -0,0 +1,39 @@
# The Basics
The simplest CLI11 program looks like this:
[include](../code/simplest.cpp)
The first line includes the library; this explicitly uses the single file
edition (see [Selecting an edition](/chapters/installation)).
After entering the main function, you'll see that a `CLI::App` object is
created. This is the basis for all interactions with the library. You could
optionally provide a description for your app here.
A normal CLI11 application would define some flags and options next. This is a
simplest possible example, so we'll go on.
The macro `CLI11_PARSE` just runs five simple lines. This internally runs
`app.parse(argc, argv)`, which takes the command line info from C++ and parses
it. If there is an error, it throws a `ParseError`; if you catch it, you can use
`app.exit` with the error as an argument to print a nice message and produce the
correct return code for your application.
If you just use `app.parse` directly, your application will still work, but the
stack will not be correctly unwound since you have an uncaught exception, and
the command line output will be cluttered, especially for help.
For this (and most of the examples in this book) we will assume that we have the
`CLI11.hpp` file in the current directory and that we are creating an output
executable `a.out` on a macOS or Linux system. The commands to compile and test
this example would be:
```term
gitbook:examples $ g++ -std=c++11 simplest.cpp
gitbook:examples $ ./a.out -h
Usage: ./a.out [OPTIONS]
Options:
-h,--help Print this help message and exit
```

View File

@@ -0,0 +1,340 @@
# Accepting configure files
## Reading a configure file
You can tell your app to allow configure files with `set_config("--config")`.
There are arguments: the first is the option name. If empty, it will clear the
config flag. The second item is the default file name. If that is specified, the
config will try to read that file. The third item is the help string, with a
reasonable default, and the final argument is a boolean (default: false) that
indicates that the configuration file is required and an error will be thrown if
the file is not found and this is set to true.
### Adding a default path
if it is desired that config files be searched for a in a default path the
`CLI::FileOnDefaultPath` transform can be used.
```cpp
app.set_config("--config")->transform(CLI::FileOnDefaultPath("/default_path/"));
```
This will allow specified files to either exist as given or on a specified
default path.
```cpp
app.set_config("--config")
->transform(CLI::FileOnDefaultPath("/default_path/"))
->transform(CLI::FileOnDefaultPath("/default_path2/",false));
```
Multiple default paths can be specified through this mechanism. The last
transform given is executed first so the error return must be disabled so it can
be chained to the first. The same effect can be achieved though the or(`|`)
operation with validators
```cpp
app.set_config("--config")
->transform(CLI::FileOnDefaultPath("/default_path2/") | CLI::FileOnDefaultPath("/default_path/"));
```
### Extra fields
Sometimes configuration files are used for multiple purposes so CLI11 allows
options on how to deal with extra fields
```cpp
app.allow_config_extras(true);
```
will allow capture the extras in the extras field of the app. (NOTE: This also
sets the `allow_extras` in the app to true)
```cpp
app.allow_config_extras(false);
```
will generate an error if there are any extra fields for slightly finer control
there is a scoped enumeration of the modes or
```cpp
app.allow_config_extras(CLI::config_extras_mode::ignore);
```
will completely ignore extra parameters in the config file. This mode is the
default.
```cpp
app.allow_config_extras(CLI::config_extras_mode::capture);
```
will store the unrecognized options in the app extras fields. This option is the
closest equivalent to `app.allow_config_extras(true);` with the exception that
it does not also set the `allow_extras` flag so using this option without also
setting `allow_extras(true)` will generate an error which may or may not be the
desired behavior.
```cpp
app.allow_config_extras(CLI::config_extras_mode::error);
```
is equivalent to `app.allow_config_extras(false);`
```cpp
app.allow_config_extras(CLI::config_extras_mode::ignore_all);
```
will completely ignore any mismatches, extras, or other issues with the config
file
### Getting the used configuration file name
If it is needed to get the configuration file name used this can be obtained via
`app.get_config_ptr()->as<std::string>()` or
`app["--config"]->as<std::string>()` assuming `--config` was the configuration
option name.
## Configure file format
Here is an example configuration file, in
[TOML](https://github.com/toml-lang/toml) format:
```ini
# Comments are supported, using a #
# The default section is [default], case insensitive
value = 1
str = "A string"
vector = [1,2,3]
# Section map to subcommands
[subcommand]
in_subcommand = Wow
[subcommand.sub]
subcommand = true # could also be give as sub.subcommand=true
```
Spaces before and after the name and argument are ignored. Multiple arguments
are separated by spaces. One set of quotes will be removed, preserving spaces
(the same way the command line works). Boolean options can be `true`, `on`, `1`,
`y`, `t`, `+`, `yes`, `enable`; or `false`, `off`, `0`, `no`, `n`, `f`, `-`,
`disable`, (case insensitive). Sections (and `.` separated names) are treated as
subcommands (note: this does not necessarily mean that subcommand was passed, it
just sets the "defaults". If a subcommand is set to `configurable` then passing
the subcommand using `[sub]` in a configuration file will trigger the
subcommand.)
CLI11 also supports configuration file in INI format.
```ini
; Comments are supported, using a ;
; The default section is [default], case insensitive
value = 1
str = "A string"
vector = 1 2 3
; Section map to subcommands
[subcommand]
in_subcommand = Wow
sub.subcommand = true
```
The main differences are in vector notation and comment character. Note: CLI11
is not a full TOML parser as it just reads values as strings. It is possible
(but not recommended) to mix notation.
## Multiple configuration files
If it is desired that multiple configuration be allowed. Use
```cpp
app.set_config("--config")->expected(1, X);
```
Where X is some positive integer and will allow up to `X` configuration files to
be specified by separate `--config` arguments.
## Writing out a configure file
To print a configuration file from the passed arguments, use
`.config_to_str(default_also=false, write_description=false)`, where
`default_also` will also show any defaulted arguments, and `write_description`
will include option descriptions and the App description
```cpp
CLI::App app;
app.add_option(...);
// several other options
CLI11_PARSE(app, argc, argv);
//the config printout should be after the parse to capture the given arguments
std::cout<<app.config_to_str(true,true);
```
if a prefix is needed to print before the options, for example to print a config
for just a subcommand, the config formatter can be obtained directly.
```cpp
auto fmtr=app.get_config_formatter();
//std::string to_config(const App *app, bool default_also, bool write_description, std::string prefix)
fmtr->to_config(&app,true,true,"sub.");
//prefix can be used to set a prefix before each argument, like "sub."
```
### Customization of configure file output
The default config parser/generator has some customization points that allow
variations on the TOML format. The default formatter has a base configuration
that matches the TOML format. It defines 5 characters that define how different
aspects of the configuration are handled. You must use
`get_config_formatter_base()` to have access to these fields
```cpp
/// the character used for comments
char commentChar = '#';
/// the character used to start an array '\0' is a default to not use
char arrayStart = '[';
/// the character used to end an array '\0' is a default to not use
char arrayEnd = ']';
/// the character used to separate elements in an array
char arraySeparator = ',';
/// the character used separate the name from the value
char valueDelimiter = '=';
/// the character to use around strings
char stringQuote = '"';
/// the character to use around single characters
char characterQuote = '\'';
/// the maximum number of layers to allow
uint8_t maximumLayers{255};
/// the separator used to separator parent layers
char parentSeparatorChar{'.'};
/// Specify the configuration index to use for arrayed sections
uint16_t configIndex{0};
/// Specify the configuration section that should be used
std::string configSection;
```
These can be modified via setter functions
- `ConfigBase *comment(char cchar)`: Specify the character to start a comment
block
- `ConfigBase *arrayBounds(char aStart, char aEnd)`: Specify the start and end
characters for an array
- `ConfigBase *arrayDelimiter(char aSep)`: Specify the delimiter character for
an array
- `ConfigBase *valueSeparator(char vSep)`: Specify the delimiter between a name
and value
- `ConfigBase *quoteCharacter(char qString, char qChar)` :specify the characters
to use around strings and single characters
- `ConfigBase *maxLayers(uint8_t layers)` : specify the maximum number of parent
layers to process. This is useful to limit processing for larger config files
- `ConfigBase *parentSeparator(char sep)` : specify the character to separate
parent layers from options
- `ConfigBase *section(const std::string &sectionName)` : specify the section
name to use to get the option values, only this section will be processed
- `ConfigBase *index(uint16_t sectionIndex)` : specify an index section to use
for processing if multiple TOML sections of the same name are present
`[[section]]`
For example, to specify reading a configure file that used `:` to separate name
and values:
```cpp
auto config_base=app.get_config_formatter_base();
config_base->valueSeparator(':');
```
The default configuration file will read INI files, but will write out files in
the TOML format. To specify outputting INI formatted files use
```cpp
app.config_formatter(std::make_shared<CLI::ConfigINI>());
```
which makes use of a predefined modification of the ConfigBase class which TOML
also uses. If a custom formatter is used that is not inheriting from the from
ConfigBase class `get_config_formatter_base() will return a nullptr if RTTI is
on (usually the default), or garbage if RTTI is off, so some care must be
exercised in its use with custom configurations.
## Custom formats
You can invent a custom format and set that instead of the default INI
formatter. You need to inherit from `CLI::Config` and implement the following
two functions:
```cpp
std::string to_config(const CLI::App *app, bool default_also, bool, std::string) const;
std::vector<CLI::ConfigItem> from_config(std::istream &input) const;
```
The `CLI::ConfigItem`s that you return are simple structures with a name, a
vector of parents, and a vector of results. A optionally customizable `to_flag`
method on the formatter lets you change what happens when a ConfigItem turns
into a flag.
Finally, set your new class as new config formatter:
```cpp
app.config_formatter(std::make_shared<NewConfig>());
```
See
[`examples/json.cpp`](https://github.com/CLIUtils/CLI11/blob/main/examples/json.cpp)
for a complete JSON config example.
### Trivial JSON configuration example
```JSON
{
"test": 56,
"testb": "test",
"flag": true
}
```
The parser can handle these structures with only a minor tweak
```cpp
app.get_config_formatter_base()->valueSeparator(':');
```
The open and close brackets must be on a separate line and the comma gets
interpreted as an array separator but since no values are after the comma they
get ignored as well. This will not support multiple layers or sections or any
other moderately complex JSON, but can work if the input file is simple.
## Triggering Subcommands
Configuration files can be used to trigger subcommands if a subcommand is set to
configure. By default configuration file just set the default values of a
subcommand. But if the `configure()` option is set on a subcommand then the if
the subcommand is utilized via a `[subname]` block in the configuration file it
will act as if it were called from the command line. Subsubcommands can be
triggered via `[subname.subsubname]`. Using the `[[subname]]` will be as if the
subcommand were triggered multiple times from the command line. This
functionality can allow the configuration file to act as a scripting file.
For custom configuration files this behavior can be triggered by specifying the
parent subcommands in the structure and `++` as the name to open a new
subcommand scope and `--` to close it. These names trigger the different
callbacks of configurable subcommands.
## Stream parsing
In addition to the regular parse functions a
`parse_from_stream(std::istream &input)` is available to directly parse a stream
operator. For example to process some arguments in an already open file stream.
The stream is fed directly in the config parser so bypasses the normal command
line parsing.
## Implementation Notes
The config file input works with any form of the option given: Long, short,
positional, or the environment variable name. When generating a config file it
will create an option name in following priority.
1. First long name
2. Positional name
3. First short name
4. Environment name

View File

@@ -0,0 +1,167 @@
# Adding Flags
The most basic addition to a command line program is a flag. This is simply
something that does not take any arguments. Adding a flag in CLI11 is done in
one of three ways.
## Boolean flags
The simplest way to add a flag is probably a boolean flag:
```cpp
bool my_flag{false};
app.add_flag("-f", my_flag, "Optional description");
```
This will bind the flag `-f` to the boolean `my_flag`. After the parsing step,
`my_flag` will be `false` if the flag was not found on the command line, or
`true` if it was. By default, it will be allowed any number of times, but if you
explicitly\[^1\] request `->take_last(false)`, it will only be allowed once;
passing something like `./my_app -f -f` or `./my_app -ff` will throw a
`ParseError` with a nice help description. A flag name may start with any
character except ('-', ' ', '\n', and '!'). For long flags, after the first
character all characters are allowed except ('=',':','{',' ', '\n'). Names are
given as a comma separated string, with the dash or dashes. An flag can have as
many names as you want, and afterward, using `count`, you can use any of the
names, with dashes as needed.
## Integer flags
If you want to allow multiple flags and count their value, simply use any
integral variables instead of a bool:
```cpp
int my_flag{0};
app.add_flag("-f", my_flag, "Optional description");
```
After the parsing step, `my_flag` will contain the number of times this flag was
found on the command line, including 0 if not found.
This behavior can also be controlled manually via
`->multi_option_policy(CLI::MultiOptionPolicy::Sum)` as of version 2.2.
## Arbitrary type flags
CLI11 allows the type of the variable to assign to in the `add_flag` function to
be any supported type. This is particularly useful in combination with
specifying default values for flags. The allowed types include bool, int, float,
vector, enum, or string-like.
### Default Flag Values
Flag options specified through the `add_flag*` functions allow a syntax for the
option names to default particular options to a false value or any other value
if some flags are passed. For example:
```cpp
app.add_flag("--flag,!--no-flag",result,"help for flag");
```
specifies that if `--flag` is passed on the command line result will be true or
contain a value of 1. If `--no-flag` is passed `result` will contain false or -1
if `result` is a signed integer type, or 0 if it is an unsigned type. An
alternative form of the syntax is more explicit: `"--flag,--no-flag{false}"`;
this is equivalent to the previous example. This also works for short form
options `"-f,!-n"` or `"-f,-n{false}"`. If `variable_to_bind_to` is anything but
an integer value the default behavior is to take the last value given, while if
`variable_to_bind_to` is an integer type the behavior will be to sum all the
given arguments and return the result. This can be modified if needed by
changing the `multi_option_policy` on each flag (this is not inherited). The
default value can be any value. For example if you wished to define a numerical
flag:
```cpp
app.add_flag("-1{1},-2{2},-3{3}",result,"numerical flag")
```
using any of those flags on the command line will result in the specified number
in the output. Similar things can be done for string values, and enumerations,
as long as the default value can be converted to the given type.
## Pure flags
Every command that starts with `add_`, such as the flag commands, return a
pointer to the internally stored `CLI::Option` that describes your addition. If
you prefer, you can capture this pointer and use it, and that allows you to skip
adding a variable to bind to entirely:
```cpp
CLI::Option* my_flag = app.add_flag("-f", "Optional description");
```
After parsing, you can use `my_flag->count()` to count the number of times this
was found. You can also directly use the value (`*my_flag`) as a bool.
`CLI::Option` will be discussed in more detail later.
## Callback flags
If you want to define a callback that runs when you make a flag, you can use
`add_flag_function` (C++11 or newer) or `add_flag` (C++14 or newer only) to add
a callback function. The function should have the signature `void(std::size_t)`.
This could be useful for a version printout, etc.
```cpp
auto callback = [](int count){std::cout << "This was called " << count << " times";};
app.add_flag_function("-c", callback, "Optional description");
```
## Aliases
The name string, the first item of every `add_` method, can contain as many
short and long names as you want, separated by commas. For example,
`"-a,--alpha,-b,--beta"` would allow any of those to be recognized on the
command line. If you use the same name twice, or if you use the same name in
multiple flags, CLI11 will immediately throw a `CLI::ConstructionError`
describing your problem (it will not wait until the parsing step).
If you want to make an option case insensitive, you can use the
`->ignore_case()` method on the `CLI::Option` to do that. For example,
```cpp
bool flag{false};
app.add_flag("--flag", flag)
->ignore_case();
```
would allow the following to count as passing the flag:
```term
gitbook $ ./my_app --fLaG
```
## Example
The following program will take several flags:
[include:"define"](../code/flags.cpp)
The values would be used like this:
[include:"usage"](../code/flags.cpp)
[Source code](https://github.com/CLIUtils/CLI11/tree/main/book/code/flags.cpp)
If you compile and run:
```term
gitbook:examples $ g++ -std=c++11 flags.cpp
gitbook:examples $ ./a.out -h
Flag example program
Usage: ./a.out [OPTIONS]
Options:
-h,--help Print this help message and exit
-b,--bool This is a bool flag
-i,--int This is an int flag
-p,--plain This is a plain flag
gitbook:examples $ ./a.out -bii --plain -i
The flags program
Bool flag passed
Flag int: 3
Flag plain: 1
```
\[^1\]: It will not inherit this from the parent defaults, since this is often
useful even if you don't want all options to allow multiple passed options.

View File

@@ -0,0 +1,86 @@
# Formatting help output
{% hint style='info' %} New in CLI11 1.6 {% endhint %}
## Customizing an existing formatter
In CLI11, you can control the output of the help printout in full or in part.
The default formatter was written in such a way as to be customizable. You can
use `app.get_formatter()` to get the current formatter. The formatter you set
will be inherited by subcommands that are created after you set the formatter.
There are several configuration options that you can set:
| Set method | Description | Availability |
| --------------------- | -------------------------------- | ------------ |
| `column_width(width)` | The width of the columns | Both |
| `label(key, value)` | Set a label to a different value | Both |
Labels will map the built in names and type names from key to value if present.
For example, if you wanted to change the width of the columns to 40 and the
`REQUIRED` label from `(REQUIRED)` to `(MUST HAVE)`:
```cpp
app.get_formatter()->column_width(40);
app.get_formatter()->label("REQUIRED", "(MUST HAVE)");
```
## Subclassing
You can further configure pieces of the code while still keeping most of the
formatting intact by subclassing either formatter and replacing any of the
methods with your own. The formatters use virtual functions most places, so you
are free to add or change anything about them. For example, if you wanted to
remove the info that shows up between the option name and the description:
```cpp
class MyFormatter : public CLI::Formatter {
public:
std::string make_option_opts(const CLI::Option *) const override {return "";}
};
app.formatter(std::make_shared<MyFormatter>());
```
Look at the class definitions in `FormatterFwd.hpp` or the method definitions in
`Formatter.hpp` to see what methods you have access to and how they are put
together.
## Anatomy of a help message
This is a normal printout, with `<>` indicating the methods used to produce each
line.
```text
<make_description(app)>
<make_usage(app)>
<make_positionals(app)>
<make_group(app, "Positionals", true, filter>
<make_groups(app, mode)>
<make_group(app, "Option Group 1"), false, filter>
<make_group(app, "Option Group 2"), false, filter>
...
<make_subcommands(app)>
<make_subcommand(sub1, Mode::Normal)>
<make_subcommand(sub2, Mode::Normal)>
<make_footer(app)>
```
`make_usage` calls `make_option_usage(opt)` on all the positionals to build that
part of the line. `make_subcommand` passes the subcommand as the app pointer.
The `make_groups` print the group name then call `make_option(o)` on the options
listed in that group. The normal printout for an option looks like this:
```text
make_option_opts(o)
┌───┴────┐
-n,--name (REQUIRED) This is a description
└────┬────┘ └──────────┬──────────┘
make_option_name(o,p) make_option_desc(o)
```
Notes:
- `*1`: This signature depends on whether the call is from a positional or
optional.
- `o` is opt pointer, `p` is true if positional.

View File

@@ -0,0 +1,114 @@
# Installation
## Single file edition
```cpp
#include <CLI11.hpp>
```
This example uses the single file edition of CLI11. You can download `CLI11.hpp`
from the latest release and put it into the same folder as your source code,
then compile this with C++ enabled. For a larger project, you can just put this
in an include folder and you are set.
## Full edition
```cpp
#include <CLI/CLI.hpp>
```
If you want to use CLI11 in its full form, you can also use the original
multiple file edition. This has an extra utility (`Timer`), and is does not
require that you use a release. The only change to your code would be the
include shown above.
### CMake support for the full edition
If you use CMake 3.4+ for your project (highly recommended), CLI11 comes with a
powerful CMakeLists.txt file that was designed to also be used with
`add_subproject`. You can add the repository to your code (preferably as a git
submodule), then add the following line to your project (assuming your folder is
called CLI11):
```cmake
add_subdirectory(CLI11)
```
Then, you will have a target `CLI11::CLI11` that you can link to with
`target_link_libraries`. It will provide the include paths you need for the
library. This is the way [GooFit](https://github.com/GooFit/GooFit) uses CLI11,
for example.
You can also configure and optionally install CLI11, and CMake will create the
necessary `lib/cmake/CLI11/CLI11Config.cmake` files, so
`find_package(CLI11 CONFIG REQUIRED)` also works.
If you use conan.io, CLI11 supports that too.
### Running tests on the full edition
CLI11 has examples and tests that can be accessed using a CMake build on any
platform. Simply build and run ctest to run the 200+ tests to ensure CLI11 works
on your system.
As an example of the build system, the following code will download and test
CLI11 in a simple Alpine Linux docker container [^1]:
```term
gitbook:~ $ docker run -it alpine
root:/ # apk add --no-cache g++ cmake make git
fetch ...
root:/ # git clone https://github.com/CLIUtils/CLI11.git
Cloning into 'CLI11' ...
root:/ # cd CLI11
root:CLI11 # mkdir build
root:CLI11 # cd build
root:build # cmake ..
-- The CXX compiler identification is GNU 6.3.0 ...
root:build # make
Scanning dependencies ...
root:build # make test
[warning]Running tests...
Test project /CLI11/build
Start 1: HelpersTest
1/10 Test #1: HelpersTest ...................... Passed 0.01 sec
Start 2: IniTest
2/10 Test #2: IniTest .......................... Passed 0.01 sec
Start 3: SimpleTest
3/10 Test #3: SimpleTest ....................... Passed 0.01 sec
Start 4: AppTest
4/10 Test #4: AppTest .......................... Passed 0.02 sec
Start 5: CreationTest
5/10 Test #5: CreationTest ..................... Passed 0.01 sec
Start 6: SubcommandTest
6/10 Test #6: SubcommandTest ................... Passed 0.01 sec
Start 7: HelpTest
7/10 Test #7: HelpTest ......................... Passed 0.01 sec
Start 8: NewParseTest
8/10 Test #8: NewParseTest ..................... Passed 0.01 sec
Start 9: TimerTest
9/10 Test #9: TimerTest ........................ Passed 0.24 sec
Start 10: link_test_2
10/10 Test #10: link_test_2 ...................... Passed 0.00 sec
100% tests passed, 0 tests failed out of 10
Total Test time (real) = 0.34 sec
```
For the curious, the CMake options and defaults are listed below. Most options
default to off if CLI11 is used as a subdirectory in another project.
| Option | Description |
| ----------------------------- | ----------------------------------------------------------------------------------------------- |
| `CLI11_SINGLE_FILE=ON` | Build the `CLI11.hpp` file from the sources. Requires Python (version 3 or 2.7). |
| `CLI11_SINGLE_FILE_TESTS=OFF` | Run the tests on the generated single file version as well |
| `CLI11_EXAMPLES=ON` | Build the example programs. |
| `CLI11_TESTING=ON` | Build the tests. |
| `CLI11_CLANG_TIDY=OFF` | Run `clang-tidy` on the examples and headers. Requires CMake 3.6+. |
| `CLI11_CLANG_TIDY_OPTIONS=""` | Options to pass to `clang-tidy`, such as `-fix` (single threaded build only if applying fixes!) |
[^1]:
Docker is being used to create a pristine disposable environment; there is
nothing special about this container. Alpine is being used because it is
small, modern, and fast. Commands are similar on any other platform.

View File

@@ -0,0 +1,54 @@
# CLI11 Internals
## Callbacks
The library was designed to bind to existing variables without requiring typed
classes or inheritance. This is accomplished through lambda functions.
This looks like:
```cpp
Option* add_option(string name, T item) {
this->function = [&item](string value){
item = detail::lexical_cast<T>(value);
}
}
```
Obviously, you can't access `T` after the `add_` method is over, so it stores
the string representation of the default value if it receives the special `true`
value as the final argument (not shown above).
## Parsing
Parsing follows the following procedure:
1. `_validate`: Make sure the defined options and subcommands are self
consistent.
2. `_parse`: Main parsing routine. See below.
3. `_run_callback`: Run an App callback if present.
The parsing phase is the most interesting:
1. `_parse_single`: Run on each entry on the command line and fill the
options/subcommands.
2. `_process`: Run the procedure listed below.
3. `_process_extra`: This throws an error if needed on extra arguments that
didn't fit in the parse.
The `_process` procedure runs the following steps; each step is recursive and
completes all subcommands before moving to the next step (new in 1.7). This
ensures that interactions between options and subcommand options is consistent.
1. `_process_ini`: This reads an INI file and fills/changes options as needed.
2. `_process_env`: Look for environment variables.
3. `_process_callbacks`: Run the callback functions - this fills out the
variables.
4. `_process_help_flags`: Run help flags if present (and quit).
5. `_process_requirements`: Make sure needs/excludes, required number of options
present.
## Exceptions
The library immediately returns a C++ exception when it detects a problem, such
as an incorrect construction or a malformed command line.

View File

@@ -0,0 +1,459 @@
# Options
## Simple options
The most versatile addition to a command line program is an option. This is like
a flag, but it takes an argument. CLI11 handles all the details for many types
of options for you, based on their type. To add an option:
```cpp
int int_option{0};
app.add_option("-i", int_option, "Optional description");
```
This will bind the option `-i` to the integer `int_option`. On the command line,
a single value that can be converted to an integer will be expected. Non-integer
results will fail. If that option is not given, CLI11 will not touch the initial
value. This allows you to set up defaults by simply setting your value
beforehand. If you want CLI11 to display your default value, you can add
`->capture_default_str()` after the option.
```cpp
int int_option{0};
app.add_option("-i", int_option, "Optional description")->capture_default_str();
```
You can use any C++ int-like type, not just `int`. CLI11 understands the
following categories of types:
| Type | CLI11 |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| number like | Integers, floats, bools, or any type that can be constructed from an integer or floating point number. Accepts common numerical strings like `0xFF` as well as octal, and decimal |
| string-like | std::string, or anything that can be constructed from or assigned a std::string |
| char | For a single char, single string values are accepted, otherwise longer strings are treated as integral values and a conversion is attempted |
| complex-number | std::complex or any type which has a real(), and imag() operations available, will allow 1 or 2 string definitions like "1+2j" or two arguments "1","2" |
| enumeration | any enum or enum class type is supported through conversion from the underlying type(typically int, though it can be specified otherwise) |
| container-like | a container(like vector) of any available types including other containers |
| wrapper | any other object with a `value_type` static definition where the type specified by `value_type` is one of the type in this list, including `std::atomic<>` |
| tuple | a tuple, pair, or array, or other type with a tuple size and tuple_type operations defined and the members being a type contained in this list |
| function | A function that takes an array of strings and returns a string that describes the conversion failure or empty for success. May be the empty function. (`{}`) |
| streamable | any other type with a `<<` operator will also work |
By default, CLI11 will assume that an option is optional, and one value is
expected if you do not use a vector. You can change this on a specific option
using option modifiers. An option name may start with any character except ('-',
' ', '\n', and '!'). For long options, after the first character all characters
are allowed except ('=',':','{',' ', '\n'). Names are given as a comma separated
string, with the dash or dashes. An option can have as many names as you want,
and afterward, using `count`, you can use any of the names, with dashes as
needed, to count the options. One of the names is allowed to be given without
proceeding dash(es); if present the option is a positional option, and that name
will be used on the help line for its positional form.
## Positional options and aliases
When you give an option on the command line without a name, that is a positional
option. Positional options are accepted in the same order they are defined. So,
for example:
```term
gitbook:examples $ ./a.out one --two three four
```
The string `one` would have to be the first positional option. If `--two` is a
flag, then the remaining two strings are positional. If `--two` is a
one-argument option, then `four` is the second positional. If `--two` accepts
two or more arguments, then there are no more positionals.
To make a positional option, you simply give CLI11 one name that does not start
with a dash. You can have as many (non-overlapping) names as you want for an
option, but only one positional name. So the following name string is valid:
```cpp
"-a,-b,--alpha,--beta,mypos"
```
This would make two short option aliases, two long option alias, and the option
would be also be accepted as a positional.
## Containers of options
If you use a vector or other container instead of a plain option, you can accept
more than one value on the command line. By default, a container accepts as many
options as possible, until the next value that could be a valid option name. You
can specify a set number using an option modifier `->expected(N)`. (The default
unlimited behavior on vectors is restored with `N=-1`) CLI11 does not
differentiate between these two methods for unlimited acceptance options.
| Separate names | Combined names |
| ----------------- | -------------- |
| `--vec 1 --vec 2` | `--vec 1 2` |
It is also possible to specify a minimum and maximum number through
`->expected(Min,Max)`. It is also possible to specify a min and max type size
for the elements of the container. It most cases these values will be
automatically determined but a user can manually restrict them.
An example of setting up a vector option:
```cpp
std::vector<int> int_vec;
app.add_option("--vec", int_vec, "My vector option");
```
Vectors will be replaced by the parsed content if the option is given on the
command line.
A definition of a container for purposes of CLI11 is a type with a `end()`,
`insert(...)`, `clear()` and `value_type` definitions. This includes `vector`,
`set`, `deque`, `list`, `forward_iist`, `map`, `unordered_map` and a few others
from the standard library, and many other containers from the boost library.
### Empty containers
By default a container will never return an empty container. If it is desired to
allow an empty container to be returned, then the option must be modified with a
0 as the minimum expected value
```cpp
std::vector<int> int_vec;
app.add_option("--vec", int_vec, "Empty vector allowed")->expected(0,-1);
```
An empty vector can than be specified on the command line as `--vec {}`
To allow an empty vector from config file, the default must be set in addition
to the above modification.
```cpp
std::vector<int> int_vec;
app.add_option("--vec", int_vec, "Empty vector allowed")->expected(0,-1)->default_str("{}");
```
Then in the file
```toml
vec={}
```
or
```toml
vec=[]
```
will generate an empty vector in `int_vec`.
### Containers of containers
Containers of containers are also supported.
```cpp
std::vector<std::vector<int>> int_vec;
app.add_option("--vec", int_vec, "My vector of vectors option");
```
CLI11 inserts a separator sequence at the start of each argument call to
separate the vectors. So unless the separators are injected as part of the
command line each call of the option on the command line will result in a
separate element of the outer vector. This can be manually controlled via
`inject_separator(true|false)` but in nearly all cases this should be left to
the defaults. To insert of a separator from the command line add a `%%` where
the separation should occur.
```bash
cmd --vec_of_vec 1 2 3 4 %% 1 2
```
would then result in a container of size 2 with the first element containing 4
values and the second 2.
This separator is also the only way to get values into something like
```cpp
std::pair<std::vector<int>,std::vector<int>> two_vecs;
app.add_option("--vec", two_vecs, "pair of vectors");
```
without calling the argument twice.
Further levels of nesting containers should compile but intermediate layers will
only have a single element in the container, so is probably not that useful.
### Nested types
Types can be nested. For example:
```cpp
std::map<int, std::pair<int,std::string>> map;
app.add_option("--dict", map, "map of pairs");
```
will require 3 arguments for each invocation, and multiple sets of 3 arguments
can be entered for a single invocation on the command line.
```cpp
std::map<int, std::pair<int,std::vector<std::string>>> map;
app.add_option("--dict", map, "map of pairs");
```
will result in a requirement for 2 integers on each invocation and absorb an
unlimited number of strings including 0.
## Option modifiers
When you call `add_option`, you get a pointer to the added option. You can use
that to add option modifiers. A full listing of the option modifiers:
| Modifier | Description |
| ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `->required()` | The program will quit if this option is not present. This is `mandatory` in Plumbum, but required options seems to be a more standard term. For compatibility, `->mandatory()` also works. |
| `->expected(N)` | Take `N` values instead of as many as possible, mainly for vector args. |
| `->expected(Nmin,Nmax)` | Take between `Nmin` and `Nmax` values. |
| `->type_size(N)` | specify that each block of values would consist of N elements |
| `->type_size(Nmin,Nmax)` | specify that each block of values would consist of between Nmin and Nmax elements |
| `->needs(opt)` | This option requires another option to also be present, opt is an `Option` pointer or a string with the name of the option. Can be removed with `->remove_needs(opt)` |
| `->excludes(opt)` | This option cannot be given with `opt` present, opt is an `Option` pointer or a string with the name of the option. Can be removed with `->remove_excludes(opt)` |
| `->envname(name)` | Gets the value from the environment if present and not passed on the command line. |
| `->group(name)` | The help group to put the option in. No effect for positional options. Defaults to `"Options"`. `"Hidden"` will not show up in the help print. |
| `->description(string)` | Set/change the description |
| `->ignore_case()` | Ignore the case on the command line (also works on subcommands, does not affect arguments). |
| `->ignore_underscore()` | Ignore any underscores on the command line (also works on subcommands, does not affect arguments). |
| `->allow_extra_args()` | Allow extra argument values to be included when an option is passed. Enabled by default for vector options. |
| `->disable_flag_override()` | specify that flag options cannot be overridden on the command line use `=<newval>` |
| `->delimiter('<CH>')` | specify a character that can be used to separate elements in a command line argument, default is <none>, common values are ',', and ';' |
| `->multi_option_policy( CLI::MultiOptionPolicy::Throw)` | Sets the policy for handling multiple arguments if the option was received on the command line several times. `Throw`ing an error is the default, but `TakeLast`, `TakeFirst`, `TakeAll`, `Join`, and `Sum` are also available. See the next four lines for shortcuts to set this more easily. |
| `->take_last()` | Only use the last option if passed several times. This is always true by default for bool options, regardless of the app default, but can be set to false explicitly with `->multi_option_policy()`. |
| `->take_first()` | sets `->multi_option_policy(CLI::MultiOptionPolicy::TakeFirst)` |
| `->take_all()` | sets `->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)` |
| `->join()` | sets `->multi_option_policy(CLI::MultiOptionPolicy::Join)`, which uses newlines or the specified delimiter to join all arguments into a single string output. |
| `->join(delim)` | sets `->multi_option_policy(CLI::MultiOptionPolicy::Join)`, which uses `delim` to join all arguments into a single string output. this also sets the delimiter |
| `->check(Validator)` | perform a check on the returned results to verify they meet some criteria. See [Validators](./validators.md) for more info |
| `->transform(Validator)` | Run a transforming validator on each value passed. See [Validators](./validators.md) for more info |
| `->each(void(std::string))` | Run a function on each parsed value, _in order_. |
| `->default_str(string)` | set a default string for use in the help and as a default value if no arguments are passed and a value is requested |
| `->default_function(std::string())` | Advanced: Change the function that `capture_default_str()` uses. |
| `->default_val(value)` | Generate the default string from a value and validate that the value is also valid. For options that assign directly to a value type the value in that type is also updated. Value must be convertible to a string(one of known types or have a stream operator). |
| `->capture_default_str()` | Store the current value attached and display it in the help string. |
| `->always_capture_default()` | Always run `capture_default_str()` when creating new options. Only useful on an App's `option_defaults`. |
| `->run_callback_for_default()` | Force the option callback to be executed or the variable set when the `default_val` is used. |
| `->force_callback()` | Force the option callback to be executed regardless of whether the option was used or not. Will use the default_str if available, if no default is given the callback will be executed with an empty string as an argument, which will translate to a default initialized value, which can be compiler dependent |
| `->trigger_on_parse()` | Have the option callback be triggered when the value is parsed vs. at the end of all parsing, the option callback can potentially be executed multiple times. Generally only useful if you have a user defined callback or validation check. Or potentially if a vector input is given multiple times as it will clear the results when a repeat option is given via command line. It will trigger the callbacks once per option call on the command line |
| `->option_text(string)` | Sets the text between the option name and description. |
The `->check(...)` and `->transform(...)` modifiers can also take a callback
function of the form `bool function(std::string)` that runs on every value that
the option receives, and returns a value that tells CLI11 whether the check
passed or failed.
## Using the `CLI::Option` pointer
Each of the option creation mechanisms returns a pointer to the internally
stored option. If you save that pointer, you can continue to access the option,
and change setting on it later. The Option object can also be converted to a
bool to see if it was passed, or `->count()` can be used to see how many times
the option was passed. Since flags are also options, the same methods work on
them.
```cpp
CLI::Option* opt = app.add_flag("--opt");
CLI11_PARSE(app, argv, argc);
if(* opt)
std::cout << "Flag received " << opt->count() << " times." << std::endl;
```
## Inheritance of defaults
One of CLI11's systems to allow customizability without high levels of verbosity
is the inheritance system. You can set default values on the parent `App`, and
all options and subcommands created from it remember the default values at the
point of creation. The default value for Options, specifically, are accessible
through the `option_defaults()` method. There are a number of settings that can
be set and inherited:
- `group`: The group name starts as "Options"
- `required`: If the option must be given. Defaults to `false`. Is ignored for
flags.
- `multi_option_policy`: What to do if several copies of an option are passed
and one value is expected. Defaults to `CLI::MultiOptionPolicy::Throw`. This
is also used for bool flags, but they always are created with the value
`CLI::MultiOptionPolicy::TakeLast` or `CLI::MultiOptionPolicy::Sum` regardless
of the default, so that multiple bool flags does not cause an error. But you
can override that setting by calling the `multi_option_policy` directly.
- `ignore_case`: Allow any mixture of cases for the option or flag name
- `ignore_underscore`: Allow any number of underscores in the option or flag
name
- `configurable`: Specify whether an option can be configured through a config
file
- `disable_flag_override`: do not allow flag values to be overridden on the
command line
- `always_capture_default`: specify that the default values should be
automatically captured.
- `delimiter`: A delimiter to use for capturing multiple values in a single
command line string (e.g. --flag="flag,-flag2,flag3")
An example of usage:
```cpp
app.option_defaults()->ignore_case()->group("Required");
app.add_flag("--CaSeLeSs");
app.get_group() // is "Required"
```
Groups are mostly for visual organization, but an empty string for a group name
will hide the option.
### Windows style options
You can also set the app setting `app->allow_windows_style_options()` to allow
windows style options to also be recognized on the command line:
- `/a` (flag)
- `/f filename` (option)
- `/long` (long flag)
- `/file filename` (space)
- `/file:filename` (colon)
- `/long_flag:false` (long flag with : to override the default value)
Windows style options do not allow combining short options or values not
separated from the short option like with `-` options. You still specify option
names in the same manner as on Linux with single and double dashes when you use
the `add_*` functions, and the Linux style on the command line will still work.
If a long and a short option share the same name, the option will match on the
first one defined.
## Parse configuration
How an option and its arguments are parsed depends on a set of controls that are
part of the option structure. In most circumstances these controls are set
automatically based on the type or function used to create the option and the
type the arguments are parsed into. The variables define the size of the
underlying type (essentially how many strings make up the type), the expected
size (how many groups are expected) and a flag indicating if multiple groups are
allowed with a single option. And these interact with the `multi_option_policy`
when it comes time to parse.
### Examples
How options manage this is best illustrated through some examples.
```cpp
std::string val;
app.add_option("--opt",val,"description");
```
creates an option that assigns a value to a `std::string` When this option is
constructed it sets a type_size min and max of 1. Meaning that the assignment
uses a single string. The Expected size is also set to 1 by default, and
`allow_extra_args` is set to false. meaning that each time this option is called
1 argument is expected. This would also be the case if val were a `double`,
`int` or any other single argument types.
now for example
```cpp
std::pair<int, std::string> val;
app.add_option("--opt",val,"description");
```
In this case the typesize is automatically detected to be 2 instead of 1, so the
parsing would expect 2 arguments associated with the option.
```cpp
std::vector<int> val;
app.add_option("--opt",val,"description");
```
detects a type size of 1, since the underlying element type is a single string,
so the minimum number of strings is 1. But since it is a vector the expected
number can be very big. The default for a vector is (1<<30), and the
allow_extra_args is set to true. This means that at least 1 argument is expected
to follow the option, but arbitrary numbers of arguments may follow. These are
checked if they have the form of an option but if not they are added to the
argument.
```cpp
std::vector<std::tuple<int, double, std::string>> val;
app.add_option("--opt",val,"description");
```
gets into the complicated cases where the type size is now 3. and the expected
max is set to a large number and `allow_extra_args` is set to true. In this case
at least 3 arguments are required to follow the option, and subsequent groups
must come in groups of three, otherwise an error will result.
```cpp
bool val{false};
app.add_flag("--opt",val,"description");
```
Using the add_flag methods for creating options creates an option with an
expected size of 0, implying no arguments can be passed.
```cpp
std::complex<double> val;
app.add_option("--opt",val,"description");
```
triggers the complex number type which has a min of 1 and max of 2, so 1 or 2
strings can be passed. Complex number conversion supports arguments of the form
"1+2j" or "1","2", or "1" "2i". The imaginary number symbols `i` and `j` are
interchangeable in this context.
```cpp
std::vector<std::vector<int>> val;
app.add_option("--opt",val,"description");
```
has a type size of 1 to (1<<30).
### Customization
The `type_size(N)`, `type_size(Nmin, Nmax)`, `expected(N)`,
`expected(Nmin,Nmax)`, and `allow_extra_args()` can be used to customize an
option. For example
```cpp
std::string val;
auto opt=app.add_flag("--opt{vvv}",val,"description");
opt->expected(0,1);
```
will create a hybrid option, that can exist on its own in which case the value
"vvv" is used or if a value is given that value will be used.
There are some additional options that can be specified to modify an option for
specific cases:
- `->run_callback_for_default()` will specify that the callback should be
executed when a default_val is set. This is set automatically when appropriate
though it can be turned on or off and any user specified callback for an
option will be executed when the default value for an option is set.
- `->force_callback()` will for the callback/value assignment to run at the
conclusion of parsing regardless of whether the option was supplied or not.
This can be used to force the default or execute some code.
- `->trigger_on_parse()` will trigger the callback or value assignment each time
the argument is passed. The value is reset if the option is supplied multiple
times.
## Unusual circumstances
There are a few cases where some things break down in the type system managing
options and definitions. Using the `add_option` method defines a lambda function
to extract a default value if required. In most cases this is either
straightforward or a failure is detected automatically and handled. But in a few
cases a streaming template is available that several layers down may not
actually be defined. This results in CLI11 not being able to detect this
circumstance automatically and will result in compile error. One specific known
case is `boost::optional` if the boost optional_io header is included. This
header defines a template for all boost optional values even if they do not
actually have a streaming operator. For example `boost::optional<std::vector>`
does not have a streaming operator but one is detected since it is part of a
template. For these cases a secondary method `app->add_option_no_stream(...)` is
provided that bypasses this operation completely and should compile in these
cases.

View File

@@ -0,0 +1,194 @@
# Subcommands and the App
Subcommands are keyword that invoke a new set of options and features. For
example, the `git` command has a long series of subcommands, like `add` and
`commit`. Each can have its own options and implementations. This chapter will
focus on implementations that are contained in the same C++ application, though
the system git uses to extend the main command by calling other commands in
separate executables is supported too; that's called "Prefix commands" and is
included at the end of this chapter.
## The parent App
We'll start by discussing the parent `App`. You've already used it quite a bit,
to create options and set option defaults. There are several other things you
can do with an `App`, however.
You are given a lot of control the help output. You can set a footer with
`app.footer("My Footer")`. You can replace the default help print when a
`ParseError` is thrown with
`app.set_failure_message(CLI::FailureMessage::help)`. The default is
`CLI:::FailureMessage::simple`, and you can easily define a new one. Just make a
(lambda) function that takes an App pointer and a reference to an error code
(even if you don't use them), and returns a string.
## Adding a subcommand
Subcommands can be added just like an option:
```cpp
CLI::App* sub = app.add_subcommand("sub", "This is a subcommand");
```
The subcommand should have a name as the first argument, and a little
description for the second argument. A pointer to the internally stored
subcommand is provided; you usually will be capturing that pointer and using it
later (though you can use callbacks if you prefer). As always, feel free to use
`auto sub = ...` instead of naming the type.
You can check to see if the subcommand was received on the command line several
ways:
```cpp
if(*sub) ...
if(sub->parsed()) ...
if(app.got_subcommand(sub)) ...
if(app.got_subcommand("sub")) ...
```
You can also get a list of subcommands with `get_subcommands()`, and they will
be in parsing order.
There are a lot of options that you can set on a subcommand; in fact,
subcommands have exactly the same options as your main app, since they are
actually the same class of object (as you may have guessed from the type above).
This has the pleasant side affect of making subcommands infinitely nestable.
## Required subcommands
Each App has controls to set the number of subcommands you expect. This is
controlled by:
```cpp
app.require_subcommand(/* min */ 0, /* max */ 1);
```
If you set the max to 0, CLI11 will allow an unlimited number of subcommands.
After the (non-unlimited) maximum is reached, CLI11 will stop trying to match
subcommands. So the if you pass "`one two`" to a command, and both `one` and
`two` are subcommands, it will depend on the maximum number as to whether the
"`two`" is a subcommand or an argument to the "`one`" subcommand.
As a shortcut, you can also call the `require_subcommand` method with one
argument; that will be the fixed number of subcommands if positive, it will be
the maximum number if negative. Calling it without an argument will set the
required subcommands to 1 or more.
The maximum number of subcommands is inherited by subcommands. This allows you
to set the maximum to 1 once at the beginning on the parent app if you only want
single subcommands throughout your app. You should keep this in mind, if you are
dealing with lots of nested subcommands.
## Using callbacks
You've already seen how to check to see what subcommands were given. It's often
much easier, however, to just define the code you want to run when you are
making your parser, and not run a bunch of code after `CLI11_PARSE` to analyse
the state (Procedural! Yuck!). You can do that with lambda functions. A
`std::function<void()>` callback `.callback()` is provided, and CLI11 ensures
that all options are prepared and usable by reference capture before entering
the callback. An example is shown below in the `geet` program.
## Inheritance of defaults
The following values are inherited when you add a new subcommand. This happens
at the point the subcommand is created:
- The name and description for the help flag
- The footer
- The failure message printer function
- Option defaults
- Allow extras
- Prefix command
- Ignore case
- Ignore underscore
- Allow Windows style options
- Fallthrough
- Group name
- Max required subcommands
- validate positional arguments
- validate optional arguments
## Special modes
There are several special modes for Apps and Subcommands.
### Allow extras
Normally CLI11 throws an error if you don't match all items given on the command
line. However, you can enable `allow_extras()` to instead store the extra values
in `.remaining()`. You can get all remaining options including those in
contained subcommands recursively in the original order with `.remaining(true)`.
`.remaining_size()` is also provided; this counts the size but ignores the `--`
special separator if present.
### Fallthrough
Fallthrough allows an option that does not match in a subcommand to "fall
through" to the parent command; if that parent allows that option, it matches
there instead. This was added to allow CLI11 to represent models:
```term
gitbook:code $ ./my_program my_model_1 --model_flag --shared_flag
```
Here, `--shared_flag` was set on the main app, and on the command line it "falls
through" `my_model_1` to match on the main app.
### Prefix command
This is a special mode that allows "prefix" commands, where the parsing
completely stops when it gets to an unknown option. Further unknown options are
ignored, even if they could match. Git is the traditional example for prefix
commands; if you run git with an unknown subcommand, like "`git thing`", it then
calls another command called "`git-thing`" with the remaining options intact.
### Silent subcommands
Subcommands can be modified by using the `silent` option. This will prevent the
subcommand from showing up in the get_subcommands list. This can be used to make
subcommands into modifiers. For example, a help subcommand might look like
```c++
auto sub1 = app.add_subcommand("help")->silent();
sub1->parse_complete_callback([]() { throw CLI::CallForHelp(); });
```
This would allow calling help such as:
```bash
./app help
./app help sub1
```
### Positional Validation
Some arguments supplied on the command line may be legitamately applied to more
than 1 positional argument. In this context enabling `positional_validation` on
the application or subcommand will check any validators before applying the
command line argument to the positional option. It is not an error to fail
validation in this context, positional arguments not matching any validators
will go into the `extra_args` field which may generate an error depending on
settings.
### Optional Argument Validation
Similar to positional validation, there are occasional contexts in which case it
might be ambiguous whether an argument should be applied to an option or a
positional option.
```c++
std::vector<std::string> vec;
std::vector<int> ivec;
app.add_option("pos", vec);
app.add_option("--args", ivec)->check(CLI::Number);
app.validate_optional_arguments();
```
In this case a sequence of integers is expected for the argument and remaining
strings go to the positional string vector. Without the
`validate_optional_arguments()` active it would be impossible get any later
arguments into the positional if the `--args` option is used. The validator in
this context is used to make sure the optional arguments match with what the
argument is expecting and if not the `-args` option is closed, and remaining
arguments fall into the positional.

View File

@@ -0,0 +1,40 @@
# Using CLI11 in a Toolkit
CLI11 was designed to be integrate into a toolkit, providing a native experience
for users. This was used in GooFit to provide `GooFit::Application`, an class
designed to make ROOT users feel at home.
## Custom namespace
If you want to provide CLI11 in a custom namespace, you'll want to at least put
`using CLI::App` in your namespace. You can also include Option, some errors,
and validators. You can also put `using namespace CLI` inside your namespace to
import everything.
You may also want to make your own copy of the `CLI11_PARSE` macro. Something
like:
```cpp
#define MYPACKAGE_PARSE(app, argv, argc) \
try { \
app.parse(argv, argc); \
} catch(const CLI::ParseError &e) { \
return app.exit(e); \
}
```
## Subclassing App
If you subclass `App`, you'll just need to do a few things. You'll need a
constructor; calling the base `App` constructor is a good idea, but not
necessary (it just sets a description and adds a help flag.
You can call anything you would like to configure in the constructor, like
`option_defaults()->take_last()` or `fallthrough()`, and it will be set on all
user instances. You can add flags and options, as well.
## Virtual functions provided
You are given a few virtual functions that you can change (only on the main
App). `pre_callback` runs right before the callbacks run, letting you print out
custom messages at the top of your app.

View File

@@ -0,0 +1,66 @@
# Validators
There are two forms of validators:
- `transform` validators: mutating
- `check` validators: non-mutating (recommended unless the parsed string must be
mutated)
A transform validator comes in one form, a function with the signature
`std::string(std::string)`. The function will take a string and return the
modified version of the string. If there is an error, the function should throw
a `CLI::ValidationError` with the appropriate reason as a message.
However, `check` validators come in two forms; either a simple function with the
const version of the above signature, `std::string(const std::string &)`, or a
subclass of `struct CLI::Validator`. This structure has two members that a user
should set; one (`func_`) is the function to add to the Option (exactly matching
the above function signature, since it will become that function), and the other
is `name_`, and is the type name to set on the Option (unless empty, in which
case the typename will be left unchanged).
Validators can be combined with `&` and `|`, and they have an `operator()` so
that you can call them as if they were a function. In CLI11, const static
versions of the validators are provided so that the user does not have to call a
constructor also.
An example of a custom validator:
```cpp
struct LowerCaseValidator : public Validator {
LowerCaseValidator() {
name_ = "LOWER";
func_ = [](const std::string &str) {
if(CLI::detail::to_lower(str) != str)
return std::string("String is not lower case");
else
return std::string();
};
}
};
const static LowerCaseValidator Lowercase;
```
If you were not interested in the extra features of Validator, you could simply
pass the lambda function above to the `->check()` method of `Option`.
The built-in validators for CLI11 are:
| Validator | Description |
| ------------------- | ---------------------------------------------------------------------- |
| `ExistingFile` | Check for existing file (returns error message if check fails) |
| `ExistingDirectory` | Check for an existing directory (returns error message if check fails) |
| `ExistingPath` | Check for an existing path |
| `NonexistentPath` | Check for an non-existing path |
| `Range(min=0, max)` | Produce a range (factory). Min and max are inclusive. |
And, the protected members that you can set when you make your own are:
| Type | Member | Description |
| ------------------------------------------- | -------------------- | ---------------------------------------------------------------------- |
| `std::function<std::string(std::string &)>` | `func_` | Core validation function - modifies input and returns "" if successful |
| `std::function<std::string()>` | `desc_function` | Optional description function (uses `description_` instead if not set) |
| `std::string` | `name_` | The name for search purposes |
| `int` (`-1`) | `application_index_` | The element this validator applies to (-1 for all) |
| `bool` (`true`) | `active_` | This can be disabled |
| `bool` (`false`) | `non_modifying_` | Specify that this is a Validator instead of a Transformer |

View File

@@ -0,0 +1,32 @@
cmake_minimum_required(VERSION 3.11)
project(CLI11_Examples LANGUAGES CXX)
# Using CMake 3.11's ability to set imported interface targets
add_library(CLI11::CLI11 IMPORTED INTERFACE)
target_include_directories(CLI11::CLI11 INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/../../include")
target_compile_features(CLI11::CLI11 INTERFACE cxx_std_11)
# Add CTest
enable_testing()
# Quick function to add the base executable
function(add_cli_exe NAME)
add_executable(${NAME} ${NAME}.cpp)
target_link_libraries(${NAME} CLI11::CLI11)
endfunction()
add_cli_exe(simplest)
add_test(NAME simplest COMMAND simplest)
add_cli_exe(intro)
add_test(NAME intro COMMAND intro)
add_test(NAME intro_p COMMAND intro -p 5)
add_cli_exe(flags)
add_test(NAME flags COMMAND flags)
add_test(NAME flags_bip COMMAND flags -b -i -p)
add_cli_exe(geet)
add_test(NAME geet_add COMMAND geet add)
add_test(NAME geet_commit COMMAND geet commit -m "Test")

View File

@@ -0,0 +1,36 @@
#include "CLI/CLI.hpp"
#include <iostream>
int main(int argc, char **argv) {
using std::cout;
using std::endl;
CLI::App app{"Flag example program"};
/// [define]
bool flag_bool;
app.add_flag("--bool,-b", flag_bool, "This is a bool flag");
int flag_int;
app.add_flag("-i,--int", flag_int, "This is an int flag");
CLI::Option *flag_plain = app.add_flag("--plain,-p", "This is a plain flag");
/// [define]
/// [parser]
try {
app.parse(argc, argv);
} catch(const CLI::ParseError &e) {
return app.exit(e);
}
/// [parser]
/// [usage]
cout << "The flags program" << endl;
if(flag_bool)
cout << "Bool flag passed" << endl;
if(flag_int > 0)
cout << "Flag int: " << flag_int << endl;
if(*flag_plain)
cout << "Flag plain: " << flag_plain->count() << endl;
/// [usage]
}

View File

@@ -0,0 +1,50 @@
#include "CLI/CLI.hpp"
#include <iostream>
int main(int argc, char **argv) {
/// [Intro]
CLI::App app{"Geet, a command line git lookalike that does nothing"};
app.require_subcommand(1);
/// [Intro]
/// [Add]
auto add = app.add_subcommand("add", "Add file(s)");
bool add_update;
add->add_flag("-u,--update", add_update, "Add updated files only");
std::vector<std::string> add_files;
add->add_option("files", add_files, "Files to add");
add->callback([&]() {
std::cout << "Adding:";
if(add_files.empty()) {
if(add_update)
std::cout << " all updated files";
else
std::cout << " all files";
} else {
for(auto file : add_files)
std::cout << " " << file;
}
});
/// [Add]
/// [Commit]
auto commit = app.add_subcommand("commit", "Commit files");
std::string commit_message;
commit->add_option("-m,--message", commit_message, "A message")->required();
commit->callback([&]() { std::cout << "Commit message: " << commit_message; });
/// [Commit]
/// [Parse]
CLI11_PARSE(app, argc, argv);
std::cout << "\nThanks for using geet!\n" << std::endl;
return 0;
/// [Parse]
}

View File

@@ -0,0 +1,15 @@
#include "CLI/CLI.hpp"
#include <iostream>
int main(int argc, char **argv) {
CLI::App app{"App description"};
// Define options
int p = 0;
app.add_option("-p", p, "Parameter");
CLI11_PARSE(app, argc, argv);
std::cout << "Parameter value: " << p << std::endl;
return 0;
}

View File

@@ -0,0 +1,11 @@
#include "CLI/CLI.hpp"
int main(int argc, char **argv) {
CLI::App app;
// Add new options/flags here
CLI11_PARSE(app, argc, argv);
return 0;
}

View File

@@ -0,0 +1,9 @@
prefix=@CMAKE_INSTALL_PREFIX@
exec_prefix=${prefix}
includedir=${prefix}/include
Name: CLI11
Description: C++ command line parser
Version: @PROJECT_VERSION@
Cflags: -I${includedir}

View File

@@ -0,0 +1,13 @@
# Adapted from write_basic_package_version_file(... COMPATIBILITY AnyNewerVersion) output
# ARCH_INDEPENDENT is only present in cmake 3.14 and onwards
set(PACKAGE_VERSION "@VERSION_STRING@")
if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
set(PACKAGE_VERSION_COMPATIBLE FALSE)
else()
set(PACKAGE_VERSION_COMPATIBLE TRUE)
if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
set(PACKAGE_VERSION_EXACT TRUE)
endif()
endif()

View File

@@ -0,0 +1,3 @@
configure_file("cmake/CLI11.pc.in" "CLI11.pc" @ONLY)
install(FILES "${PROJECT_BINARY_DIR}/CLI11.pc" DESTINATION "${CMAKE_INSTALL_DATADIR}/pkgconfig")

View File

@@ -0,0 +1,243 @@
# Copyright (c) 2012 - 2017, Lars Bilke
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# CHANGES:
#
# 2012-01-31, Lars Bilke
# - Enable Code Coverage
#
# 2013-09-17, Joakim Söderberg
# - Added support for Clang.
# - Some additional usage instructions.
#
# 2016-02-03, Lars Bilke
# - Refactored functions to use named parameters
#
# 2017-06-02, Lars Bilke
# - Merged with modified version from github.com/ufz/ogs
#
#
# USAGE:
#
# 1. Copy this file into your cmake modules path.
#
# 2. Add the following line to your CMakeLists.txt:
# include(CodeCoverage)
#
# 3. Append necessary compiler flags:
# APPEND_COVERAGE_COMPILER_FLAGS()
#
# 4. If you need to exclude additional directories from the report, specify them
# using the COVERAGE_EXCLUDES variable before calling SETUP_TARGET_FOR_COVERAGE.
# Example:
# set(COVERAGE_EXCLUDES 'dir1/*' 'dir2/*')
#
# 5. Use the functions described below to create a custom make target which
# runs your test executable and produces a code coverage report.
#
# 6. Build a Debug build:
# cmake -DCMAKE_BUILD_TYPE=Debug ..
# make
# make my_coverage_target
#
include(CMakeParseArguments)
# Check prereqs
find_program(GCOV_PATH gcov)
find_program(LCOV_PATH NAMES lcov lcov.bat lcov.exe lcov.perl)
find_program(GENHTML_PATH NAMES genhtml genhtml.perl genhtml.bat)
find_program(GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/scripts/test)
find_program(SIMPLE_PYTHON_EXECUTABLE python)
if(NOT GCOV_PATH)
message(FATAL_ERROR "gcov not found! Aborting...")
endif() # NOT GCOV_PATH
if("${CMAKE_CXX_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang")
if("${CMAKE_CXX_COMPILER_VERSION}" VERSION_LESS 3)
message(FATAL_ERROR "Clang version must be 3.0.0 or greater! Aborting...")
endif()
elseif(NOT CMAKE_COMPILER_IS_GNUCXX)
message(FATAL_ERROR "Compiler is not GNU gcc! Aborting...")
endif()
set(COVERAGE_COMPILER_FLAGS
"-g -O0 --coverage -fprofile-arcs -ftest-coverage -fno-inline -fno-inline-small-functions -fno-default-inline"
CACHE INTERNAL "")
set(CMAKE_CXX_FLAGS_COVERAGE
${COVERAGE_COMPILER_FLAGS}
CACHE STRING "Flags used by the C++ compiler during coverage builds." FORCE)
set(CMAKE_C_FLAGS_COVERAGE
${COVERAGE_COMPILER_FLAGS}
CACHE STRING "Flags used by the C compiler during coverage builds." FORCE)
set(CMAKE_EXE_LINKER_FLAGS_COVERAGE
""
CACHE STRING "Flags used for linking binaries during coverage builds." FORCE)
set(CMAKE_SHARED_LINKER_FLAGS_COVERAGE
""
CACHE STRING "Flags used by the shared libraries linker during coverage builds." FORCE)
mark_as_advanced(CMAKE_CXX_FLAGS_COVERAGE CMAKE_C_FLAGS_COVERAGE CMAKE_EXE_LINKER_FLAGS_COVERAGE
CMAKE_SHARED_LINKER_FLAGS_COVERAGE)
if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
message(WARNING "Code coverage results with an optimised (non-Debug) build may be misleading")
endif() # NOT CMAKE_BUILD_TYPE STREQUAL "Debug"
if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
link_libraries(gcov)
else()
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --coverage")
endif()
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# SETUP_TARGET_FOR_COVERAGE(
# NAME testrunner_coverage # New target name
# EXECUTABLE testrunner -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES testrunner # Dependencies to build first
# )
function(SETUP_TARGET_FOR_COVERAGE)
set(options NONE)
set(oneValueArgs NAME)
set(multiValueArgs EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT LCOV_PATH)
message(FATAL_ERROR "lcov not found! Aborting...")
endif() # NOT LCOV_PATH
if(NOT GENHTML_PATH)
message(FATAL_ERROR "genhtml not found! Aborting...")
endif() # NOT GENHTML_PATH
# Setup target
add_custom_target(
${Coverage_NAME}
# Cleanup lcov
COMMAND ${LCOV_PATH} --directory . --zerocounters
# Create baseline to make sure untouched files show up in the report
COMMAND ${LCOV_PATH} -c -i -d . -o ${Coverage_NAME}.base
# Run tests
COMMAND ${Coverage_EXECUTABLE}
# Capturing lcov counters and generating report
COMMAND ${LCOV_PATH} --directory . --capture --output-file ${Coverage_NAME}.info
# add baseline counters
COMMAND ${LCOV_PATH} -a ${Coverage_NAME}.base -a ${Coverage_NAME}.info --output-file
${Coverage_NAME}.total
COMMAND ${LCOV_PATH} --remove ${Coverage_NAME}.total ${COVERAGE_EXCLUDES} --output-file
${PROJECT_BINARY_DIR}/${Coverage_NAME}.info.cleaned
COMMAND ${GENHTML_PATH} -o ${Coverage_NAME} ${PROJECT_BINARY_DIR}/${Coverage_NAME}.info.cleaned
COMMAND ${CMAKE_COMMAND} -E remove ${Coverage_NAME}.base ${Coverage_NAME}.total
${PROJECT_BINARY_DIR}/${Coverage_NAME}.info.cleaned
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
COMMENT
"Resetting code coverage counters to zero.\nProcessing code coverage counters and generating report."
)
# Show where to find the lcov info report
add_custom_command(
TARGET ${Coverage_NAME}
POST_BUILD
COMMAND ;
COMMENT "Lcov code coverage info report saved in ${Coverage_NAME}.info.")
# Show info where to find the report
add_custom_command(
TARGET ${Coverage_NAME}
POST_BUILD
COMMAND ;
COMMENT "Open ./${Coverage_NAME}/index.html in your browser to view the coverage report.")
endfunction() # SETUP_TARGET_FOR_COVERAGE
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# SETUP_TARGET_FOR_COVERAGE_COBERTURA(
# NAME ctest_coverage # New target name
# EXECUTABLE ctest -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES executable_target # Dependencies to build first
# )
function(SETUP_TARGET_FOR_COVERAGE_COBERTURA)
set(options NONE)
set(oneValueArgs NAME)
set(multiValueArgs EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT SIMPLE_PYTHON_EXECUTABLE)
message(FATAL_ERROR "python not found! Aborting...")
endif() # NOT SIMPLE_PYTHON_EXECUTABLE
if(NOT GCOVR_PATH)
message(FATAL_ERROR "gcovr not found! Aborting...")
endif() # NOT GCOVR_PATH
# Combine excludes to several -e arguments
set(COBERTURA_EXCLUDES "")
foreach(EXCLUDE ${COVERAGE_EXCLUDES})
set(COBERTURA_EXCLUDES "-e ${EXCLUDE} ${COBERTURA_EXCLUDES}")
endforeach()
add_custom_target(
${Coverage_NAME}
# Run tests
${Coverage_EXECUTABLE}
# Running gcovr
COMMAND ${GCOVR_PATH} -x -r ${CMAKE_SOURCE_DIR} ${COBERTURA_EXCLUDES} -o ${Coverage_NAME}.xml
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
COMMENT "Running gcovr to produce Cobertura code coverage report.")
# Show info where to find the report
add_custom_command(
TARGET ${Coverage_NAME}
POST_BUILD
COMMAND ;
COMMENT "Cobertura code coverage report saved in ${Coverage_NAME}.xml.")
endfunction() # SETUP_TARGET_FOR_COVERAGE_COBERTURA
function(APPEND_COVERAGE_COMPILER_FLAGS)
set(CMAKE_C_FLAGS
"${CMAKE_C_FLAGS} ${COVERAGE_COMPILER_FLAGS}"
PARENT_SCOPE)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} ${COVERAGE_COMPILER_FLAGS}"
PARENT_SCOPE)
message(STATUS "Appending code coverage compiler flags: ${COVERAGE_COMPILER_FLAGS}")
endfunction() # APPEND_COVERAGE_COMPILER_FLAGS

48
libs/CLI11/conanfile.py Normal file
View File

@@ -0,0 +1,48 @@
from conans import ConanFile, CMake
from conans.tools import load, cross_building
import re
def get_version():
try:
content = load("include/CLI/Version.hpp")
version = re.search(r'#define CLI11_VERSION "(.*)"', content).group(1)
return version
except Exception:
return None
class CLI11Conan(ConanFile):
name = "CLI11"
version = get_version()
description = "Command Line Interface toolkit for C++11"
topics = ("cli", "c++11", "parser", "cli11")
url = "https://github.com/CLIUtils/CLI11"
homepage = "https://github.com/CLIUtils/CLI11"
author = "Henry Schreiner <hschrein@cern.ch>"
license = "BSD-3-Clause"
settings = "os", "compiler", "arch", "build_type"
exports_sources = (
"LICENSE",
"README.md",
"include/*",
"extern/*",
"cmake/*",
"CMakeLists.txt",
"CLI11.CPack.Description.txt",
"tests/*",
)
def build(self): # this is not building a library, just tests
cmake = CMake(self)
cmake.definitions["CLI11_EXAMPLES"] = "OFF"
cmake.definitions["CLI11_SINGLE_FILE"] = "OFF"
cmake.configure()
cmake.build()
if not cross_building(self.settings):
cmake.test()
cmake.install()
def package_id(self):
self.info.header_only()

2
libs/CLI11/docs/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
/html/*
/latex/*

114
libs/CLI11/docs/CLI11.svg Normal file
View File

@@ -0,0 +1,114 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="34.342606mm"
height="15.300875mm"
viewBox="0 0 34.342606 15.300875"
version="1.1"
id="svg8"
inkscape:version="0.92.2 (unknown)"
sodipodi:docname="CLI11.svg"
inkscape:export-filename="/data/CLI11_300.png"
inkscape:export-xdpi="222.62143"
inkscape:export-ydpi="222.62143">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="11.206433"
inkscape:cx="93.996945"
inkscape:cy="15.843961"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:window-width="2560"
inkscape:window-height="1347"
inkscape:window-x="0"
inkscape:window-y="1"
inkscape:window-maximized="1"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-53.018986,-23.9019)">
<g
id="g4602"
transform="rotate(-0.28559572,70.190289,31.552338)">
<path
inkscape:connector-curvature="0"
id="path3732"
transform="scale(0.26458333)"
d="m 233.33789,90.337891 -32.95117,28.619139 31.94726,28.91406 64.9004,0.29688 32.95117,-28.61914 -31.94727,-28.914064 z"
style="fill:#008080;stroke-width:0.54128456" />
<path
inkscape:connector-curvature="0"
style="fill:none;stroke:#ffffff;stroke-width:0.3148967;stroke-miterlimit:4;stroke-dasharray:none"
d="m 62.120274,24.413292 -8.32335,7.065988 8.069765,7.138804 16.393615,0.0733 8.32335,-7.065988 -8.069768,-7.138806 z"
id="path3774" />
</g>
<g
id="g4609"
transform="translate(-0.43472687)">
<path
inkscape:transform-center-y="0.00020894337"
inkscape:transform-center-x="0.0229185"
inkscape:connector-curvature="0"
id="path3730"
d="m 60.964519,27.804182 c 0.886395,-0.348655 1.859691,-0.390207 2.74248,-0.111952 0.651274,0.210103 1.042699,0.454066 1.576252,0.972044 l -1.506657,0.592635 c -0.744252,-0.446473 -1.423964,-0.497745 -2.270962,-0.164583 -0.738662,0.290549 -1.26082,0.814436 -1.498695,1.510755 -0.203801,0.580557 -0.182185,1.300104 0.05025,1.891033 0.534609,1.359137 2.079298,2.048044 3.418738,1.521183 0.699266,-0.275052 1.11846,-0.713017 1.465328,-1.565931 l 1.585527,-0.623658 c -0.04824,1.554281 -1.023053,2.892949 -2.510224,3.47792 -2.127345,0.836779 -4.497206,-0.187252 -5.322363,-2.28505 -0.809661,-2.058401 0.211919,-4.404734 2.270322,-5.214396 z"
style="fill:#ffffff;stroke-width:0.14321487" />
<path
inkscape:connector-curvature="0"
id="path3728"
transform="scale(0.26458333)"
d="m 253.49609,104.47266 h 5.48047 v 24.32031 h 9.03906 v 5.24023 h -14.51953 z"
style="fill:#ffffff;stroke-width:0.54128456" />
<path
inkscape:connector-curvature="0"
id="path3726"
transform="scale(0.26458333)"
d="m 271.07422,104.47266 h 5.48047 v 29.56054 h -5.48047 z"
style="fill:#ffffff;stroke-width:0.54128456" />
<path
inkscape:connector-curvature="0"
id="path3724"
transform="scale(0.26458333)"
d="m 294.68555,104.47266 v 29.56054 h -5.32032 v -24.56054 h -3.71875 z"
style="fill:#ffffff;stroke-width:0.54128456" />
<path
inkscape:connector-curvature="0"
id="path3705"
transform="scale(0.26458333)"
d="m 305.76758,104.47266 v 29.56054 h -5.32031 v -24.56054 h -3.71875 z"
style="fill:#ffffff;stroke-width:0.54128456" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

View File

@@ -0,0 +1,11 @@
set(DOXYGEN_EXTRACT_ALL YES)
set(DOXYGEN_BUILTIN_STL_SUPPORT YES)
set(PROJECT_BRIEF "C++11 Command Line Interface Parser")
file(
GLOB DOC_LIST
RELATIVE "${PROJECT_SOURCE_DIR}/include"
"${PROJECT_SOURCE_DIR}/include/CLI/*.hpp")
doxygen_add_docs(docs ${DOC_LIST} "${CMAKE_CURRENT_SOURCE_DIR}/mainpage.md"
WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}/include")

2475
libs/CLI11/docs/Doxyfile Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,24 @@
# Introduction {#mainpage}
This is the Doxygen API documentation for CLI11 parser. There is a friendly
introduction to CLI11 on the [GitHub page](https://github.com/CLIUtils/CLI11),
and [a tutorial series](https://cliutils.github.io/CLI11/book/).
The main classes are:
| Name | Where used |
| -------------- | --------------------------------------------------------- |
| CLI::Option | Options, stored in the app |
| CLI::App | The main application or subcommands |
| CLI::Validator | A check that can affect the type name |
| CLI::Formatter | A subclassable formatter for help printing |
| CLI::ExitCode | A scoped enum with exit codes |
| CLI::Timer | A timer class, only in CLI/Timer.hpp (not in `CLI11.hpp`) |
| CLI::AutoTimer | A timer that prints on deletion |
Groups of related topics:
| Name | Description |
| -------------------- | ---------------------------------------------- |
| @ref error_group | Errors that can be thrown |
| @ref validator_group | Common validators used in CLI::Option::check() |

View File

@@ -0,0 +1,254 @@
function(add_cli_exe T)
add_executable(${T} ${ARGN} ${CLI11_headers})
target_link_libraries(${T} PUBLIC CLI11)
set_property(TARGET ${T} PROPERTY FOLDER "Examples")
if(CLI11_FORCE_LIBCXX)
set_property(
TARGET ${T}
APPEND_STRING
PROPERTY LINK_FLAGS -stdlib=libc++)
endif()
if(CLI11_CLANG_TIDY)
set_property(TARGET ${T} PROPERTY CXX_CLANG_TIDY "${DO_CLANG_TIDY}")
endif()
endfunction()
if(CLI11_BUILD_EXAMPLES_JSON)
message(STATUS "Using nlohmann/json")
FetchContent_Declare(
json
URL https://github.com/nlohmann/json/releases/download/v3.7.3/include.zip
URL_HASH "SHA256=87b5884741427220d3a33df1363ae0e8b898099fbc59f1c451113f6732891014")
FetchContent_GetProperties(json)
if(NOT json_POPULATED)
FetchContent_Populate(json)
endif()
add_cli_exe(json json.cpp)
target_include_directories(json PUBLIC SYSTEM "${json_SOURCE_DIR}/single_include")
add_test(NAME json_config_out COMMAND json --item 2)
set_property(TEST json_config_out PROPERTY PASS_REGULAR_EXPRESSION [[{]] [["item": "2"]]
[["simple": false]] [[}]])
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/input.json" [=[{"item":3,"simple":false}]=])
add_test(NAME json_config_in COMMAND json --config "${CMAKE_CURRENT_BINARY_DIR}/input.json")
set_property(TEST json_config_in PROPERTY PASS_REGULAR_EXPRESSION [[{]] [["item": "3"]]
[["simple": false]] [[}]])
endif()
add_cli_exe(simple simple.cpp)
add_test(NAME simple_basic COMMAND simple)
add_test(NAME simple_all COMMAND simple -f filename.txt -c 12 --flag --flag -d 1.2)
set_property(
TEST simple_all
PROPERTY PASS_REGULAR_EXPRESSION "Working on file: filename.txt, direct count: 1, opt count: 1"
"Working on count: 12, direct count: 1, opt count: 1" "Received flag: 2 (2) times"
"Some value: 1.2")
add_test(NAME simple_version COMMAND simple --version)
set_property(TEST simple_version PROPERTY PASS_REGULAR_EXPRESSION "${CLI11_VERSION}")
add_cli_exe(subcommands subcommands.cpp)
add_test(NAME subcommands_none COMMAND subcommands)
set_property(TEST subcommands_none PROPERTY PASS_REGULAR_EXPRESSION "A subcommand is required")
add_test(
NAME subcommands_all
COMMAND subcommands --random start --file
name stop --count)
set_property(
TEST subcommands_all
PROPERTY PASS_REGULAR_EXPRESSION "Working on --file from start: name"
"Working on --count from stop: 1, direct count: 1" "Count of --random flag: 1"
"Subcommand: start" "Subcommand: stop")
add_cli_exe(subcom_partitioned subcom_partitioned.cpp)
add_test(NAME subcom_partitioned_none COMMAND subcom_partitioned)
set_property(
TEST subcom_partitioned_none
PROPERTY PASS_REGULAR_EXPRESSION "This is a timer:" "--file is required"
"Run with --help for more information.")
add_test(NAME subcom_partitioned_all COMMAND subcom_partitioned --file this --count --count -d 1.2)
set_property(
TEST subcom_partitioned_all
PROPERTY PASS_REGULAR_EXPRESSION "This is a timer:"
"Working on file: this, direct count: 1, opt count: 1"
"Working on count: 2, direct count: 2, opt count: 2" "Some value: 1.2")
# test shows that the help prints out for unnamed subcommands
add_test(NAME subcom_partitioned_help COMMAND subcom_partitioned --help)
set_property(TEST subcom_partitioned_help PROPERTY PASS_REGULAR_EXPRESSION
"-f,--file TEXT REQUIRED" "-d,--double FLOAT")
####################################################
add_cli_exe(config_app config_app.cpp)
add_test(NAME config_app1 COMMAND config_app -p)
set_property(TEST config_app1 PROPERTY PASS_REGULAR_EXPRESSION "file=")
add_test(NAME config_app2 COMMAND config_app -p -f /)
set_property(TEST config_app2 PROPERTY PASS_REGULAR_EXPRESSION "file=\"/\"")
add_test(NAME config_app3 COMMAND config_app -f "" -p)
set_property(TEST config_app3 PROPERTY PASS_REGULAR_EXPRESSION "file=\"\"")
add_test(NAME config_app4 COMMAND config_app -f "/" -p)
set_property(TEST config_app4 PROPERTY PASS_REGULAR_EXPRESSION "file=\"/\"")
####################################################
add_cli_exe(option_groups option_groups.cpp)
add_test(NAME option_groups_missing COMMAND option_groups)
set_property(TEST option_groups_missing PROPERTY PASS_REGULAR_EXPRESSION "Exactly 1 option from"
"is required")
add_test(NAME option_groups_extra COMMAND option_groups --csv --binary)
set_property(TEST option_groups_extra PROPERTY PASS_REGULAR_EXPRESSION "and 2 were given")
add_test(NAME option_groups_extra2 COMMAND option_groups --csv --address "192.168.1.1" -o
"test.out")
set_property(TEST option_groups_extra2 PROPERTY PASS_REGULAR_EXPRESSION "at most 1")
add_cli_exe(positional_arity positional_arity.cpp)
add_test(NAME positional_arity1 COMMAND positional_arity one)
set_property(TEST positional_arity1 PROPERTY PASS_REGULAR_EXPRESSION "File 1 = one")
add_test(NAME positional_arity2 COMMAND positional_arity one two)
set_property(TEST positional_arity2 PROPERTY PASS_REGULAR_EXPRESSION "File 1 = one" "File 2 = two")
add_test(NAME positional_arity3 COMMAND positional_arity 1 2 one)
set_property(TEST positional_arity3 PROPERTY PASS_REGULAR_EXPRESSION "File 1 = one")
add_test(NAME positional_arity_fail COMMAND positional_arity 1 one two)
set_property(TEST positional_arity_fail PROPERTY PASS_REGULAR_EXPRESSION "Could not convert")
add_cli_exe(positional_validation positional_validation.cpp)
add_test(NAME positional_validation1 COMMAND positional_validation one)
set_property(TEST positional_validation1 PROPERTY PASS_REGULAR_EXPRESSION "File 1 = one")
add_test(NAME positional_validation2 COMMAND positional_validation one 1 2 two)
set_property(TEST positional_validation2 PROPERTY PASS_REGULAR_EXPRESSION "File 1 = one"
"File 2 = two")
add_test(NAME positional_validation3 COMMAND positional_validation 1 2 one)
set_property(TEST positional_validation3 PROPERTY PASS_REGULAR_EXPRESSION "File 1 = one")
add_test(NAME positional_validation4 COMMAND positional_validation 1 one two 2)
set_property(TEST positional_validation4 PROPERTY PASS_REGULAR_EXPRESSION "File 1 = one"
"File 2 = two")
add_cli_exe(shapes shapes.cpp)
add_test(NAME shapes_all COMMAND shapes circle 4.4 circle 10.7 rectangle 4 4 circle 2.3 triangle
4.5 ++ rectangle 2.1 ++ circle 234.675)
set_property(
TEST shapes_all PROPERTY PASS_REGULAR_EXPRESSION "circle2" "circle4"
"rectangle2 with edges [2.1,2.1]" "triangel1 with sides [4.5]")
add_cli_exe(ranges ranges.cpp)
add_test(NAME ranges_range COMMAND ranges --range 1 2 3)
set_property(TEST ranges_range PROPERTY PASS_REGULAR_EXPRESSION "[2:1:3]")
add_test(NAME ranges_minmax COMMAND ranges --min 2 --max 3)
set_property(TEST ranges_minmax PROPERTY PASS_REGULAR_EXPRESSION "[2:1:3]")
add_test(NAME ranges_error COMMAND ranges --min 2 --max 3 --step 1 --range 1 2 3)
set_property(TEST ranges_error PROPERTY PASS_REGULAR_EXPRESSION "Exactly 1 option from")
add_cli_exe(validators validators.cpp)
add_test(NAME validators_help COMMAND validators --help)
set_property(
TEST validators_help
PROPERTY PASS_REGULAR_EXPRESSION " -f,--file TEXT:FILE[\\r\\n\\t ]+File name"
" -v,--value INT:INT in [3 - 6][\\r\\n\\t ]+Value in range")
add_test(NAME validators_file COMMAND validators --file nonex.xxx)
set_property(
TEST validators_file PROPERTY PASS_REGULAR_EXPRESSION "--file: File does not exist: nonex.xxx"
"Run with --help for more information.")
add_test(NAME validators_plain COMMAND validators --value 9)
set_property(
TEST validators_plain PROPERTY PASS_REGULAR_EXPRESSION "--value: Value 9 not in range 3 to 6"
"Run with --help for more information.")
add_cli_exe(groups groups.cpp)
add_test(NAME groups_none COMMAND groups)
set_property(
TEST groups_none PROPERTY PASS_REGULAR_EXPRESSION "This is a timer:" "--file is required"
"Run with --help for more information.")
add_test(NAME groups_all COMMAND groups --file this --count --count -d 1.2)
set_property(
TEST groups_all
PROPERTY PASS_REGULAR_EXPRESSION "This is a timer:"
"Working on file: this, direct count: 1, opt count: 1"
"Working on count: 2, direct count: 2, opt count: 2" "Some value: 1.2")
add_cli_exe(inter_argument_order inter_argument_order.cpp)
add_test(NAME inter_argument_order COMMAND inter_argument_order --foo 1 2 3 --x --bar 4 5 6 --z
--foo 7 8)
set_property(
TEST inter_argument_order
PROPERTY
PASS_REGULAR_EXPRESSION
[=[foo : 1
foo : 2
foo : 3
bar : 4
bar : 5
bar : 6
foo : 7
foo : 8]=])
add_cli_exe(prefix_command prefix_command.cpp)
add_test(NAME prefix_command COMMAND prefix_command -v 3 2 1 -- other one two 3)
set_property(TEST prefix_command PROPERTY PASS_REGULAR_EXPRESSION "Prefix: 3 : 2 : 1"
"Remaining commands: other one two 3")
add_cli_exe(callback_passthrough callback_passthrough.cpp)
add_test(NAME callback_passthrough1 COMMAND callback_passthrough --argname t2 --t2 test)
set_property(TEST callback_passthrough1 PROPERTY PASS_REGULAR_EXPRESSION "the value is now test")
add_test(NAME callback_passthrough2 COMMAND callback_passthrough --arg EEEK --argname arg)
set_property(TEST callback_passthrough2 PROPERTY PASS_REGULAR_EXPRESSION "the value is now EEEK")
add_cli_exe(enum enum.cpp)
add_test(NAME enum_pass COMMAND enum -l 1)
add_test(NAME enum_fail COMMAND enum -l 4)
set_property(TEST enum_fail PROPERTY PASS_REGULAR_EXPRESSION "--level: Check 4 value in {"
"FAILED")
add_cli_exe(enum_ostream enum_ostream.cpp)
add_test(NAME enum_ostream_pass COMMAND enum_ostream --level medium)
set_property(TEST enum_ostream_pass PROPERTY PASS_REGULAR_EXPRESSION "Enum received: Medium")
add_cli_exe(digit_args digit_args.cpp)
add_test(NAME digit_args COMMAND digit_args -h)
set_property(TEST digit_args PROPERTY PASS_REGULAR_EXPRESSION "-3{3}")
add_cli_exe(modhelp modhelp.cpp)
add_test(NAME modhelp COMMAND modhelp -a test -h)
set_property(TEST modhelp PROPERTY PASS_REGULAR_EXPRESSION "Option -a string in help: test")
add_subdirectory(subcom_in_files)
add_test(NAME subcom_in_files COMMAND subcommand_main subcommand_a -f this.txt --with-foo)
set_property(TEST subcom_in_files PROPERTY PASS_REGULAR_EXPRESSION "Working on file: this\.txt"
"Using foo!")
add_cli_exe(formatter formatter.cpp)
add_cli_exe(nested nested.cpp)
add_cli_exe(subcom_help subcom_help.cpp)
add_test(NAME subcom_help_normal COMMAND subcom_help sub --help)
add_test(NAME subcom_help_reversed COMMAND subcom_help --help sub)
add_cli_exe(retired retired.cpp)
add_test(NAME retired_retired_test COMMAND retired --retired_option)
add_test(NAME retired_retired_test2 COMMAND retired --retired_option 567)
add_test(NAME retired_retired_test3 COMMAND retired --retired_option2 567 689 789)
add_test(NAME retired_deprecated COMMAND retired --deprecate 19 20)
set_property(TEST retired_retired_test PROPERTY PASS_REGULAR_EXPRESSION "WARNING.*retired")
set_property(TEST retired_retired_test2 PROPERTY PASS_REGULAR_EXPRESSION "WARNING.*retired")
set_property(TEST retired_retired_test3 PROPERTY PASS_REGULAR_EXPRESSION "WARNING.*retired")
set_property(TEST retired_deprecated PROPERTY PASS_REGULAR_EXPRESSION "deprecated.*not_deprecated")
#--------------------------------------------
add_cli_exe(custom_parse custom_parse.cpp)
add_test(NAME cp_test COMMAND custom_parse --dv 1.7)
set_property(TEST cp_test PROPERTY PASS_REGULAR_EXPRESSION "called correct")
#------------------------------------------------
# This executable is for manual testing and is expected to change regularly
add_cli_exe(tester testEXE.cpp)

View File

@@ -0,0 +1,28 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <string>
int main(int argc, char **argv) {
CLI::App app("callback_passthrough");
app.allow_extras();
std::string argName;
std::string val;
app.add_option("--argname", argName, "the name of the custom command line argument");
app.callback([&app, &val, &argName]() {
if(!argName.empty()) {
CLI::App subApp;
subApp.add_option("--" + argName, val, "custom argument option");
subApp.parse(app.remaining_for_passthrough());
}
});
CLI11_PARSE(app, argc, argv);
std::cout << "the value is now " << val << '\n';
}

View File

@@ -0,0 +1,50 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <string>
int main(int argc, char **argv) {
CLI::App app("configuration print example");
app.add_flag("-p,--print", "Print configuration and exit")->configurable(false); // NEW: print flag
std::string file;
CLI::Option *opt = app.add_option("-f,--file,file", file, "File name")
->capture_default_str()
->run_callback_for_default(); // NEW: capture_default_str()
int count{0};
CLI::Option *copt =
app.add_option("-c,--count", count, "Counter")->capture_default_str(); // NEW: capture_default_str()
int v{0};
CLI::Option *flag = app.add_flag("--flag", v, "Some flag that can be passed multiple times")
->capture_default_str(); // NEW: capture_default_str()
double value{0.0}; // = 3.14;
app.add_option("-d,--double", value, "Some Value")->capture_default_str(); // NEW: capture_default_str()
app.get_config_formatter_base()->quoteCharacter('"', '"');
CLI11_PARSE(app, argc, argv);
if(app.get_option("--print")->as<bool>()) { // NEW: print configuration and exit
std::cout << app.config_to_str(true, false);
return 0;
}
std::cout << "Working on file: " << file << ", direct count: " << app.count("--file")
<< ", opt count: " << opt->count() << std::endl;
std::cout << "Working on count: " << count << ", direct count: " << app.count("--count")
<< ", opt count: " << copt->count() << std::endl;
std::cout << "Received flag: " << v << " (" << flag->count() << ") times\n";
std::cout << "Some value: " << value << std::endl;
return 0;
}

View File

@@ -0,0 +1,39 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
// from Issue #566 on github https://github.com/CLIUtils/CLI11/issues/566
#include <CLI/CLI.hpp>
#include <iostream>
#include <sstream>
// example file to demonstrate a custom lexical cast function
template <class T = int> struct Values {
T a;
T b;
T c;
};
// in C++20 this is constructible from a double due to the new aggregate initialization in C++20.
using DoubleValues = Values<double>;
// the lexical cast operator should be in the same namespace as the type for ADL to work properly
bool lexical_cast(const std::string &input, Values<double> &v) {
std::cout << "called correct lexical_cast function ! val: " << input << std::endl;
return true;
}
DoubleValues doubles;
void argparse(CLI::Option_group *group) { group->add_option("--dv", doubles)->default_str("0"); }
int main(int argc, char **argv) {
CLI::App app;
argparse(app.add_option_group("param"));
CLI11_PARSE(app, argc, argv);
return 0;
}

View File

@@ -0,0 +1,21 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
int main(int argc, char **argv) {
CLI::App app;
int val{0};
// add a set of flags with default values associate with them
app.add_flag("-1{1},-2{2},-3{3},-4{4},-5{5},-6{6}, -7{7}, -8{8}, -9{9}", val, "compression level");
CLI11_PARSE(app, argc, argv);
std::cout << "value = " << val << std::endl;
return 0;
}

View File

@@ -0,0 +1,33 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <map>
#include <string>
enum class Level : int { High, Medium, Low };
int main(int argc, char **argv) {
CLI::App app;
Level level{Level::Low};
// specify string->value mappings
std::map<std::string, Level> map{{"high", Level::High}, {"medium", Level::Medium}, {"low", Level::Low}};
// CheckedTransformer translates and checks whether the results are either in one of the strings or in one of the
// translations already
app.add_option("-l,--level", level, "Level settings")
->required()
->transform(CLI::CheckedTransformer(map, CLI::ignore_case));
CLI11_PARSE(app, argc, argv);
// CLI11's built in enum streaming can be used outside CLI11 like this:
using CLI::enums::operator<<;
std::cout << "Enum received: " << level << std::endl;
return 0;
}

View File

@@ -0,0 +1,50 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <map>
#include <string>
enum class Level : int { High, Medium, Low };
// Defining operator<<() for your enum class (in this case for 'Level') overrides CLI11's enum streaming
inline std::ostream &operator<<(std::ostream &os, const Level &level) {
switch(level) {
case Level::High:
os << "High";
break;
case Level::Medium:
os << "Medium";
break;
case Level::Low:
os << "Low";
break;
}
os << " (ft rom custom ostream)";
return os;
}
int main(int argc, char **argv) {
CLI::App app;
Level level{Level::Low};
// specify string->value mappings
std::map<std::string, Level> map{{"high", Level::High}, {"medium", Level::Medium}, {"low", Level::Low}};
// CheckedTransformer translates and checks whether the results are either in one of the strings or in one of the
// translations already
app.add_option("-l,--level", level, "Level settings")
->required()
->transform(CLI::CheckedTransformer(map, CLI::ignore_case));
CLI11_PARSE(app, argc, argv);
// CLI11's built in enum streaming can be used outside CLI11 like this:
using CLI::enums::operator<<;
std::cout << "Enum received: " << level << std::endl;
return 0;
}

View File

@@ -0,0 +1,37 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <memory>
class MyFormatter : public CLI::Formatter {
public:
MyFormatter() : Formatter() {}
std::string make_option_opts(const CLI::Option *) const override { return " OPTION"; }
};
int main(int argc, char **argv) {
CLI::App app;
app.set_help_all_flag("--help-all", "Show all help");
auto fmt = std::make_shared<MyFormatter>();
fmt->column_width(15);
app.formatter(fmt);
app.add_flag("--flag", "This is a flag");
auto sub1 = app.add_subcommand("one", "Description One");
sub1->add_flag("--oneflag", "Some flag");
auto sub2 = app.add_subcommand("two", "Description Two");
sub2->add_flag("--twoflag", "Some other flag");
CLI11_PARSE(app, argc, argv);
std::cout << "This app was meant to show off the formatter, run with -h" << std::endl;
return 0;
}

View File

@@ -0,0 +1,39 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <CLI/Timer.hpp>
#include <iostream>
#include <string>
int main(int argc, char **argv) {
CLI::AutoTimer("This is a timer");
CLI::App app("K3Pi goofit fitter");
std::string file;
CLI::Option *opt = app.add_option("-f,--file,file", file, "File name")->required()->group("Important");
int count{0};
CLI::Option *copt = app.add_flag("-c,--count", count, "Counter")->required()->group("Important");
double value{0.0}; // = 3.14;
app.add_option("-d,--double", value, "Some Value")->group("Other");
try {
app.parse(argc, argv);
} catch(const CLI::ParseError &e) {
return app.exit(e);
}
std::cout << "Working on file: " << file << ", direct count: " << app.count("--file")
<< ", opt count: " << opt->count() << std::endl;
std::cout << "Working on count: " << count << ", direct count: " << app.count("--count")
<< ", opt count: " << copt->count() << std::endl;
std::cout << "Some value: " << value << std::endl;
return 0;
}

View File

@@ -0,0 +1,51 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <algorithm>
#include <iostream>
#include <tuple>
#include <vector>
int main(int argc, char **argv) {
CLI::App app{"An app to practice mixing unlimited arguments, but still recover the original order."};
std::vector<int> foos;
auto foo = app.add_option("--foo,-f", foos, "Some unlimited argument");
std::vector<int> bars;
auto bar = app.add_option("--bar", bars, "Some unlimited argument");
app.add_flag("--z,--x", "Random other flags");
// Standard parsing lines (copy and paste in, or use CLI11_PARSE)
try {
app.parse(argc, argv);
} catch(const CLI::ParseError &e) {
return app.exit(e);
}
// I prefer using the back and popping
std::reverse(std::begin(foos), std::end(foos));
std::reverse(std::begin(bars), std::end(bars));
std::vector<std::pair<std::string, int>> keyval;
for(auto option : app.parse_order()) {
if(option == foo) {
keyval.emplace_back("foo", foos.back());
foos.pop_back();
}
if(option == bar) {
keyval.emplace_back("bar", bars.back());
bars.pop_back();
}
}
// Prove the vector is correct
for(auto &pair : keyval) {
std::cout << pair.first << " : " << pair.second << std::endl;
}
}

View File

@@ -0,0 +1,123 @@
// Copyright (c) 2017-2021, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <memory>
#include <nlohmann/json.hpp>
#include <string>
#include <vector>
// This example is only built on GCC 7 on Travis due to mismatch in stdlib
// for clang (CLI11 is forgiving about mismatches, json.hpp is not)
using nlohmann::json;
class ConfigJSON : public CLI::Config {
public:
std::string to_config(const CLI::App *app, bool default_also, bool, std::string) const override {
json j;
for(const CLI::Option *opt : app->get_options({})) {
// Only process option with a long-name and configurable
if(!opt->get_lnames().empty() && opt->get_configurable()) {
std::string name = opt->get_lnames()[0];
// Non-flags
if(opt->get_type_size() != 0) {
// If the option was found on command line
if(opt->count() == 1)
j[name] = opt->results().at(0);
else if(opt->count() > 1)
j[name] = opt->results();
// If the option has a default and is requested by optional argument
else if(default_also && !opt->get_default_str().empty())
j[name] = opt->get_default_str();
// Flag, one passed
} else if(opt->count() == 1) {
j[name] = true;
// Flag, multiple passed
} else if(opt->count() > 1) {
j[name] = opt->count();
// Flag, not present
} else if(opt->count() == 0 && default_also) {
j[name] = false;
}
}
}
for(const CLI::App *subcom : app->get_subcommands({}))
j[subcom->get_name()] = json(to_config(subcom, default_also, false, ""));
return j.dump(4);
}
std::vector<CLI::ConfigItem> from_config(std::istream &input) const override {
json j;
input >> j;
return _from_config(j);
}
std::vector<CLI::ConfigItem>
_from_config(json j, std::string name = "", std::vector<std::string> prefix = {}) const {
std::vector<CLI::ConfigItem> results;
if(j.is_object()) {
for(json::iterator item = j.begin(); item != j.end(); ++item) {
auto copy_prefix = prefix;
if(!name.empty())
copy_prefix.push_back(name);
auto sub_results = _from_config(*item, item.key(), copy_prefix);
results.insert(results.end(), sub_results.begin(), sub_results.end());
}
} else if(!name.empty()) {
results.emplace_back();
CLI::ConfigItem &res = results.back();
res.name = name;
res.parents = prefix;
if(j.is_boolean()) {
res.inputs = {j.get<bool>() ? "true" : "false"};
} else if(j.is_number()) {
std::stringstream ss;
ss << j.get<double>();
res.inputs = {ss.str()};
} else if(j.is_string()) {
res.inputs = {j.get<std::string>()};
} else if(j.is_array()) {
for(std::string ival : j)
res.inputs.push_back(ival);
} else {
throw CLI::ConversionError("Failed to convert " + name);
}
} else {
throw CLI::ConversionError("You must make all top level values objects in json!");
}
return results;
}
};
int main(int argc, char **argv) {
CLI::App app;
app.config_formatter(std::make_shared<ConfigJSON>());
int item;
app.add_flag("--simple");
app.add_option("--item", item);
app.set_config("--config");
CLI11_PARSE(app, argc, argv);
std::cout << app.config_to_str(true, true) << std::endl;
}

View File

@@ -0,0 +1,35 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <string>
int main(int argc, char **argv) {
CLI::App test{R"raw(Modify the help print so that argument values are accessible.
Note that this will not shortcut `->required` and other similar options.)raw"};
// Remove help flag because it shortcuts all processing
test.set_help_flag();
// Add custom flag that activates help
auto help = test.add_flag("-h,--help", "Request help");
std::string some_option;
test.add_option("-a", some_option, "Some description");
try {
test.parse(argc, argv);
if(*help)
throw CLI::CallForHelp();
} catch(const CLI::Error &e) {
std::cout << "Option -a string in help: " << some_option << std::endl;
return test.exit(e);
}
std::cout << "Option -a string: " << some_option << std::endl;
return 0;
}

View File

@@ -0,0 +1,30 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <string>
int main(int argc, char **argv) {
CLI::App app("Vision Application");
app.set_help_all_flag("--help-all", "Expand all help");
app.add_flag("--version", "Get version");
CLI::App *cameraApp = app.add_subcommand("camera", "Configure the app camera");
cameraApp->require_subcommand(0, 1); // 0 (default) or 1 camera
std::string mvcamera_config_file = "mvcamera_config.json";
CLI::App *mvcameraApp = cameraApp->add_subcommand("mvcamera", "MatrixVision Camera Configuration");
mvcameraApp->add_option("-c,--config", mvcamera_config_file, "Config filename")
->capture_default_str()
->check(CLI::ExistingFile);
std::string mock_camera_path;
CLI::App *mockcameraApp = cameraApp->add_subcommand("mock", "Mock Camera Configuration");
mockcameraApp->add_option("-p,--path", mock_camera_path, "Path")->required()->check(CLI::ExistingPath);
CLI11_PARSE(app, argc, argv);
}

View File

@@ -0,0 +1,46 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <string>
int main(int argc, char **argv) {
CLI::App app("data output specification");
app.set_help_all_flag("--help-all", "Expand all help");
auto format = app.add_option_group("output_format", "formatting type for output");
auto target = app.add_option_group("output target", "target location for the output");
bool csv{false};
bool human{false};
bool binary{false};
format->add_flag("--csv", csv, "specify the output in csv format");
format->add_flag("--human", human, "specify the output in human readable text format");
format->add_flag("--binary", binary, "specify the output in binary format");
// require one of the options to be selected
format->require_option(1);
std::string fileLoc;
std::string networkAddress;
target->add_option("-o,--file", fileLoc, "specify the file location of the output");
target->add_option("--address", networkAddress, "specify a network address to send the file");
// require at most one of the target options
target->require_option(0, 1);
CLI11_PARSE(app, argc, argv);
std::string format_type = (csv) ? std::string("CSV") : ((human) ? "human readable" : "binary");
std::cout << "Selected " << format_type << " format" << std::endl;
if(!fileLoc.empty()) {
std::cout << " sent to file " << fileLoc << std::endl;
} else if(!networkAddress.empty()) {
std::cout << " sent over network to " << networkAddress << std::endl;
} else {
std::cout << " sent to std::cout" << std::endl;
}
return 0;
}

View File

@@ -0,0 +1,46 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <string>
int main(int argc, char **argv) {
CLI::App app("test for positional arity");
auto numbers = app.add_option_group("numbers", "specify key numbers");
auto files = app.add_option_group("files", "specify files");
int num1{-1}, num2{-1};
numbers->add_option("num1", num1, "first number");
numbers->add_option("num2", num2, "second number");
std::string file1, file2;
files->add_option("file1", file1, "first file")->required();
files->add_option("file2", file2, "second file");
// set a pre parse callback that turns the numbers group on or off depending on the number of arguments
app.preparse_callback([numbers](std::size_t arity) {
if(arity <= 2) {
numbers->disabled();
} else {
numbers->disabled(false);
}
});
CLI11_PARSE(app, argc, argv);
if(num1 != -1)
std::cout << "Num1 = " << num1 << '\n';
if(num2 != -1)
std::cout << "Num2 = " << num2 << '\n';
std::cout << "File 1 = " << file1 << '\n';
if(!file2.empty()) {
std::cout << "File 2 = " << file2 << '\n';
}
return 0;
}

View File

@@ -0,0 +1,37 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <string>
int main(int argc, char **argv) {
CLI::App app("test for positional validation");
int num1{-1}, num2{-1};
app.add_option("num1", num1, "first number")->check(CLI::Number);
app.add_option("num2", num2, "second number")->check(CLI::Number);
std::string file1, file2;
app.add_option("file1", file1, "first file")->required();
app.add_option("file2", file2, "second file");
app.validate_positionals();
CLI11_PARSE(app, argc, argv);
if(num1 != -1)
std::cout << "Num1 = " << num1 << '\n';
if(num2 != -1)
std::cout << "Num2 = " << num2 << '\n';
std::cout << "File 1 = " << file1 << '\n';
if(!file2.empty()) {
std::cout << "File 2 = " << file2 << '\n';
}
return 0;
}

View File

@@ -0,0 +1,35 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char **argv) {
CLI::App app("Prefix command app");
app.prefix_command();
std::vector<int> vals;
app.add_option("--vals,-v", vals)->expected(-1);
CLI11_PARSE(app, argc, argv);
std::vector<std::string> more_comms = app.remaining();
std::cout << "Prefix";
for(int v : vals)
std::cout << ": " << v << " ";
std::cout << std::endl << "Remaining commands: ";
for(auto com : more_comms)
std::cout << com << " ";
std::cout << std::endl;
return 0;
}

View File

@@ -0,0 +1,41 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <vector>
int main(int argc, char **argv) {
CLI::App app{"App to demonstrate exclusionary option groups."};
std::vector<int> range;
app.add_option("--range,-R", range, "A range")->expected(-2);
auto ogroup = app.add_option_group("min_max_step", "set the min max and step");
int min{0}, max{0}, step{1};
ogroup->add_option("--min,-m", min, "The minimum")->required();
ogroup->add_option("--max,-M", max, "The maximum")->required();
ogroup->add_option("--step,-s", step, "The step")->capture_default_str();
app.require_option(1);
CLI11_PARSE(app, argc, argv);
if(!range.empty()) {
if(range.size() == 2) {
min = range[0];
max = range[1];
}
if(range.size() >= 3) {
step = range[0];
min = range[1];
max = range[2];
}
}
std::cout << "range is [" << min << ':' << step << ':' << max << "]\n";
return 0;
}

View File

@@ -0,0 +1,46 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <utility>
#include <vector>
// This example shows the usage of the retired and deprecated option helper methods
int main(int argc, char **argv) {
CLI::App app("example for retired/deprecated options");
std::vector<int> x;
auto opt1 = app.add_option("--retired_option2", x);
std::pair<int, int> y;
auto opt2 = app.add_option("--deprecate", y);
app.add_option("--not_deprecated", x);
// specify that a non-existing option is retired
CLI::retire_option(app, "--retired_option");
// specify that an existing option is retired and non-functional: this will replace the option with another that
// behaves the same but does nothing
CLI::retire_option(app, opt1);
// deprecate an existing option and specify the recommended replacement
CLI::deprecate_option(opt2, "--not_deprecated");
CLI11_PARSE(app, argc, argv);
if(!x.empty()) {
std::cout << "Retired option example: got --not_deprecated values:";
for(auto &xval : x) {
std::cout << xval << " ";
}
std::cout << '\n';
} else if(app.count_all() == 1) {
std::cout << "Retired option example: no arguments received\n";
}
return 0;
}

View File

@@ -0,0 +1,56 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <vector>
int main(int argc, char **argv) {
CLI::App app("load shapes");
app.set_help_all_flag("--help-all");
auto circle = app.add_subcommand("circle", "draw a circle")->immediate_callback();
double radius{0.0};
int circle_counter{0};
circle->callback([&radius, &circle_counter] {
++circle_counter;
std::cout << "circle" << circle_counter << " with radius " << radius << std::endl;
});
circle->add_option("radius", radius, "the radius of the circle")->required();
auto rect = app.add_subcommand("rectangle", "draw a rectangle")->immediate_callback();
double edge1{0.0};
double edge2{0.0};
int rect_counter{0};
rect->callback([&edge1, &edge2, &rect_counter] {
++rect_counter;
if(edge2 == 0) {
edge2 = edge1;
}
std::cout << "rectangle" << rect_counter << " with edges [" << edge1 << ',' << edge2 << "]" << std::endl;
edge2 = 0;
});
rect->add_option("edge1", edge1, "the first edge length of the rectangle")->required();
rect->add_option("edge2", edge2, "the second edge length of the rectangle");
auto tri = app.add_subcommand("triangle", "draw a rectangle")->immediate_callback();
std::vector<double> sides;
int tri_counter = 0;
tri->callback([&sides, &tri_counter] {
++tri_counter;
std::cout << "triangle" << tri_counter << " with sides [" << CLI::detail::join(sides) << "]" << std::endl;
});
tri->add_option("sides", sides, "the side lengths of the triangle");
CLI11_PARSE(app, argc, argv);
return 0;
}

View File

@@ -0,0 +1,38 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <string>
int main(int argc, char **argv) {
CLI::App app("K3Pi goofit fitter");
// add version output
app.set_version_flag("--version", std::string(CLI11_VERSION));
std::string file;
CLI::Option *opt = app.add_option("-f,--file,file", file, "File name");
int count{0};
CLI::Option *copt = app.add_option("-c,--count", count, "Counter");
int v{0};
CLI::Option *flag = app.add_flag("--flag", v, "Some flag that can be passed multiple times");
double value{0.0}; // = 3.14;
app.add_option("-d,--double", value, "Some Value");
CLI11_PARSE(app, argc, argv);
std::cout << "Working on file: " << file << ", direct count: " << app.count("--file")
<< ", opt count: " << opt->count() << std::endl;
std::cout << "Working on count: " << count << ", direct count: " << app.count("--count")
<< ", opt count: " << copt->count() << std::endl;
std::cout << "Received flag: " << v << " (" << flag->count() << ") times\n";
std::cout << "Some value: " << value << std::endl;
return 0;
}

View File

@@ -0,0 +1,21 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <string>
int main(int argc, char *argv[]) {
CLI::App cli_global{"Demo app"};
auto &cli_sub = *cli_global.add_subcommand("sub", "Some subcommand");
std::string sub_arg;
cli_sub.add_option("sub_arg", sub_arg, "Argument for subcommand")->required();
CLI11_PARSE(cli_global, argc, argv);
if(cli_sub) {
std::cout << "Got: " << sub_arg << std::endl;
}
return 0;
}

View File

@@ -0,0 +1 @@
add_cli_exe(subcommand_main subcommand_main.cpp subcommand_a.cpp subcommand_a.hpp)

View File

@@ -0,0 +1,37 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include "subcommand_a.hpp"
#include <iostream>
#include <memory>
/// Set up a subcommand and capture a shared_ptr to a struct that holds all its options.
/// The variables of the struct are bound to the CLI options.
/// We use a shared ptr so that the addresses of the variables remain for binding,
/// You could return the shared pointer if you wanted to access the values in main.
void setup_subcommand_a(CLI::App &app) {
// Create the option and subcommand objects.
auto opt = std::make_shared<SubcommandAOptions>();
auto sub = app.add_subcommand("subcommand_a", "performs subcommand a");
// Add options to sub, binding them to opt.
sub->add_option("-f,--file", opt->file, "File name")->required();
sub->add_flag("--with-foo", opt->with_foo, "Counter");
// Set the run function as callback to be called when this subcommand is issued.
sub->callback([opt]() { run_subcommand_a(*opt); });
}
/// The function that runs our code.
/// This could also simply be in the callback lambda itself,
/// but having a separate function is cleaner.
void run_subcommand_a(SubcommandAOptions const &opt) {
// Do stuff...
std::cout << "Working on file: " << opt.file << std::endl;
if(opt.with_foo) {
std::cout << "Using foo!" << std::endl;
}
}

View File

@@ -0,0 +1,23 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#pragma once
#include <CLI/CLI.hpp>
#include <string>
/// Collection of all options of Subcommand A.
struct SubcommandAOptions {
std::string file;
bool with_foo;
};
// We could manually make a few variables and use shared pointers for each; this
// is just done this way to be nicely organized
// Function declarations.
void setup_subcommand_a(CLI::App &app);
void run_subcommand_a(SubcommandAOptions const &opt);

View File

@@ -0,0 +1,26 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include "subcommand_a.hpp"
#include <CLI/CLI.hpp>
int main(int argc, char **argv) {
CLI::App app{"..."};
// Call the setup functions for the subcommands.
// They are kept alive by a shared pointer in the
// lambda function held by CLI11
setup_subcommand_a(app);
// Make sure we get at least one subcommand
app.require_subcommand();
// More setup if needed, i.e., other subcommands etc.
CLI11_PARSE(app, argc, argv);
return 0;
}

View File

@@ -0,0 +1,46 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <CLI/Timer.hpp>
#include <iostream>
#include <memory>
#include <string>
int main(int argc, char **argv) {
CLI::AutoTimer("This is a timer");
CLI::App app("K3Pi goofit fitter");
CLI::App_p impOpt = std::make_shared<CLI::App>("Important");
std::string file;
CLI::Option *opt = impOpt->add_option("-f,--file,file", file, "File name")->required();
int count{0};
CLI::Option *copt = impOpt->add_flag("-c,--count", count, "Counter")->required();
CLI::App_p otherOpt = std::make_shared<CLI::App>("Other");
double value{0.0}; // = 3.14;
otherOpt->add_option("-d,--double", value, "Some Value");
// add the subapps to the main one
app.add_subcommand(impOpt);
app.add_subcommand(otherOpt);
try {
app.parse(argc, argv);
} catch(const CLI::ParseError &e) {
return app.exit(e);
}
std::cout << "Working on file: " << file << ", direct count: " << impOpt->count("--file")
<< ", opt count: " << opt->count() << std::endl;
std::cout << "Working on count: " << count << ", direct count: " << impOpt->count("--count")
<< ", opt count: " << copt->count() << std::endl;
std::cout << "Some value: " << value << std::endl;
return 0;
}

View File

@@ -0,0 +1,35 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <string>
int main(int argc, char **argv) {
CLI::App app("K3Pi goofit fitter");
app.set_help_all_flag("--help-all", "Expand all help");
app.add_flag("--random", "Some random flag");
CLI::App *start = app.add_subcommand("start", "A great subcommand");
CLI::App *stop = app.add_subcommand("stop", "Do you really want to stop?");
app.require_subcommand(); // 1 or more
std::string file;
start->add_option("-f,--file", file, "File name");
CLI::Option *s = stop->add_flag("-c,--count", "Counter");
CLI11_PARSE(app, argc, argv);
std::cout << "Working on --file from start: " << file << std::endl;
std::cout << "Working on --count from stop: " << s->count() << ", direct count: " << stop->count("--count")
<< std::endl;
std::cout << "Count of --random flag: " << app.count("--random") << std::endl;
for(auto subcom : app.get_subcommands())
std::cout << "Subcommand: " << subcom->get_name() << std::endl;
return 0;
}

View File

@@ -0,0 +1,26 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
// Code modified from https://github.com/CLIUtils/CLI11/issues/559
#include <CLI/CLI.hpp>
#include <iostream>
#include <string>
int main(int argc, const char *argv[]) {
int logLevel{0};
CLI::App app{"Test App"};
app.add_option("-v", logLevel, "level");
auto subcom = app.add_subcommand("sub", "")->fallthrough();
subcom->preparse_callback([&app](size_t) { app.get_subcommand("sub")->add_option_group("group"); });
CLI11_PARSE(app, argc, argv);
std::cout << "level: " << logLevel << std::endl;
}

View File

@@ -0,0 +1,25 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#include <CLI/CLI.hpp>
#include <iostream>
#include <string>
int main(int argc, char **argv) {
CLI::App app("Validator checker");
std::string file;
app.add_option("-f,--file,file", file, "File name")->check(CLI::ExistingFile);
int count{0};
app.add_option("-v,--value", count, "Value in range")->check(CLI::Range(3, 6));
CLI11_PARSE(app, argc, argv);
std::cout << "Try printing help or failing the validator" << std::endl;
return 0;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,36 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#pragma once
// CLI Library includes
// Order is important for combiner script
#include "Version.hpp"
#include "Macros.hpp"
#include "StringTools.hpp"
#include "Error.hpp"
#include "TypeTools.hpp"
#include "Split.hpp"
#include "ConfigFwd.hpp"
#include "Validators.hpp"
#include "FormatterFwd.hpp"
#include "Option.hpp"
#include "App.hpp"
#include "Config.hpp"
#include "Formatter.hpp"

View File

@@ -0,0 +1,396 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#pragma once
// [CLI11:public_includes:set]
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
// [CLI11:public_includes:set]
#include "App.hpp"
#include "ConfigFwd.hpp"
#include "StringTools.hpp"
namespace CLI {
// [CLI11:config_hpp:verbatim]
namespace detail {
inline std::string convert_arg_for_ini(const std::string &arg, char stringQuote = '"', char characterQuote = '\'') {
if(arg.empty()) {
return std::string(2, stringQuote);
}
// some specifically supported strings
if(arg == "true" || arg == "false" || arg == "nan" || arg == "inf") {
return arg;
}
// floating point conversion can convert some hex codes, but don't try that here
if(arg.compare(0, 2, "0x") != 0 && arg.compare(0, 2, "0X") != 0) {
double val;
if(detail::lexical_cast(arg, val)) {
return arg;
}
}
// just quote a single non numeric character
if(arg.size() == 1) {
return std::string(1, characterQuote) + arg + characterQuote;
}
// handle hex, binary or octal arguments
if(arg.front() == '0') {
if(arg[1] == 'x') {
if(std::all_of(arg.begin() + 2, arg.end(), [](char x) {
return (x >= '0' && x <= '9') || (x >= 'A' && x <= 'F') || (x >= 'a' && x <= 'f');
})) {
return arg;
}
} else if(arg[1] == 'o') {
if(std::all_of(arg.begin() + 2, arg.end(), [](char x) { return (x >= '0' && x <= '7'); })) {
return arg;
}
} else if(arg[1] == 'b') {
if(std::all_of(arg.begin() + 2, arg.end(), [](char x) { return (x == '0' || x == '1'); })) {
return arg;
}
}
}
if(arg.find_first_of(stringQuote) == std::string::npos) {
return std::string(1, stringQuote) + arg + stringQuote;
} else {
return characterQuote + arg + characterQuote;
}
}
/// Comma separated join, adds quotes if needed
inline std::string ini_join(const std::vector<std::string> &args,
char sepChar = ',',
char arrayStart = '[',
char arrayEnd = ']',
char stringQuote = '"',
char characterQuote = '\'') {
std::string joined;
if(args.size() > 1 && arrayStart != '\0') {
joined.push_back(arrayStart);
}
std::size_t start = 0;
for(const auto &arg : args) {
if(start++ > 0) {
joined.push_back(sepChar);
if(isspace(sepChar) == 0) {
joined.push_back(' ');
}
}
joined.append(convert_arg_for_ini(arg, stringQuote, characterQuote));
}
if(args.size() > 1 && arrayEnd != '\0') {
joined.push_back(arrayEnd);
}
return joined;
}
inline std::vector<std::string> generate_parents(const std::string &section, std::string &name, char parentSeparator) {
std::vector<std::string> parents;
if(detail::to_lower(section) != "default") {
if(section.find(parentSeparator) != std::string::npos) {
parents = detail::split(section, parentSeparator);
} else {
parents = {section};
}
}
if(name.find(parentSeparator) != std::string::npos) {
std::vector<std::string> plist = detail::split(name, parentSeparator);
name = plist.back();
detail::remove_quotes(name);
plist.pop_back();
parents.insert(parents.end(), plist.begin(), plist.end());
}
// clean up quotes on the parents
for(auto &parent : parents) {
detail::remove_quotes(parent);
}
return parents;
}
/// assuming non default segments do a check on the close and open of the segments in a configItem structure
inline void
checkParentSegments(std::vector<ConfigItem> &output, const std::string &currentSection, char parentSeparator) {
std::string estring;
auto parents = detail::generate_parents(currentSection, estring, parentSeparator);
if(!output.empty() && output.back().name == "--") {
std::size_t msize = (parents.size() > 1U) ? parents.size() : 2;
while(output.back().parents.size() >= msize) {
output.push_back(output.back());
output.back().parents.pop_back();
}
if(parents.size() > 1) {
std::size_t common = 0;
std::size_t mpair = (std::min)(output.back().parents.size(), parents.size() - 1);
for(std::size_t ii = 0; ii < mpair; ++ii) {
if(output.back().parents[ii] != parents[ii]) {
break;
}
++common;
}
if(common == mpair) {
output.pop_back();
} else {
while(output.back().parents.size() > common + 1) {
output.push_back(output.back());
output.back().parents.pop_back();
}
}
for(std::size_t ii = common; ii < parents.size() - 1; ++ii) {
output.emplace_back();
output.back().parents.assign(parents.begin(), parents.begin() + static_cast<std::ptrdiff_t>(ii) + 1);
output.back().name = "++";
}
}
} else if(parents.size() > 1) {
for(std::size_t ii = 0; ii < parents.size() - 1; ++ii) {
output.emplace_back();
output.back().parents.assign(parents.begin(), parents.begin() + static_cast<std::ptrdiff_t>(ii) + 1);
output.back().name = "++";
}
}
// insert a section end which is just an empty items_buffer
output.emplace_back();
output.back().parents = std::move(parents);
output.back().name = "++";
}
} // namespace detail
inline std::vector<ConfigItem> ConfigBase::from_config(std::istream &input) const {
std::string line;
std::string currentSection = "default";
std::string previousSection = "default";
std::vector<ConfigItem> output;
bool isDefaultArray = (arrayStart == '[' && arrayEnd == ']' && arraySeparator == ',');
bool isINIArray = (arrayStart == '\0' || arrayStart == ' ') && arrayStart == arrayEnd;
bool inSection{false};
char aStart = (isINIArray) ? '[' : arrayStart;
char aEnd = (isINIArray) ? ']' : arrayEnd;
char aSep = (isINIArray && arraySeparator == ' ') ? ',' : arraySeparator;
int currentSectionIndex{0};
while(getline(input, line)) {
std::vector<std::string> items_buffer;
std::string name;
detail::trim(line);
std::size_t len = line.length();
// lines have to be at least 3 characters to have any meaning to CLI just skip the rest
if(len < 3) {
continue;
}
if(line.front() == '[' && line.back() == ']') {
if(currentSection != "default") {
// insert a section end which is just an empty items_buffer
output.emplace_back();
output.back().parents = detail::generate_parents(currentSection, name, parentSeparatorChar);
output.back().name = "--";
}
currentSection = line.substr(1, len - 2);
// deal with double brackets for TOML
if(currentSection.size() > 1 && currentSection.front() == '[' && currentSection.back() == ']') {
currentSection = currentSection.substr(1, currentSection.size() - 2);
}
if(detail::to_lower(currentSection) == "default") {
currentSection = "default";
} else {
detail::checkParentSegments(output, currentSection, parentSeparatorChar);
}
inSection = false;
if(currentSection == previousSection) {
++currentSectionIndex;
} else {
currentSectionIndex = 0;
previousSection = currentSection;
}
continue;
}
// comment lines
if(line.front() == ';' || line.front() == '#' || line.front() == commentChar) {
continue;
}
// Find = in string, split and recombine
auto pos = line.find(valueDelimiter);
if(pos != std::string::npos) {
name = detail::trim_copy(line.substr(0, pos));
std::string item = detail::trim_copy(line.substr(pos + 1));
auto cloc = item.find(commentChar);
if(cloc != std::string::npos) {
item.erase(cloc, std::string::npos);
detail::trim(item);
}
if(item.size() > 1 && item.front() == aStart) {
for(std::string multiline; item.back() != aEnd && std::getline(input, multiline);) {
detail::trim(multiline);
item += multiline;
}
items_buffer = detail::split_up(item.substr(1, item.length() - 2), aSep);
} else if((isDefaultArray || isINIArray) && item.find_first_of(aSep) != std::string::npos) {
items_buffer = detail::split_up(item, aSep);
} else if((isDefaultArray || isINIArray) && item.find_first_of(' ') != std::string::npos) {
items_buffer = detail::split_up(item);
} else {
items_buffer = {item};
}
} else {
name = detail::trim_copy(line);
auto cloc = name.find(commentChar);
if(cloc != std::string::npos) {
name.erase(cloc, std::string::npos);
detail::trim(name);
}
items_buffer = {"true"};
}
if(name.find(parentSeparatorChar) == std::string::npos) {
detail::remove_quotes(name);
}
// clean up quotes on the items
for(auto &it : items_buffer) {
detail::remove_quotes(it);
}
std::vector<std::string> parents = detail::generate_parents(currentSection, name, parentSeparatorChar);
if(parents.size() > maximumLayers) {
continue;
}
if(!configSection.empty() && !inSection) {
if(parents.empty() || parents.front() != configSection) {
continue;
}
if(configIndex >= 0 && currentSectionIndex != configIndex) {
continue;
}
parents.erase(parents.begin());
inSection = true;
}
if(!output.empty() && name == output.back().name && parents == output.back().parents) {
output.back().inputs.insert(output.back().inputs.end(), items_buffer.begin(), items_buffer.end());
} else {
output.emplace_back();
output.back().parents = std::move(parents);
output.back().name = std::move(name);
output.back().inputs = std::move(items_buffer);
}
}
if(currentSection != "default") {
// insert a section end which is just an empty items_buffer
std::string ename;
output.emplace_back();
output.back().parents = detail::generate_parents(currentSection, ename, parentSeparatorChar);
output.back().name = "--";
while(output.back().parents.size() > 1) {
output.push_back(output.back());
output.back().parents.pop_back();
}
}
return output;
}
inline std::string
ConfigBase::to_config(const App *app, bool default_also, bool write_description, std::string prefix) const {
std::stringstream out;
std::string commentLead;
commentLead.push_back(commentChar);
commentLead.push_back(' ');
std::vector<std::string> groups = app->get_groups();
bool defaultUsed = false;
groups.insert(groups.begin(), std::string("Options"));
if(write_description && (app->get_configurable() || app->get_parent() == nullptr || app->get_name().empty())) {
out << commentLead << detail::fix_newlines(commentLead, app->get_description()) << '\n';
}
for(auto &group : groups) {
if(group == "Options" || group.empty()) {
if(defaultUsed) {
continue;
}
defaultUsed = true;
}
if(write_description && group != "Options" && !group.empty()) {
out << '\n' << commentLead << group << " Options\n";
}
for(const Option *opt : app->get_options({})) {
// Only process options that are configurable
if(opt->get_configurable()) {
if(opt->get_group() != group) {
if(!(group == "Options" && opt->get_group().empty())) {
continue;
}
}
std::string name = prefix + opt->get_single_name();
std::string value = detail::ini_join(
opt->reduced_results(), arraySeparator, arrayStart, arrayEnd, stringQuote, characterQuote);
if(value.empty() && default_also) {
if(!opt->get_default_str().empty()) {
value = detail::convert_arg_for_ini(opt->get_default_str(), stringQuote, characterQuote);
} else if(opt->get_expected_min() == 0) {
value = "false";
} else if(opt->get_run_callback_for_default()) {
value = "\"\""; // empty string default value
}
}
if(!value.empty()) {
if(write_description && opt->has_description()) {
out << '\n';
out << commentLead << detail::fix_newlines(commentLead, opt->get_description()) << '\n';
}
out << name << valueDelimiter << value << '\n';
}
}
}
}
auto subcommands = app->get_subcommands({});
for(const App *subcom : subcommands) {
if(subcom->get_name().empty()) {
if(write_description && !subcom->get_group().empty()) {
out << '\n' << commentLead << subcom->get_group() << " Options\n";
}
out << to_config(subcom, default_also, write_description, prefix);
}
}
for(const App *subcom : subcommands) {
if(!subcom->get_name().empty()) {
if(subcom->get_configurable() && app->got_subcommand(subcom)) {
if(!prefix.empty() || app->get_parent() == nullptr) {
out << '[' << prefix << subcom->get_name() << "]\n";
} else {
std::string subname = app->get_name() + parentSeparatorChar + subcom->get_name();
auto p = app->get_parent();
while(p->get_parent() != nullptr) {
subname = p->get_name() + parentSeparatorChar + subname;
p = p->get_parent();
}
out << '[' << subname << "]\n";
}
out << to_config(subcom, default_also, write_description, "");
} else {
out << to_config(
subcom, default_also, write_description, prefix + subcom->get_name() + parentSeparatorChar);
}
}
}
return out.str();
}
// [CLI11:config_hpp:end]
} // namespace CLI

View File

@@ -0,0 +1,185 @@
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#pragma once
// [CLI11:public_includes:set]
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
// [CLI11:public_includes:end]
#include "Error.hpp"
#include "StringTools.hpp"
namespace CLI {
// [CLI11:config_fwd_hpp:verbatim]
class App;
/// Holds values to load into Options
struct ConfigItem {
/// This is the list of parents
std::vector<std::string> parents{};
/// This is the name
std::string name{};
/// Listing of inputs
std::vector<std::string> inputs{};
/// The list of parents and name joined by "."
std::string fullname() const {
std::vector<std::string> tmp = parents;
tmp.emplace_back(name);
return detail::join(tmp, ".");
}
};
/// This class provides a converter for configuration files.
class Config {
protected:
std::vector<ConfigItem> items{};
public:
/// Convert an app into a configuration
virtual std::string to_config(const App *, bool, bool, std::string) const = 0;
/// Convert a configuration into an app
virtual std::vector<ConfigItem> from_config(std::istream &) const = 0;
/// Get a flag value
virtual std::string to_flag(const ConfigItem &item) const {
if(item.inputs.size() == 1) {
return item.inputs.at(0);
}
if(item.inputs.empty()) {
return "{}";
}
throw ConversionError::TooManyInputsFlag(item.fullname());
}
/// Parse a config file, throw an error (ParseError:ConfigParseError or FileError) on failure
std::vector<ConfigItem> from_file(const std::string &name) {
std::ifstream input{name};
if(!input.good())
throw FileError::Missing(name);
return from_config(input);
}
/// Virtual destructor
virtual ~Config() = default;
};
/// This converter works with INI/TOML files; to write INI files use ConfigINI
class ConfigBase : public Config {
protected:
/// the character used for comments
char commentChar = '#';
/// the character used to start an array '\0' is a default to not use
char arrayStart = '[';
/// the character used to end an array '\0' is a default to not use
char arrayEnd = ']';
/// the character used to separate elements in an array
char arraySeparator = ',';
/// the character used separate the name from the value
char valueDelimiter = '=';
/// the character to use around strings
char stringQuote = '"';
/// the character to use around single characters
char characterQuote = '\'';
/// the maximum number of layers to allow
uint8_t maximumLayers{255};
/// the separator used to separator parent layers
char parentSeparatorChar{'.'};
/// Specify the configuration index to use for arrayed sections
int16_t configIndex{-1};
/// Specify the configuration section that should be used
std::string configSection{};
public:
std::string
to_config(const App * /*app*/, bool default_also, bool write_description, std::string prefix) const override;
std::vector<ConfigItem> from_config(std::istream &input) const override;
/// Specify the configuration for comment characters
ConfigBase *comment(char cchar) {
commentChar = cchar;
return this;
}
/// Specify the start and end characters for an array
ConfigBase *arrayBounds(char aStart, char aEnd) {
arrayStart = aStart;
arrayEnd = aEnd;
return this;
}
/// Specify the delimiter character for an array
ConfigBase *arrayDelimiter(char aSep) {
arraySeparator = aSep;
return this;
}
/// Specify the delimiter between a name and value
ConfigBase *valueSeparator(char vSep) {
valueDelimiter = vSep;
return this;
}
/// Specify the quote characters used around strings and characters
ConfigBase *quoteCharacter(char qString, char qChar) {
stringQuote = qString;
characterQuote = qChar;
return this;
}
/// Specify the maximum number of parents
ConfigBase *maxLayers(uint8_t layers) {
maximumLayers = layers;
return this;
}
/// Specify the separator to use for parent layers
ConfigBase *parentSeparator(char sep) {
parentSeparatorChar = sep;
return this;
}
/// get a reference to the configuration section
std::string &sectionRef() { return configSection; }
/// get the section
const std::string &section() const { return configSection; }
/// specify a particular section of the configuration file to use
ConfigBase *section(const std::string &sectionName) {
configSection = sectionName;
return this;
}
/// get a reference to the configuration index
int16_t &indexRef() { return configIndex; }
/// get the section index
int16_t index() const { return configIndex; }
/// specify a particular index in the section to use (-1) for all sections to use
ConfigBase *index(int16_t sectionIndex) {
configIndex = sectionIndex;
return this;
}
};
/// the default Config is the TOML file format
using ConfigTOML = ConfigBase;
/// ConfigINI generates a "standard" INI compliant output
class ConfigINI : public ConfigTOML {
public:
ConfigINI() {
commentChar = ';';
arrayStart = '\0';
arrayEnd = '\0';
arraySeparator = ' ';
valueDelimiter = '=';
}
};
// [CLI11:config_fwd_hpp:end]
} // namespace CLI

Some files were not shown because too many files have changed in this diff Show More