This commit is contained in:
2026-09-13 13:30:21 +08:00
commit a6bbd520cf
2744 changed files with 1598795 additions and 0 deletions
File diff suppressed because it is too large Load Diff
+31
View File
@@ -0,0 +1,31 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// [CLI11:public_includes:set]
#include <string>
#include <vector>
// [CLI11:public_includes:end]
#include "Macros.hpp"
namespace CLI {
// [CLI11:argv_hpp:verbatim]
namespace detail {
#ifdef _WIN32
/// Decode and return UTF-8 argv from GetCommandLineW.
CLI11_INLINE std::vector<std::string> compute_win32_argv();
#endif
} // namespace detail
// [CLI11:argv_hpp:end]
} // namespace CLI
#ifndef CLI11_COMPILE
#include "impl/Argv_inl.hpp" // IWYU pragma: export
#endif
+46
View File
@@ -0,0 +1,46 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: begin_exports
#include "Version.hpp"
#include "Macros.hpp"
#include "Encoding.hpp"
#include "Argv.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"
#include "ExtraValidators.hpp"
// IWYU pragma: end_exports
+50
View File
@@ -0,0 +1,50 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// [CLI11:public_includes:set]
#include <string>
#include <vector>
// [CLI11:public_includes:end]
#include "App.hpp"
#include "ConfigFwd.hpp"
#include "StringTools.hpp"
namespace CLI {
// [CLI11:config_hpp:verbatim]
namespace detail {
std::string convert_arg_for_ini(const std::string &arg,
char stringQuote = '"',
char literalQuote = '\'',
bool disable_multi_line = false);
/// Comma separated join, adds quotes if needed
std::string ini_join(const std::vector<std::string> &args,
char sepChar = ',',
char arrayStart = '[',
char arrayEnd = ']',
char stringQuote = '"',
char literalQuote = '\'');
void clean_name_string(std::string &name, const std::string &keyChars);
std::vector<std::string> generate_parents(const std::string &section, std::string &name, char parentSeparator);
/// assuming non default segments do a check on the close and open of the segments in a configItem structure
void checkParentSegments(std::vector<ConfigItem> &output, const std::string &currentSection, char parentSeparator);
} // namespace detail
// [CLI11:config_hpp:end]
} // namespace CLI
#ifndef CLI11_COMPILE
#include "impl/Config_inl.hpp" // IWYU pragma: export
#endif
+185
View File
@@ -0,0 +1,185 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// [CLI11:public_includes:set]
#include <cstdint>
#include <iosfwd>
#include <string>
#include <vector>
// [CLI11:public_includes:end]
#include "Error.hpp"
#include "StringTools.hpp"
namespace CLI {
// [CLI11:config_fwd_hpp:verbatim]
class App;
/// enumeration of output modes for writing config files
enum class ConfigOutputMode : std::uint8_t { Active = 0, AllDefaults, ActiveSubcommandDefaults };
/// 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{};
/// @brief indicator if a multiline vector separator was inserted
bool multiline{false};
/// The list of parents and name joined by "."
CLI11_NODISCARD std::string fullname() const;
};
/// 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 an app into a configuration
virtual std::string
to_config(const App *app, ConfigOutputMode mode, bool write_description, std::string prefix) const;
/// Convert a configuration into an app
virtual std::vector<ConfigItem> from_config(std::istream &) const = 0;
/// Get a flag value
CLI11_NODISCARD virtual std::string to_flag(const ConfigItem &item) const;
/// Parse a config file, throw an error (ParseError:ConfigParseError or FileError) on failure
CLI11_NODISCARD std::vector<ConfigItem> from_file(const std::string &name) const;
/// 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 and literal strings
char literalQuote = '\'';
/// the maximum number of layers to allow
std::uint8_t maximumLayers{255};
/// the separator used to separator parent layers
char parentSeparatorChar{'.'};
/// comment default values
bool commentDefaultsBool = false;
/// specify the config reader should collapse repeated field names to a single vector
bool allowMultipleDuplicateFields{false};
/// 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*/, ConfigOutputMode mode, bool write_description, std::string prefix) const override;
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 literal strings
ConfigBase *quoteCharacter(char qString, char literalChar) {
stringQuote = qString;
literalQuote = literalChar;
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;
}
/// comment default value options
ConfigBase *commentDefaults(bool comDef = true) {
commentDefaultsBool = comDef;
return this;
}
/// get a reference to the configuration section
std::string &sectionRef() { return configSection; }
/// get the section
CLI11_NODISCARD 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
CLI11_NODISCARD 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;
}
/// specify that multiple duplicate arguments should be merged even if not sequential
ConfigBase *allowDuplicateFields(bool value = true) {
allowMultipleDuplicateFields = value;
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();
};
// [CLI11:config_fwd_hpp:end]
} // namespace CLI
+55
View File
@@ -0,0 +1,55 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
#include "Macros.hpp"
// [CLI11:public_includes:set]
#include <cstddef>
#include <string>
// [CLI11:public_includes:end]
// [CLI11:encoding_includes:verbatim]
#if defined(CLI11_CPP17) || (defined(CLI11_HAS_FILESYSTEM) && CLI11_HAS_FILESYSTEM > 0)
#include <string_view>
#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
#include <filesystem>
#endif
#endif
// [CLI11:encoding_includes:end]
namespace CLI {
// [CLI11:encoding_hpp:verbatim]
/// Convert a wide string to a narrow string.
CLI11_INLINE std::string narrow(const std::wstring &str);
CLI11_INLINE std::string narrow(const wchar_t *str);
CLI11_INLINE std::string narrow(const wchar_t *str, std::size_t size);
/// Convert a narrow string to a wide string.
CLI11_INLINE std::wstring widen(const std::string &str);
CLI11_INLINE std::wstring widen(const char *str);
CLI11_INLINE std::wstring widen(const char *str, std::size_t size);
#ifdef CLI11_CPP17
CLI11_INLINE std::string narrow(std::wstring_view str);
CLI11_INLINE std::wstring widen(std::string_view str);
#endif // CLI11_CPP17
#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
/// Convert a char-string to a native path correctly.
CLI11_INLINE std::filesystem::path to_path(std::string_view str);
#endif // CLI11_HAS_FILESYSTEM
// [CLI11:encoding_hpp:end]
} // namespace CLI
#ifndef CLI11_COMPILE
#include "impl/Encoding_inl.hpp" // IWYU pragma: export
#endif
+363
View File
@@ -0,0 +1,363 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// [CLI11:public_includes:set]
#include <cstddef>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// [CLI11:public_includes:end]
// CLI library includes
#include "Macros.hpp"
#include "StringTools.hpp"
namespace CLI {
// [CLI11:error_hpp:verbatim]
// Use one of these on all error classes.
// These are temporary and are undef'd at the end of this file.
#define CLI11_ERROR_DEF(parent, name) \
protected: \
name(std::string ename, std::string msg, int exit_code) : parent(std::move(ename), std::move(msg), exit_code) {} \
name(std::string ename, std::string msg, ExitCodes exit_code) \
: parent(std::move(ename), std::move(msg), exit_code) {} \
\
public: \
name(std::string msg, ExitCodes exit_code) : parent(#name, std::move(msg), exit_code) {} \
name(std::string msg, int exit_code) : parent(#name, std::move(msg), exit_code) {}
// This is added after the one above if a class is used directly and builds its own message
#define CLI11_ERROR_SIMPLE(name) \
explicit name(std::string msg) : name(#name, std::move(msg), ExitCodes::name) {}
/// These codes are part of every error in CLI. They can be obtained from e using e.exit_code or as a quick shortcut,
/// int values from e.get_error_code().
enum class ExitCodes : int {
Success = 0,
IncorrectConstruction = 100,
BadNameString,
OptionAlreadyAdded,
FileError,
ConversionError,
ValidationError,
RequiredError,
RequiresError,
ExcludesError,
ExtrasError,
ConfigError,
InvalidError,
HorribleError,
OptionNotFound,
ArgumentMismatch,
BaseClass = 127
};
// Error definitions
/// @defgroup error_group Errors
/// @brief Errors thrown by CLI11
///
/// These are the errors that can be thrown. Some of them, like CLI::Success, are not really errors.
/// @{
/// All errors derive from this one
class Error : public std::runtime_error {
int actual_exit_code;
std::string error_name{"Error"};
public:
CLI11_NODISCARD int get_exit_code() const { return actual_exit_code; }
CLI11_NODISCARD std::string get_name() const { return error_name; }
Error(std::string name, std::string msg, int exit_code = static_cast<int>(ExitCodes::BaseClass))
: runtime_error(msg), actual_exit_code(exit_code), error_name(std::move(name)) {}
Error(std::string name, std::string msg, ExitCodes exit_code)
: Error(std::move(name), std::move(msg), static_cast<int>(exit_code)) {}
};
// Note: Using Error::Error constructors does not work on GCC 4.7
/// Construction errors (not in parsing)
class ConstructionError : public Error {
CLI11_ERROR_DEF(Error, ConstructionError)
};
/// Thrown when an option is set to conflicting values (non-vector and multi args, for example)
class IncorrectConstruction : public ConstructionError {
CLI11_ERROR_DEF(ConstructionError, IncorrectConstruction)
CLI11_ERROR_SIMPLE(IncorrectConstruction)
static IncorrectConstruction PositionalFlag(std::string name) {
return IncorrectConstruction(name + ": Flags cannot be positional");
}
static IncorrectConstruction Set0Opt(std::string name) {
return IncorrectConstruction(name + ": Cannot set 0 expected, use a flag instead");
}
static IncorrectConstruction SetFlag(std::string name) {
return IncorrectConstruction(name + ": Cannot set an expected number for flags");
}
static IncorrectConstruction ChangeNotVector(std::string name) {
return IncorrectConstruction(name + ": You can only change the expected arguments for vectors");
}
static IncorrectConstruction AfterMultiOpt(std::string name) {
return IncorrectConstruction(
name + ": You can't change expected arguments after you've changed the multi option policy!");
}
static IncorrectConstruction MissingOption(std::string name) {
return IncorrectConstruction("Option " + name + " is not defined");
}
static IncorrectConstruction MultiOptionPolicy(std::string name) {
return IncorrectConstruction(name + ": multi_option_policy only works for flags and exact value options");
}
};
/// Thrown on construction of a bad name
class BadNameString : public ConstructionError {
CLI11_ERROR_DEF(ConstructionError, BadNameString)
CLI11_ERROR_SIMPLE(BadNameString)
static BadNameString OneCharName(std::string name) { return BadNameString("Invalid one char name: " + name); }
static BadNameString MissingDash(std::string name) {
return BadNameString("Long names strings require 2 dashes " + name);
}
static BadNameString BadLongName(std::string name) { return BadNameString("Bad long name: " + name); }
static BadNameString BadPositionalName(std::string name) {
return BadNameString("Invalid positional Name: " + name);
}
static BadNameString ReservedName(std::string name) {
return BadNameString("Names '-','--','++' are reserved and not allowed as option names " + name);
}
static BadNameString MultiPositionalNames(std::string name) {
return BadNameString("Only one positional name allowed, remove: " + name);
}
};
/// Thrown when an option already exists
class OptionAlreadyAdded : public ConstructionError {
CLI11_ERROR_DEF(ConstructionError, OptionAlreadyAdded)
explicit OptionAlreadyAdded(std::string name)
: OptionAlreadyAdded(name + " is already added", ExitCodes::OptionAlreadyAdded) {}
static OptionAlreadyAdded Requires(std::string name, std::string other) {
return {name + " requires " + other, ExitCodes::OptionAlreadyAdded};
}
static OptionAlreadyAdded Excludes(std::string name, std::string other) {
return {name + " excludes " + other, ExitCodes::OptionAlreadyAdded};
}
};
// Parsing errors
/// Anything that can error in Parse
class ParseError : public Error {
CLI11_ERROR_DEF(Error, ParseError)
};
// Not really "errors"
/// This is a successful completion on parsing, supposed to exit
class Success : public ParseError {
CLI11_ERROR_DEF(ParseError, Success)
Success() : Success("Successfully completed, should be caught and quit", ExitCodes::Success) {}
};
/// -h or --help on command line
class CallForHelp : public Success {
CLI11_ERROR_DEF(Success, CallForHelp)
CallForHelp() : CallForHelp("This should be caught in your main function, see examples", ExitCodes::Success) {}
};
/// Usually something like --help-all on command line
class CallForAllHelp : public Success {
CLI11_ERROR_DEF(Success, CallForAllHelp)
CallForAllHelp()
: CallForAllHelp("This should be caught in your main function, see examples", ExitCodes::Success) {}
};
/// -v or --version on command line
class CallForVersion : public Success {
CLI11_ERROR_DEF(Success, CallForVersion)
CallForVersion()
: CallForVersion("This should be caught in your main function, see examples", ExitCodes::Success) {}
};
/// Does not output a diagnostic in CLI11_PARSE, but allows main() to return with a specific error code.
class RuntimeError : public ParseError {
CLI11_ERROR_DEF(ParseError, RuntimeError)
explicit RuntimeError(int exit_code = 1) : RuntimeError("Runtime error", exit_code) {}
};
/// Thrown when parsing an INI file and it is missing
class FileError : public ParseError {
CLI11_ERROR_DEF(ParseError, FileError)
CLI11_ERROR_SIMPLE(FileError)
static FileError Missing(std::string name) { return FileError(name + " was not readable (missing?)"); }
};
/// Thrown when conversion call back fails, such as when an int fails to coerce to a string
class ConversionError : public ParseError {
CLI11_ERROR_DEF(ParseError, ConversionError)
CLI11_ERROR_SIMPLE(ConversionError)
ConversionError(std::string member, std::string name)
: ConversionError("The value " + member + " is not an allowed value for " + name) {}
ConversionError(std::string name, std::vector<std::string> results)
: ConversionError("Could not convert: " + name + " = " + detail::join(results)) {}
static ConversionError TooManyInputsFlag(std::string name) {
return ConversionError(name + ": too many inputs for a flag");
}
static ConversionError TrueFalse(std::string name) {
return ConversionError(name + ": Should be true/false or a number");
}
};
/// Thrown when validation of results fails
class ValidationError : public ParseError {
CLI11_ERROR_DEF(ParseError, ValidationError)
CLI11_ERROR_SIMPLE(ValidationError)
explicit ValidationError(std::string name, std::string msg) : ValidationError(name + ": " + msg) {}
};
/// Thrown when a required option is missing
class RequiredError : public ParseError {
CLI11_ERROR_DEF(ParseError, RequiredError)
explicit RequiredError(std::string name) : RequiredError(name + " is required", ExitCodes::RequiredError) {}
static RequiredError Subcommand(std::size_t min_subcom) {
if(min_subcom == 1) {
return RequiredError("A subcommand");
}
return {"Requires at least " + std::to_string(min_subcom) + " subcommands", ExitCodes::RequiredError};
}
static RequiredError
Option(std::size_t min_option, std::size_t max_option, std::size_t used, const std::string &option_list) {
if((min_option == 1) && (max_option == 1) && (used == 0))
return RequiredError("Exactly 1 option from [" + option_list + "]");
if((min_option == 1) && (max_option == 1) && (used > 1)) {
return {"Exactly 1 option from [" + option_list + "] is required but " + std::to_string(used) +
" were given",
ExitCodes::RequiredError};
}
if((min_option == 1) && (used == 0))
return RequiredError("At least 1 option from [" + option_list + "]");
if(used < min_option) {
return {"Requires at least " + std::to_string(min_option) + " options used but only " +
std::to_string(used) + " were given from [" + option_list + "]",
ExitCodes::RequiredError};
}
if(max_option == 1)
return {"Requires at most 1 options be given from [" + option_list + "]", ExitCodes::RequiredError};
return {"Requires at most " + std::to_string(max_option) + " options be used but " + std::to_string(used) +
" were given from [" + option_list + "]",
ExitCodes::RequiredError};
}
};
/// Thrown when the wrong number of arguments has been received
class ArgumentMismatch : public ParseError {
CLI11_ERROR_DEF(ParseError, ArgumentMismatch)
CLI11_ERROR_SIMPLE(ArgumentMismatch)
ArgumentMismatch(std::string name, int expected, std::size_t received)
: ArgumentMismatch(expected > 0 ? ("Expected exactly " + std::to_string(expected) + " arguments to " + name +
", got " + std::to_string(received))
: ("Expected at least " + std::to_string(-expected) + " arguments to " + name +
", got " + std::to_string(received)),
ExitCodes::ArgumentMismatch) {}
static ArgumentMismatch AtLeast(std::string name, int num, std::size_t received) {
return ArgumentMismatch(name + ": At least " + std::to_string(num) + " required but received " +
std::to_string(received));
}
static ArgumentMismatch AtMost(std::string name, int num, std::size_t received) {
return ArgumentMismatch(name + ": At most " + std::to_string(num) + " required but received " +
std::to_string(received));
}
static ArgumentMismatch TypedAtLeast(std::string name, int num, std::string type) {
return ArgumentMismatch(name + ": " + std::to_string(num) + " required " + type + " missing");
}
static ArgumentMismatch FlagOverride(std::string name) {
return ArgumentMismatch(name + " was given a disallowed flag override");
}
static ArgumentMismatch PartialType(std::string name, int num, std::string type) {
return ArgumentMismatch(name + ": " + type + " only partially specified: " + std::to_string(num) +
" required for each element");
}
};
/// Thrown when a requires option is missing
class RequiresError : public ParseError {
CLI11_ERROR_DEF(ParseError, RequiresError)
RequiresError(std::string curname, std::string subname)
: RequiresError(curname + " requires " + subname, ExitCodes::RequiresError) {}
};
/// Thrown when an excludes option is present
class ExcludesError : public ParseError {
CLI11_ERROR_DEF(ParseError, ExcludesError)
ExcludesError(std::string curname, std::string subname)
: ExcludesError(curname + " excludes " + subname, ExitCodes::ExcludesError) {}
};
/// Thrown when too many positionals or options are found
class ExtrasError : public ParseError {
CLI11_ERROR_DEF(ParseError, ExtrasError)
explicit ExtrasError(std::vector<std::string> args)
: ExtrasError((args.size() > 1 ? "The following arguments were not expected: "
: "The following argument was not expected: ") +
detail::join(args, " "),
ExitCodes::ExtrasError) {}
ExtrasError(const std::string &name, std::vector<std::string> args)
: ExtrasError((name.empty() ? std::string{} : name + ": ") +
(args.size() > 1 ? "The following arguments were not expected: "
: "The following argument was not expected: ") +
detail::join(args, " "),
ExitCodes::ExtrasError) {}
};
/// Thrown when extra values are found in an INI file
class ConfigError : public ParseError {
CLI11_ERROR_DEF(ParseError, ConfigError)
CLI11_ERROR_SIMPLE(ConfigError)
static ConfigError Extras(std::string item) { return ConfigError("INI was not able to parse " + item); }
static ConfigError NotConfigurable(std::string item) {
return ConfigError(item + ": This option is not allowed in a configuration file");
}
};
/// Thrown when validation fails before parsing
class InvalidError : public ParseError {
CLI11_ERROR_DEF(ParseError, InvalidError)
explicit InvalidError(std::string name)
: InvalidError(name + ": Too many positional arguments with unlimited expected args", ExitCodes::InvalidError) {
}
};
/// This is just a safety check to verify selection and parsing match - you should not ever see it
/// Strings are directly added to this error, but again, it should never be seen.
class HorribleError : public ParseError {
CLI11_ERROR_DEF(ParseError, HorribleError)
CLI11_ERROR_SIMPLE(HorribleError)
};
// After parsing
/// Thrown when counting a nonexistent option
class OptionNotFound : public Error {
CLI11_ERROR_DEF(Error, OptionNotFound)
explicit OptionNotFound(std::string name) : OptionNotFound(name + " not found", ExitCodes::OptionNotFound) {}
};
#undef CLI11_ERROR_DEF
#undef CLI11_ERROR_SIMPLE
/// @}
// [CLI11:error_hpp:end]
} // namespace CLI
+645
View File
@@ -0,0 +1,645 @@
// Copyright (c) 2017-2026, 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
#if (defined(CLI11_ENABLE_EXTRA_VALIDATORS) && CLI11_ENABLE_EXTRA_VALIDATORS != 0) || \
(!defined(CLI11_DISABLE_EXTRA_VALIDATORS) || CLI11_DISABLE_EXTRA_VALIDATORS == 0)
// IWYU pragma: private, include "CLI/CLI.hpp"
#include "Error.hpp"
#include "Macros.hpp"
#include "StringTools.hpp"
#include "Validators.hpp"
// [CLI11:public_includes:set]
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <locale>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
// [CLI11:public_includes:end]
namespace CLI {
// [CLI11:extra_validators_hpp:verbatim]
// The implementation of the extra validators is using the Validator class;
// the user is only expected to use the const (static) versions (since there's no setup).
// Therefore, this is in detail.
namespace detail {
/// Validate the given string is a legal ipv4 address
class IPV4Validator : public Validator {
public:
IPV4Validator();
};
} // namespace detail
/// Validate the input as a particular type
template <typename DesiredType> class TypeValidator : public Validator {
public:
explicit TypeValidator(const std::string &validator_name)
: Validator(validator_name, [](std::string &input_string) {
using CLI::detail::lexical_cast;
auto val = DesiredType();
if(!lexical_cast(input_string, val)) {
return std::string("Failed parsing ") + input_string + " as a " + detail::type_name<DesiredType>();
}
return std::string{};
}) {}
TypeValidator() : TypeValidator(detail::type_name<DesiredType>()) {}
};
/// Check for a number
CLI11_MODULE_INLINE const TypeValidator<double> Number("NUMBER");
/// Produce a bounded range (factory). Min and max are inclusive.
class Bound : public Validator {
public:
/// This bounds a value with min and max inclusive.
///
/// Note that the constructor is templated, but the struct is not, so C++17 is not
/// needed to provide nice syntax for Range(a,b).
template <typename T> Bound(T min_val, T max_val) {
std::stringstream out;
out << detail::type_name<T>() << " bounded to [" << min_val << " - " << max_val << "]";
description(out.str());
func_ = [min_val, max_val](std::string &input) {
using CLI::detail::lexical_cast;
T val;
bool converted = lexical_cast(input, val);
if(!converted) {
return std::string("Value ") + input + " could not be converted";
}
if(val < min_val)
input = detail::to_string(min_val);
else if(val > max_val)
input = detail::to_string(max_val);
return std::string{};
};
}
/// Range of one value is 0 to value
template <typename T> explicit Bound(T max_val) : Bound(static_cast<T>(0), max_val) {}
};
// Static is not needed here, because global const implies static.
/// Check for an IP4 address
CLI11_MODULE_INLINE const detail::IPV4Validator ValidIPV4;
namespace detail {
template <typename T,
enable_if_t<is_copyable_ptr<typename std::remove_reference<T>::type>::value, detail::enabler> = detail::dummy>
auto smart_deref(T value) -> decltype(*value) {
return *value;
}
template <
typename T,
enable_if_t<!is_copyable_ptr<typename std::remove_reference<T>::type>::value, detail::enabler> = detail::dummy>
typename std::remove_reference<T>::type &smart_deref(T &value) {
// NOLINTNEXTLINE
return value;
}
/// Generate a string representation of a set
template <typename T> std::string generate_set(const T &set) {
using element_t = typename detail::element_type<T>::type;
using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
std::string out(1, '{');
out.append(detail::join(
detail::smart_deref(set),
[](const iteration_type_t &v) { return detail::pair_adaptor<element_t>::first(v); },
","));
out.push_back('}');
return out;
}
/// Generate a string representation of a map
template <typename T> std::string generate_map(const T &map, bool key_only = false) {
using element_t = typename detail::element_type<T>::type;
using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
std::string out(1, '{');
out.append(detail::join(
detail::smart_deref(map),
[key_only](const iteration_type_t &v) {
std::string res{detail::to_string(detail::pair_adaptor<element_t>::first(v))};
if(!key_only) {
res.append("->");
res += detail::to_string(detail::pair_adaptor<element_t>::second(v));
}
return res;
},
","));
out.push_back('}');
return out;
}
template <typename C, typename V> struct has_find {
template <typename CC, typename VV>
static auto test(int) -> decltype(std::declval<CC>().find(std::declval<VV>()), std::true_type());
template <typename, typename> static auto test(...) -> decltype(std::false_type());
static const auto value = decltype(test<C, V>(0))::value;
using type = std::integral_constant<bool, value>;
};
/// A search function
template <typename T, typename V, enable_if_t<!has_find<T, V>::value, detail::enabler> = detail::dummy>
auto search(const T &set, const V &val) -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
using element_t = typename detail::element_type<T>::type;
auto &setref = detail::smart_deref(set);
auto it = std::find_if(std::begin(setref), std::end(setref), [&val](decltype(*std::begin(setref)) v) {
return (detail::pair_adaptor<element_t>::first(v) == val);
});
return {(it != std::end(setref)), it};
}
/// A search function that uses the built in find function
template <typename T, typename V, enable_if_t<has_find<T, V>::value, detail::enabler> = detail::dummy>
auto search(const T &set, const V &val) -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
auto &setref = detail::smart_deref(set);
auto it = setref.find(val);
return {(it != std::end(setref)), it};
}
/// A search function with a filter function
template <typename T, typename V>
auto search(const T &set, const V &val, const std::function<V(V)> &filter_function)
-> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
using element_t = typename detail::element_type<T>::type;
// do the potentially faster first search
auto res = search(set, val);
if((res.first) || (!(filter_function))) {
return res;
}
// if we haven't found it do the longer linear search with all the element translations
auto &setref = detail::smart_deref(set);
auto it = std::find_if(std::begin(setref), std::end(setref), [&](decltype(*std::begin(setref)) v) {
V a{detail::pair_adaptor<element_t>::first(v)};
a = filter_function(a);
return (a == val);
});
return {(it != std::end(setref)), it};
}
} // namespace detail
/// Verify items are in a set
class IsMember : public Validator {
public:
using filter_fn_t = std::function<std::string(std::string)>;
/// This allows in-place construction using an initializer list
template <typename T, typename... Args>
IsMember(std::initializer_list<T> values, Args &&...args)
: IsMember(std::vector<T>(values), std::forward<Args>(args)...) {}
/// This checks to see if an item is in a set (empty function)
template <typename T> explicit IsMember(T &&set) : IsMember(std::forward<T>(set), nullptr) {}
/// This checks to see if an item is in a set: pointer or copy version. You can pass in a function that will filter
/// both sides of the comparison before computing the comparison.
template <typename T, typename F> explicit IsMember(T set, F filter_function) {
// Get the type of the contained item - requires a container have ::value_type
// if the type does not have first_type and second_type, these are both value_type
using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
using local_item_t = typename IsMemberType<item_t>::type; // This will convert bad types to good ones
// (const char * to std::string)
// Make a local copy of the filter function, using a std::function if not one already
std::function<local_item_t(local_item_t)> filter_fn = filter_function;
// Store a single copy of the set in a shared_ptr so the lambdas below can share it
auto shared_set = std::make_shared<T>(std::move(set));
// This is the type name for help, it will take the current version of the set contents
desc_function_ = [shared_set]() { return detail::generate_set(detail::smart_deref(*shared_set)); };
// This is the function that validates
// It stores a copy of the set pointer-like, so shared_ptr will stay alive
func_ = [shared_set, filter_fn](std::string &input) {
using CLI::detail::lexical_cast;
local_item_t b;
if(!lexical_cast(input, b)) {
throw ValidationError(input); // name is added later
}
if(filter_fn) {
b = filter_fn(b);
}
auto res = detail::search(*shared_set, b, filter_fn);
if(res.first) {
// Make sure the version in the input string is identical to the one in the set
if(filter_fn) {
input = detail::value_string(detail::pair_adaptor<element_t>::first(*(res.second)));
}
// Return empty error string (success)
return std::string{};
}
// If you reach this point, the result was not found
return input + " not in " + detail::generate_set(detail::smart_deref(*shared_set));
};
}
/// You can pass in as many filter functions as you like, they nest (string only currently)
template <typename T, typename... Args>
IsMember(T &&set, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
: IsMember(
std::forward<T>(set),
[filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
other...) {}
};
/// definition of the default transformation object
template <typename T> using TransformPairs = std::vector<std::pair<std::string, T>>;
/// Translate named items to other or a value set
class Transformer : public Validator {
public:
using filter_fn_t = std::function<std::string(std::string)>;
/// This allows in-place construction
template <typename... Args>
Transformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&...args)
: Transformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
/// direct map of std::string to std::string
template <typename T> explicit Transformer(T &&mapping) : Transformer(std::forward<T>(mapping), nullptr) {}
/// This checks to see if an item is in a set: pointer or copy version. You can pass in a function that will filter
/// both sides of the comparison before computing the comparison.
template <typename T, typename F> explicit Transformer(T mapping, F filter_function) {
static_assert(detail::pair_adaptor<typename detail::element_type<T>::type>::value,
"mapping must produce value pairs");
// Get the type of the contained item - requires a container have ::value_type
// if the type does not have first_type and second_type, these are both value_type
using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
using local_item_t = typename IsMemberType<item_t>::type; // Will convert bad types to good ones
// (const char * to std::string)
// Make a local copy of the filter function, using a std::function if not one already
std::function<local_item_t(local_item_t)> filter_fn = filter_function;
// Store a single copy of the mapping in a shared_ptr so the lambdas below can share it
auto shared_mapping = std::make_shared<T>(std::move(mapping));
// This is the type name for help, it will take the current version of the set contents
desc_function_ = [shared_mapping]() { return detail::generate_map(detail::smart_deref(*shared_mapping)); };
func_ = [shared_mapping, filter_fn](std::string &input) {
using CLI::detail::lexical_cast;
local_item_t b;
if(!lexical_cast(input, b)) {
return std::string();
// there is no possible way we can match anything in the mapping if we can't convert so just return
}
if(filter_fn) {
b = filter_fn(b);
}
auto res = detail::search(*shared_mapping, b, filter_fn);
if(res.first) {
input = detail::value_string(detail::pair_adaptor<element_t>::second(*res.second));
}
return std::string{};
};
}
/// You can pass in as many filter functions as you like, they nest
template <typename T, typename... Args>
Transformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
: Transformer(
std::forward<T>(mapping),
[filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
other...) {}
};
/// translate named items to other or a value set
class CheckedTransformer : public Validator {
public:
using filter_fn_t = std::function<std::string(std::string)>;
/// This allows in-place construction
template <typename... Args>
CheckedTransformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&...args)
: CheckedTransformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
/// direct map of std::string to std::string
template <typename T> explicit CheckedTransformer(T mapping) : CheckedTransformer(std::move(mapping), nullptr) {}
/// This checks to see if an item is in a set: pointer or copy version. You can pass in a function that will filter
/// both sides of the comparison before computing the comparison.
template <typename T, typename F> explicit CheckedTransformer(T mapping, F filter_function) {
static_assert(detail::pair_adaptor<typename detail::element_type<T>::type>::value,
"mapping must produce value pairs");
// Get the type of the contained item - requires a container have ::value_type
// if the type does not have first_type and second_type, these are both value_type
using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
using local_item_t = typename IsMemberType<item_t>::type; // Will convert bad types to good ones
// (const char * to std::string)
using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
// Make a local copy of the filter function, using a std::function if not one already
std::function<local_item_t(local_item_t)> filter_fn = filter_function;
// Store a single copy of the mapping in a shared_ptr so the lambdas below can share it
auto shared_mapping = std::make_shared<T>(std::move(mapping));
auto tfunc = [shared_mapping]() {
std::string out("value in ");
out += detail::generate_map(detail::smart_deref(*shared_mapping)) + " OR {";
out += detail::join(
detail::smart_deref(*shared_mapping),
[](const iteration_type_t &v) {
return detail::value_string(detail::pair_adaptor<element_t>::second(v));
},
",");
out.push_back('}');
return out;
};
desc_function_ = tfunc;
func_ = [shared_mapping, tfunc, filter_fn](std::string &input) {
using CLI::detail::lexical_cast;
local_item_t b;
bool converted = lexical_cast(input, b);
if(converted) {
if(filter_fn) {
b = filter_fn(b);
}
auto res = detail::search(*shared_mapping, b, filter_fn);
if(res.first) {
input = detail::value_string(detail::pair_adaptor<element_t>::second(*res.second));
return std::string{};
}
}
for(const auto &v : detail::smart_deref(*shared_mapping)) {
auto output_string = detail::value_string(detail::pair_adaptor<element_t>::second(v));
if(output_string == input) {
return std::string();
}
}
return "Check " + input + " " + tfunc() + " FAILED";
};
}
/// You can pass in as many filter functions as you like, they nest
template <typename T, typename... Args>
CheckedTransformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
: CheckedTransformer(
std::forward<T>(mapping),
[filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
other...) {}
};
/// Helper function to allow ignore_case to be passed to IsMember or Transform
inline std::string ignore_case(std::string item) { return detail::to_lower(item); }
/// Helper function to allow ignore_underscore to be passed to IsMember or Transform
inline std::string ignore_underscore(std::string item) { return detail::remove_underscore(item); }
/// Helper function to allow checks to ignore spaces to be passed to IsMember or Transform
inline std::string ignore_space(std::string item) {
item.erase(std::remove(std::begin(item), std::end(item), ' '), std::end(item));
item.erase(std::remove(std::begin(item), std::end(item), '\t'), std::end(item));
return item;
}
/// Multiply a number by a factor using given mapping.
/// Can be used to write transforms for SIZE or DURATION inputs.
///
/// Example:
/// With mapping = `{"b"->1, "kb"->1024, "mb"->1024*1024}`
/// one can recognize inputs like "100", "12kb", "100 MB",
/// that will be automatically transformed to 100, 14448, 104857600.
///
/// Output number type matches the type in the provided mapping.
/// Therefore, if it is required to interpret real inputs like "0.42 s",
/// the mapping should be of a type <string, float> or <string, double>.
class AsNumberWithUnit : public Validator {
public:
/// Adjust AsNumberWithUnit behavior.
/// CASE_SENSITIVE/CASE_INSENSITIVE controls how units are matched.
/// UNIT_OPTIONAL/UNIT_REQUIRED throws ValidationError
/// if UNIT_REQUIRED is set and unit literal is not found.
enum Options : std::uint8_t {
CASE_SENSITIVE = 0,
CASE_INSENSITIVE = 1,
UNIT_OPTIONAL = 0,
UNIT_REQUIRED = 2,
DEFAULT = CASE_INSENSITIVE | UNIT_OPTIONAL
};
template <typename Number>
explicit AsNumberWithUnit(std::map<std::string, Number> mapping,
Options opts = DEFAULT,
const std::string &unit_name = "UNIT") {
description(generate_description<Number>(unit_name, opts));
validate_mapping(mapping, opts);
// transform function
func_ = [mapping, opts](std::string &input) -> std::string {
Number num{};
detail::rtrim(input);
if(input.empty()) {
throw ValidationError("Input is empty");
}
// Find split position between number and prefix
auto unit_begin = input.end();
const std::locale loc{};
while(unit_begin > input.begin() && std::isalpha(*(unit_begin - 1), loc)) {
--unit_begin;
}
std::string unit{unit_begin, input.end()};
input.resize(static_cast<std::size_t>(std::distance(input.begin(), unit_begin)));
detail::trim(input);
if(opts & UNIT_REQUIRED && unit.empty()) {
throw ValidationError("Missing mandatory unit");
}
if(opts & CASE_INSENSITIVE) {
unit = detail::to_lower(unit);
}
if(unit.empty()) {
using CLI::detail::lexical_cast;
if(!lexical_cast(input, num)) {
throw ValidationError(std::string("Value ") + input + " could not be converted to " +
detail::type_name<Number>());
}
// No need to modify input if no unit passed
return {};
}
// find corresponding factor
auto it = mapping.find(unit);
if(it == mapping.end()) {
throw ValidationError(unit +
" unit not recognized. "
"Allowed values: " +
detail::generate_map(mapping, true));
}
if(!input.empty()) {
using CLI::detail::lexical_cast;
bool converted = lexical_cast(input, num);
if(!converted) {
throw ValidationError(std::string("Value ") + input + " could not be converted to " +
detail::type_name<Number>());
}
// perform safe multiplication
bool ok = detail::checked_multiply(num, it->second);
if(!ok) {
throw ValidationError(detail::to_string(num) + " multiplied by " + unit +
" factor would cause number overflow. Use smaller value.");
}
} else {
num = static_cast<Number>(it->second);
}
input = detail::to_string(num);
return {};
};
}
private:
/// Check that mapping contains valid units.
/// Update mapping for CASE_INSENSITIVE mode.
template <typename Number> static void validate_mapping(std::map<std::string, Number> &mapping, Options opts) {
for(auto &kv : mapping) {
if(kv.first.empty()) {
throw ValidationError("Unit must not be empty.");
}
if(!detail::isalpha(kv.first)) {
throw ValidationError("Unit must contain only letters.");
}
}
// make all units lowercase if CASE_INSENSITIVE
if(opts & CASE_INSENSITIVE) {
std::map<std::string, Number> lower_mapping;
for(auto &kv : mapping) {
auto s = detail::to_lower(kv.first);
if(lower_mapping.count(s)) {
throw ValidationError(std::string("Several matching lowercase unit representations are found: ") +
s);
}
lower_mapping[std::move(s)] = kv.second;
}
mapping = std::move(lower_mapping);
}
}
/// Generate description like this: NUMBER [UNIT]
template <typename Number> static std::string generate_description(const std::string &name, Options opts) {
std::stringstream out;
out << detail::type_name<Number>() << ' ';
if(opts & UNIT_REQUIRED) {
out << name;
} else {
out << '[' << name << ']';
}
return out.str();
}
};
inline AsNumberWithUnit::Options operator|(const AsNumberWithUnit::Options &a, const AsNumberWithUnit::Options &b) {
return static_cast<AsNumberWithUnit::Options>(static_cast<int>(a) | static_cast<int>(b));
}
/// Converts a human-readable size string (with unit literal) to uin64_t size.
/// Example:
/// "100" => 100
/// "1 b" => 1
/// "10Kb" => 10240 // you can configure this to be interpreted as kilobyte (*1000) or kibibyte (*1024)
/// "10 KB" => 10240
/// "10 kb" => 10240
/// "10 kib" => 10240 // *i, *ib are always interpreted as *bibyte (*1024)
/// "10kb" => 10240
/// "2 MB" => 2097152
/// "2 EiB" => 2^61 // Units up to exibyte are supported
class AsSizeValue : public AsNumberWithUnit {
public:
using result_t = std::uint64_t;
/// If kb_is_1000 is true,
/// interpret 'kb', 'k' as 1000 and 'kib', 'ki' as 1024
/// (same applies to higher order units as well).
/// Otherwise, interpret all literals as factors of 1024.
/// The first option is formally correct, but
/// the second interpretation is more wide-spread
/// (see https://en.wikipedia.org/wiki/Binary_prefix).
explicit AsSizeValue(bool kb_is_1000);
private:
/// Get <size unit, factor> mapping
static std::map<std::string, result_t> init_mapping(bool kb_is_1000);
/// Cache calculated mapping
static const std::map<std::string, result_t> &get_mapping(bool kb_is_1000);
};
#if defined(CLI11_ENABLE_EXTRA_VALIDATORS) && CLI11_ENABLE_EXTRA_VALIDATORS != 0
// new extra validators
#if CLI11_HAS_FILESYSTEM
namespace detail {
enum class Permission : std::uint8_t { none = 0, read = 1, write = 2, exec = 4 };
class PermissionValidator : public Validator {
public:
explicit PermissionValidator(Permission permission);
};
} // namespace detail
class FileSizeValidator : public Validator {
public:
explicit FileSizeValidator(std::uint64_t min_size, std::uint64_t max_size = 0);
};
/// Check that the file exist and available for read
CLI11_MODULE_INLINE const detail::PermissionValidator ReadPermissions(detail::Permission::read);
/// Check that the file exist and available for write
CLI11_MODULE_INLINE const detail::PermissionValidator WritePermissions(detail::Permission::write);
/// Check that the file exist and available for execute
CLI11_MODULE_INLINE const detail::PermissionValidator ExecPermissions(detail::Permission::exec);
/// Check that the file exists and is not empty
CLI11_MODULE_INLINE const FileSizeValidator NonEmptyFile(1, 0);
#endif
#endif
// [CLI11:extra_validators_hpp:end]
} // namespace CLI
#ifndef CLI11_COMPILE
#include "impl/ExtraValidators_inl.hpp" // IWYU pragma: export
#endif
#endif
+24
View File
@@ -0,0 +1,24 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// [CLI11:public_includes:set]
// [CLI11:public_includes:end]
#include "App.hpp"
#include "FormatterFwd.hpp"
namespace CLI {
// [CLI11:formatter_hpp:verbatim]
// [CLI11:formatter_hpp:end]
} // namespace CLI
#ifndef CLI11_COMPILE
#include "impl/Formatter_inl.hpp" // IWYU pragma: export
#endif
+255
View File
@@ -0,0 +1,255 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// [CLI11:public_includes:set]
#include <cstddef>
#include <cstdint>
#include <functional>
#include <map>
#include <string>
#include <vector>
// [CLI11:public_includes:end]
#include "StringTools.hpp"
namespace CLI {
// [CLI11:formatter_fwd_hpp:verbatim]
class Option;
class App;
/// This enum signifies the type of help requested
///
/// This is passed in by App; all user classes must accept this as
/// the second argument.
enum class AppFormatMode : std::uint8_t {
Normal, ///< The normal, detailed help
All, ///< A fully expanded help
Sub, ///< Used when printed as part of expanded subcommand
};
/// This is the minimum requirements to run a formatter.
///
/// A user can subclass this is if they do not care at all
/// about the structure in CLI::Formatter.
class FormatterBase {
protected:
/// @name Options
///@{
/// The width of the left column (options/flags/subcommands)
std::size_t column_width_{30};
/// The alignment ratio for long options within the left column
float long_option_alignment_ratio_{1 / 3.f};
/// The width of the right column (description of options/flags/subcommands)
std::size_t right_column_width_{65};
/// The width of the description paragraph at the top of help
std::size_t description_paragraph_width_{80};
/// The width of the footer paragraph
std::size_t footer_paragraph_width_{80};
/// options controlling formatting for footer and descriptions
bool enable_description_formatting_{true};
bool enable_footer_formatting_{true};
/// options controlling formatting of options
bool enable_option_defaults_{true};
bool enable_option_type_names_{true};
bool enable_default_flag_values_{true};
/// @brief The required help printout labels (user changeable)
/// Values are Needs, Excludes, etc.
std::map<std::string, std::string> labels_{};
/// Default user-facing help labels used when no override is set
static std::string default_label(const std::string &key) { return key; }
///@}
/// @name Basic
///@{
public:
FormatterBase() = default;
FormatterBase(const FormatterBase &) = default;
FormatterBase(FormatterBase &&) = default;
FormatterBase &operator=(const FormatterBase &) = default;
FormatterBase &operator=(FormatterBase &&) = default;
/// Adding a destructor in this form to work around bug in GCC 4.7
virtual ~FormatterBase() noexcept {} // NOLINT(modernize-use-equals-default)
/// This is the key method that puts together help
virtual std::string make_help(const App *, std::string, AppFormatMode) const = 0;
///@}
/// @name Setters
///@{
/// Set the "REQUIRED" or other labels
void label(std::string key, std::string val) { labels_[key] = val; }
/// Set the left column width (options/flags/subcommands)
void column_width(std::size_t val) { column_width_ = val; }
/// Set the alignment ratio for long options within the left column
/// The ratio is in [0;1] range (e.g. 0.2 = 20% of column width, 6.f/column_width = 6th character)
void long_option_alignment_ratio(float ratio);
/// Set the right column width (description of options/flags/subcommands)
void right_column_width(std::size_t val) { right_column_width_ = val; }
/// Set the description paragraph width at the top of help
void description_paragraph_width(std::size_t val) { description_paragraph_width_ = val; }
/// Set the footer paragraph width
void footer_paragraph_width(std::size_t val) { footer_paragraph_width_ = val; }
/// enable formatting for description paragraph
void enable_description_formatting(bool value = true) { enable_description_formatting_ = value; }
/// disable formatting for footer paragraph
void enable_footer_formatting(bool value = true) { enable_footer_formatting_ = value; }
/// enable option defaults to be printed
void enable_option_defaults(bool value = true) { enable_option_defaults_ = value; }
/// enable option type names to be printed
void enable_option_type_names(bool value = true) { enable_option_type_names_ = value; }
/// enable default flag values to be printed
void enable_default_flag_values(bool value = true) { enable_default_flag_values_ = value; }
///@}
/// @name Getters
///@{
/// Get the current value of a name (REQUIRED, etc.)
CLI11_NODISCARD std::string get_label(std::string key) const;
/// Get the current left column width (options/flags/subcommands)
CLI11_NODISCARD std::size_t get_column_width() const { return column_width_; }
/// Get the current right column width (description of options/flags/subcommands)
CLI11_NODISCARD std::size_t get_right_column_width() const { return right_column_width_; }
/// Get the current description paragraph width at the top of help
CLI11_NODISCARD std::size_t get_description_paragraph_width() const { return description_paragraph_width_; }
/// Get the current footer paragraph width
CLI11_NODISCARD std::size_t get_footer_paragraph_width() const { return footer_paragraph_width_; }
/// @brief Get the current alignment ratio for long options within the left column
/// @return The alignment ratio used for long options within the left column
CLI11_NODISCARD float get_long_option_alignment_ratio() const { return long_option_alignment_ratio_; }
/// Get the current status of description paragraph formatting
CLI11_NODISCARD bool is_description_paragraph_formatting_enabled() const { return enable_description_formatting_; }
/// Get the current status of whether footer paragraph formatting is enabled
CLI11_NODISCARD bool is_footer_paragraph_formatting_enabled() const { return enable_footer_formatting_; }
/// Get the current status of whether option defaults are printed
CLI11_NODISCARD bool is_option_defaults_enabled() const { return enable_option_defaults_; }
/// Get the current status of whether option type names are printed
CLI11_NODISCARD bool is_option_type_names_enabled() const { return enable_option_type_names_; }
/// Get the current status of whether default flag values are printed
CLI11_NODISCARD bool is_default_flag_values_enabled() const { return enable_default_flag_values_; }
///@}
};
/// This is a specialty override for lambda functions
class FormatterLambda final : public FormatterBase {
using funct_t = std::function<std::string(const App *, std::string, AppFormatMode)>;
/// The lambda to hold and run
funct_t lambda_;
public:
/// Create a FormatterLambda with a lambda function
explicit FormatterLambda(funct_t funct);
/// Adding a destructor (mostly to make GCC 4.7 happy)
~FormatterLambda() noexcept override {} // NOLINT(modernize-use-equals-default)
/// This will simply call the lambda function
std::string make_help(const App *app, std::string name, AppFormatMode mode) const override;
};
/// This is the default Formatter for CLI11. It pretty prints help output, and is broken into quite a few
/// overridable methods, to be highly customizable with minimal effort.
class Formatter : public FormatterBase {
public:
Formatter() = default;
Formatter(const Formatter &) = default;
Formatter(Formatter &&) = default;
Formatter &operator=(const Formatter &) = default;
Formatter &operator=(Formatter &&) = default;
/// @name Overridables
///@{
/// This prints out a group of options with title
///
CLI11_NODISCARD virtual std::string
make_group(std::string group, bool is_positional, std::vector<const Option *> opts) const;
/// This prints out just the positionals "group"
virtual std::string make_positionals(const App *app) const;
/// This prints out all the groups of options
std::string make_groups(const App *app, AppFormatMode mode) const;
/// This prints out all the subcommands
virtual std::string make_subcommands(const App *app, AppFormatMode mode) const;
/// This prints out a subcommand
virtual std::string make_subcommand(const App *sub) const;
/// This prints out a subcommand in help-all
virtual std::string make_expanded(const App *sub, AppFormatMode mode) const;
/// This prints out all the groups of options
virtual std::string make_footer(const App *app) const;
/// This displays the description line
virtual std::string make_description(const App *app) const;
/// This displays the usage line
virtual std::string make_usage(const App *app, std::string name) const;
/// This puts everything together
std::string make_help(const App *app, std::string, AppFormatMode mode) const override;
///@}
/// @name Options
///@{
/// This prints out an option help line, either positional or optional form
virtual std::string make_option(const Option *, bool) const;
/// @brief This is the name part of an option, Default: left column
virtual std::string make_option_name(const Option *, bool) const;
/// @brief This is the options part of the name, Default: combined into left column
virtual std::string make_option_opts(const Option *) const;
/// @brief This is the description. Default: Right column, on new line if left column too large
virtual std::string make_option_desc(const Option *) const;
/// @brief This is used to print the name on the USAGE line
virtual std::string make_option_usage(const Option *opt) const;
///@}
};
// [CLI11:formatter_fwd_hpp:end]
} // namespace CLI
+178
View File
@@ -0,0 +1,178 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// [CLI11:macros_hpp:verbatim]
// The following version macro is very similar to the one in pybind11
#if !(defined(_MSC_VER) && __cplusplus == 199711L) && !defined(__INTEL_COMPILER)
#if __cplusplus >= 201402L
#define CLI11_CPP14
#if __cplusplus >= 201703L
#define CLI11_CPP17
#if __cplusplus > 201703L
#define CLI11_CPP20
#if __cplusplus > 202002L
#define CLI11_CPP23
#if __cplusplus > 202302L
#define CLI11_CPP26
#endif
#endif
#endif
#endif
#endif
#elif defined(_MSC_VER) && __cplusplus == 199711L
// MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard was fully implemented)
// Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3 or newer
#if _MSVC_LANG >= 201402L
#define CLI11_CPP14
#if _MSVC_LANG > 201402L && _MSC_VER >= 1910
#define CLI11_CPP17
#if _MSVC_LANG > 201703L && _MSC_VER >= 1910
#define CLI11_CPP20
#if _MSVC_LANG > 202002L && _MSC_VER >= 1922
#define CLI11_CPP23
#endif
#endif
#endif
#endif
#endif
#if defined(CLI11_CPP14)
#define CLI11_DEPRECATED(reason) [[deprecated(reason)]]
#elif defined(_MSC_VER)
#define CLI11_DEPRECATED(reason) __declspec(deprecated(reason))
#else
#define CLI11_DEPRECATED(reason) __attribute__((deprecated(reason)))
#endif
// GCC < 10 doesn't ignore this in unevaluated contexts
#if !defined(CLI11_CPP17) || \
(defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER) && __GNUC__ < 10 && __GNUC__ > 4)
#define CLI11_NODISCARD
#else
#define CLI11_NODISCARD [[nodiscard]]
#endif
/** detection of rtti */
#ifndef CLI11_USE_STATIC_RTTI
#if (defined(_HAS_STATIC_RTTI) && _HAS_STATIC_RTTI)
#define CLI11_USE_STATIC_RTTI 1
#elif defined(__cpp_rtti)
#if (defined(_CPPRTTI) && _CPPRTTI == 0)
#define CLI11_USE_STATIC_RTTI 1
#else
#define CLI11_USE_STATIC_RTTI 0
#endif
#elif (defined(__GCC_RTTI) && __GXX_RTTI)
#define CLI11_USE_STATIC_RTTI 0
#else
#define CLI11_USE_STATIC_RTTI 1
#endif
#endif
/** <filesystem> availability */
#if defined CLI11_CPP17 && defined __has_include && !defined CLI11_HAS_FILESYSTEM
#if __has_include(<filesystem>)
// Filesystem cannot be used if targeting macOS < 10.15
#if defined __MAC_OS_X_VERSION_MIN_REQUIRED && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500
#define CLI11_HAS_FILESYSTEM 0
#elif defined(__wasi__)
// As of wasi-sdk-14, filesystem is not implemented
#define CLI11_HAS_FILESYSTEM 0
#else
#include <filesystem>
#if defined __cpp_lib_filesystem && __cpp_lib_filesystem >= 201703
#if defined _GLIBCXX_RELEASE && _GLIBCXX_RELEASE >= 9
#define CLI11_HAS_FILESYSTEM 1
#elif defined(__GLIBCXX__)
// if we are using gcc and Version <9 default to no filesystem
#define CLI11_HAS_FILESYSTEM 0
#else
#define CLI11_HAS_FILESYSTEM 1
#endif
#else
#define CLI11_HAS_FILESYSTEM 0
#endif
#endif
#endif
#endif
/** <codecvt> availability (the header is only included where it is used) */
#ifndef CLI11_HAS_CODECVT
#if defined(CLI11_CPP26)
#define CLI11_HAS_CODECVT 0
#elif defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER) && __GNUC__ < 5
#define CLI11_HAS_CODECVT 0
#else
#define CLI11_HAS_CODECVT 1
#endif
#endif
/** rtti enabled */
#ifndef CLI11_HAS_RTTI
#if defined(__GXX_RTTI) && __GXX_RTTI == 1
// gcc
#define CLI11_HAS_RTTI 1
#elif defined(_CPPRTTI) && _CPPRTTI == 1
// msvc
#define CLI11_HAS_RTTI 1
#elif defined(__NO_RTTI__) && __NO_RTTI__ == 1
// intel
#define CLI11_HAS_RTTI 0
#elif defined(__has_feature)
// clang and other newer compilers
#if __has_feature(cxx_rtti)
#define CLI11_HAS_RTTI 1
#else
#define CLI11_HAS_RTTI 0
#endif
#elif defined(__RTTI) || defined(__INTEL_RTTI__)
// more intel and some other compilers
#define CLI11_HAS_RTTI 1
#else
#define CLI11_HAS_RTTI 0
#endif
#endif
/** disable deprecations */
#if defined(__GNUC__) // GCC or clang
#define CLI11_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
#define CLI11_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
#define CLI11_DIAGNOSTIC_IGNORE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
#elif defined(_MSC_VER)
#define CLI11_DIAGNOSTIC_PUSH __pragma(warning(push))
#define CLI11_DIAGNOSTIC_POP __pragma(warning(pop))
#define CLI11_DIAGNOSTIC_IGNORE_DEPRECATED __pragma(warning(disable : 4996))
#else
#define CLI11_DIAGNOSTIC_PUSH
#define CLI11_DIAGNOSTIC_POP
#define CLI11_DIAGNOSTIC_IGNORE_DEPRECATED
#endif
/** Inline macro **/
#ifdef CLI11_COMPILE
#define CLI11_INLINE
#else
#define CLI11_INLINE inline
#endif
/** Module inline to support module operations**/
#if defined CLI11_CPP17
#define CLI11_MODULE_INLINE inline
#else
#define CLI11_MODULE_INLINE static
#endif
// [CLI11:macros_hpp:end]
+848
View File
@@ -0,0 +1,848 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// [CLI11:public_includes:set]
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iterator>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
// [CLI11:public_includes:end]
#include "Error.hpp"
#include "Macros.hpp"
#include "Split.hpp"
#include "StringTools.hpp"
#include "Validators.hpp"
namespace CLI {
// [CLI11:option_hpp:verbatim]
using results_t = std::vector<std::string>;
/// callback function definition
using callback_t = std::function<bool(const results_t &)>;
class Option;
class App;
class ConfigBase;
using Option_p = std::unique_ptr<Option>;
using Validator_p = std::shared_ptr<Validator>;
/// Enumeration of the multiOption Policy selection
enum class MultiOptionPolicy : char {
Throw, //!< Throw an error if any extra arguments were given
TakeLast, //!< take only the last Expected number of arguments
TakeFirst, //!< take only the first Expected number of arguments
Join, //!< merge all the arguments together into a single string via the delimiter character default('\n')
TakeAll, //!< just get all the passed argument regardless
Sum, //!< sum all the arguments together if numerical or concatenate directly without delimiter
Reverse, //!< take only the last Expected number of arguments in reverse order
};
/// @brief enumeration for the callback priority
enum class CallbackPriority : std::uint8_t {
FirstPreHelp = 0,
First = 1,
PreRequirementsCheckPreHelp = 2,
PreRequirementsCheck = 3,
NormalPreHelp = 4,
Normal = 5,
LastPreHelp = 6,
Last = 7
}; // namespace CLI
/// This is the CRTP base class for Option and OptionDefaults. It was designed this way
/// to share parts of the class; an OptionDefaults can copy to an Option.
template <typename CRTP> class OptionBase {
friend App;
friend ConfigBase;
protected:
/// The group membership
std::string group_ = std::string("OPTIONS");
/// True if this is a required option
bool required_{false};
/// Ignore the case when matching (option, not value)
bool ignore_case_{false};
/// Ignore underscores when matching (option, not value)
bool ignore_underscore_{false};
/// Allow this option to be given in a configuration file
bool configurable_{true};
/// Disable overriding flag values with '=value'
bool disable_flag_override_{false};
/// Specify a delimiter character for vector arguments
char delimiter_{'\0'};
/// Automatically capture default value
bool always_capture_default_{false};
/// Policy for handling multiple arguments beyond the expected Max
MultiOptionPolicy multi_option_policy_{MultiOptionPolicy::Throw};
/// Priority of callback
CallbackPriority callback_priority_{CallbackPriority::Normal};
/// Copy the contents to another similar class (one based on OptionBase)
template <typename T> void copy_to(T *other) const;
public:
// setters
/// Changes the group membership
CRTP *group(const std::string &name) {
if(!detail::valid_alias_name_string(name)) {
throw IncorrectConstruction("Group names may not contain newlines or null characters");
}
group_ = name;
return static_cast<CRTP *>(this);
}
/// Set the option as required
CRTP *required(bool value = true) {
required_ = value;
return static_cast<CRTP *>(this);
}
/// Support Plumbum term
CRTP *mandatory(bool value = true) { return required(value); }
CRTP *always_capture_default(bool value = true) {
always_capture_default_ = value;
return static_cast<CRTP *>(this);
}
// Getters
/// Get the group of this option
CLI11_NODISCARD const std::string &get_group() const { return group_; }
/// True if this is a required option
CLI11_NODISCARD bool get_required() const { return required_; }
/// The status of ignore case
CLI11_NODISCARD bool get_ignore_case() const { return ignore_case_; }
/// The status of ignore_underscore
CLI11_NODISCARD bool get_ignore_underscore() const { return ignore_underscore_; }
/// The status of configurable
CLI11_NODISCARD bool get_configurable() const { return configurable_; }
/// The status of configurable
CLI11_NODISCARD bool get_disable_flag_override() const { return disable_flag_override_; }
/// Get the current delimiter char
CLI11_NODISCARD char get_delimiter() const { return delimiter_; }
/// Return true if this will automatically capture the default value for help printing
CLI11_NODISCARD bool get_always_capture_default() const { return always_capture_default_; }
/// The status of the multi option policy
CLI11_NODISCARD MultiOptionPolicy get_multi_option_policy() const { return multi_option_policy_; }
/// The priority of callback
CLI11_NODISCARD CallbackPriority get_callback_priority() const { return callback_priority_; }
// Shortcuts for multi option policy
/// Set the multi option policy to take last
CRTP *take_last() {
auto *self = static_cast<CRTP *>(this);
self->multi_option_policy(MultiOptionPolicy::TakeLast);
return self;
}
/// Set the multi option policy to take last
CRTP *take_first() {
auto *self = static_cast<CRTP *>(this);
self->multi_option_policy(MultiOptionPolicy::TakeFirst);
return self;
}
/// Set the multi option policy to take all arguments
CRTP *take_all() {
auto self = static_cast<CRTP *>(this);
self->multi_option_policy(MultiOptionPolicy::TakeAll);
return self;
}
/// Set the multi option policy to join
CRTP *join() {
auto *self = static_cast<CRTP *>(this);
self->multi_option_policy(MultiOptionPolicy::Join);
return self;
}
/// Set the multi option policy to join with a specific delimiter
CRTP *join(char delim) {
auto self = static_cast<CRTP *>(this);
self->delimiter_ = delim;
self->multi_option_policy(MultiOptionPolicy::Join);
return self;
}
/// Allow in a configuration file
CRTP *configurable(bool value = true) {
configurable_ = value;
return static_cast<CRTP *>(this);
}
/// Allow in a configuration file
CRTP *delimiter(char value = '\0') {
delimiter_ = value;
return static_cast<CRTP *>(this);
}
};
/// This is a version of OptionBase that only supports setting values,
/// for defaults. It is stored as the default option in an App.
class OptionDefaults : public OptionBase<OptionDefaults> {
public:
OptionDefaults() = default;
// Methods here need a different implementation if they are Option vs. OptionDefault
/// Set the callback priority
OptionDefaults *callback_priority(CallbackPriority value = CallbackPriority::Normal) {
callback_priority_ = value;
return this;
}
/// Take the last argument if given multiple times
OptionDefaults *multi_option_policy(MultiOptionPolicy value = MultiOptionPolicy::Throw) {
multi_option_policy_ = value;
return this;
}
/// Ignore the case of the option name
OptionDefaults *ignore_case(bool value = true) {
ignore_case_ = value;
return this;
}
/// Ignore underscores in the option name
OptionDefaults *ignore_underscore(bool value = true) {
ignore_underscore_ = value;
return this;
}
/// Disable overriding flag values with an '=<value>' segment
OptionDefaults *disable_flag_override(bool value = true) {
disable_flag_override_ = value;
return this;
}
/// set a delimiter character to split up single arguments to treat as multiple inputs
OptionDefaults *delimiter(char value = '\0') {
delimiter_ = value;
return this;
}
};
class Option : public OptionBase<Option> {
friend App;
friend ConfigBase;
protected:
/// @name Names
///@{
/// A list of the short names (`-a`) without the leading dashes
std::vector<std::string> snames_{};
/// A list of the long names (`--long`) without the leading dashes
std::vector<std::string> lnames_{};
/// A list of the flag names with the appropriate default value, the first part of the pair should be duplicates of
/// what is in snames or lnames but will trigger a particular response on a flag
std::vector<std::pair<std::string, std::string>> default_flag_values_{};
/// a list of flag names with specified default values;
std::vector<std::string> fnames_{};
/// A positional name
std::string pname_{};
/// If given, check the environment for this option
std::string envname_{};
///@}
/// @name Help
///@{
/// The description for help strings
std::string description_{};
/// A human readable default value, either manually set, captured, or captured by default
std::string default_str_{};
/// If given, replace the text that describes the option type and usage in the help text
std::string option_text_{};
/// A human readable type value, set when App creates this
///
/// This is a lambda function so "types" can be dynamic, such as when a set prints its contents.
std::function<std::string()> type_name_{[]() { return std::string(); }};
/// Run this function to capture a default (ignore if empty)
std::function<std::string()> default_function_{};
///@}
/// @name Configuration
///@{
/// The number of arguments that make up one option. max is the nominal type size, min is the minimum number of
/// strings
int type_size_max_{1};
/// The minimum number of arguments an option should be expecting
int type_size_min_{1};
/// The minimum number of expected values
int expected_min_{1};
/// The maximum number of expected values
int expected_max_{1};
/// A list of Validators to run on each value parsed
std::vector<Validator_p> validators_{};
/// A list of options that are required with this option
std::set<Option *> needs_{};
/// A list of options that are excluded with this option
std::set<Option *> excludes_{};
///@}
/// @name Other
///@{
/// link back up to the parent App for fallthrough
App *parent_{nullptr};
/// Options store a callback to do all the work
callback_t callback_{};
///@}
/// @name Parsing results
///@{
/// complete Results of parsing
results_t results_{};
/// results after reduction
mutable results_t proc_results_{};
/// enumeration for the option state machine
enum class option_state : char {
parsing = 0, //!< The option is currently collecting parsed results
validated = 2, //!< the results have been validated
reduced = 4, //!< a subset of results has been generated
callback_run = 6, //!< the callback has been executed
};
/// Whether the callback has run (needed for INI parsing)
option_state current_option_state_{option_state::parsing};
/// Specify that extra args beyond type_size_max should be allowed
bool allow_extra_args_{false};
/// Specify that the option should act like a flag vs regular option
bool flag_like_{false};
/// Control option to run the callback to set the default
bool run_callback_for_default_{false};
/// flag indicating a separator needs to be injected after each argument call
bool inject_separator_{false};
/// flag indicating that the option should trigger the validation and callback chain on each result when loaded
bool trigger_on_result_{false};
/// flag indicating that the option should force the callback regardless if any results present
bool force_callback_{false};
/// Making an option by hand is not defined, it must be made by the App class
Option(std::string option_name,
std::string option_description,
callback_t callback,
App *parent,
bool allow_non_standard = false);
public:
/// @name Basic
///@{
Option(const Option &) = delete;
Option &operator=(const Option &) = delete;
/// Count the total number of times an option was passed
CLI11_NODISCARD std::size_t count() const { return results_.size(); }
/// True if the option was not passed
CLI11_NODISCARD bool empty() const { return results_.empty(); }
/// This bool operator returns true if any arguments were passed or the option callback is forced
explicit operator bool() const { return !empty() || force_callback_; }
/// Clear the parsed results (mostly for testing)
void clear();
///@}
/// @name Setting options
///@{
/// Set the number of expected arguments
Option *expected(int value);
/// Set the range of expected arguments
Option *expected(int value_min, int value_max);
/// Set the value of allow_extra_args which allows extra value arguments on the flag or option to be included
/// with each instance
Option *allow_extra_args(bool value = true) {
allow_extra_args_ = value;
return this;
}
/// Get the current value of allow extra args
CLI11_NODISCARD bool get_allow_extra_args() const { return allow_extra_args_; }
/// Set the value of trigger_on_parse which specifies that the option callback should be triggered on every parse
Option *trigger_on_parse(bool value = true) {
trigger_on_result_ = value;
return this;
}
/// The status of trigger on parse
CLI11_NODISCARD bool get_trigger_on_parse() const { return trigger_on_result_; }
/// Set the value of force_callback
Option *force_callback(bool value = true) {
force_callback_ = value;
return this;
}
/// The status of force_callback
CLI11_NODISCARD bool get_force_callback() const { return force_callback_; }
/// Set the value of run_callback_for_default which controls whether the callback function should be called to set
/// the default This is controlled automatically but could be manipulated by the user.
Option *run_callback_for_default(bool value = true) {
run_callback_for_default_ = value;
return this;
}
/// Get the current value of run_callback_for_default
CLI11_NODISCARD bool get_run_callback_for_default() const { return run_callback_for_default_; }
/// Set the value of callback priority which controls when the callback function should be called relative to other
/// parsing operations the default This is controlled automatically but could be manipulated by the user.
Option *callback_priority(CallbackPriority value = CallbackPriority::Normal) {
callback_priority_ = value;
return this;
}
/// Adds a shared validator
Option *check(Validator_p validator);
/// Adds a Validator with a built in type name
Option *check(Validator validator, const std::string &validator_name = "");
/// Adds a Validator. Takes a const string& and returns an error message (empty if conversion/check is okay).
Option *check(std::function<std::string(const std::string &)> validator_func,
std::string validator_description = "",
std::string validator_name = "");
/// Adds a shared Validator
Option *transform(Validator_p validator);
/// Adds a transforming Validator with a built in type name
Option *transform(Validator validator, const std::string &transform_name = "");
/// Adds a transforming Validator with a built in type name and description
Option *transform(Validator validator, const std::string &transform_description, const std::string &transform_name);
/// Adds a Validator-like function that can change result
Option *transform(const std::function<std::string(std::string)> &transform_func,
std::string transform_description = "",
std::string transform_name = "");
/// Adds a user supplied function to run on each item passed in (communicate though lambda capture)
Option *each(const std::function<void(std::string)> &func);
/// Get a named Validator
Validator *get_validator(const std::string &validator_name = "");
/// Get a Validator by index NOTE: this may not be the order of definition
Validator *get_validator(int index);
/// Sets required options
Option *needs(Option *opt);
/// Can find a string if needed
template <typename T = App> Option *needs(std::string opt_name) {
auto opt = static_cast<T *>(parent_)->get_option_no_throw(opt_name);
if(opt == nullptr) {
throw IncorrectConstruction::MissingOption(opt_name);
}
return needs(opt);
}
/// Any number supported, any mix of string and Opt
template <typename A, typename B, typename... ARG> Option *needs(A opt, B opt1, ARG... args) {
needs(opt);
return needs(opt1, args...); // NOLINT(readability-suspicious-call-argument)
}
/// Remove needs link from an option. Returns true if the option really was in the needs list.
bool remove_needs(Option *opt);
/// Sets excluded options
Option *excludes(Option *opt);
/// Can find a string if needed
template <typename T = App> Option *excludes(std::string opt_name) {
auto opt = static_cast<T *>(parent_)->get_option_no_throw(opt_name);
if(opt == nullptr) {
throw IncorrectConstruction::MissingOption(opt_name);
}
return excludes(opt);
}
/// Any number supported, any mix of string and Opt
template <typename A, typename B, typename... ARG> Option *excludes(A opt, B opt1, ARG... args) {
excludes(opt);
return excludes(opt1, args...);
}
/// Remove needs link from an option. Returns true if the option really was in the needs list.
bool remove_excludes(Option *opt);
/// Sets environment variable to read if no option given
Option *envname(std::string name) {
envname_ = std::move(name);
return this;
}
/// Ignore case
///
/// The template hides the fact that we don't have the definition of App yet.
/// You are never expected to add an argument to the template here.
template <typename T = App> Option *ignore_case(bool value = true);
/// Ignore underscores in the option names
///
/// The template hides the fact that we don't have the definition of App yet.
/// You are never expected to add an argument to the template here.
template <typename T = App> Option *ignore_underscore(bool value = true);
/// Take the last argument if given multiple times (or another policy)
Option *multi_option_policy(MultiOptionPolicy value = MultiOptionPolicy::Throw);
/// Disable flag overrides values, e.g. --flag=<value> is not allowed
Option *disable_flag_override(bool value = true) {
disable_flag_override_ = value;
return this;
}
///@}
/// @name Accessors
///@{
/// The number of arguments the option expects
CLI11_NODISCARD int get_type_size() const { return type_size_min_; }
/// The minimum number of arguments the option expects
CLI11_NODISCARD int get_type_size_min() const { return type_size_min_; }
/// The maximum number of arguments the option expects
CLI11_NODISCARD int get_type_size_max() const { return type_size_max_; }
/// Return the inject_separator flag
CLI11_NODISCARD bool get_inject_separator() const { return inject_separator_; }
/// The environment variable associated to this value
CLI11_NODISCARD std::string get_envname() const { return envname_; }
/// The set of options needed
CLI11_NODISCARD std::set<Option *> get_needs() const { return needs_; }
/// The set of options excluded
CLI11_NODISCARD std::set<Option *> get_excludes() const { return excludes_; }
/// The default value (for help printing)
CLI11_NODISCARD std::string get_default_str() const { return default_str_; }
/// Get the callback function
CLI11_NODISCARD callback_t get_callback() const { return callback_; }
/// Get the long names
CLI11_NODISCARD const std::vector<std::string> &get_lnames() const { return lnames_; }
/// Get the short names
CLI11_NODISCARD const std::vector<std::string> &get_snames() const { return snames_; }
/// Get the flag names with specified default values
CLI11_NODISCARD const std::vector<std::string> &get_fnames() const { return fnames_; }
/// Get a single name for the option, first of lname, sname, pname, envname
CLI11_NODISCARD const std::string &get_single_name() const;
/// The number of times the option expects to be included
CLI11_NODISCARD int get_expected() const { return expected_min_; }
/// The number of times the option expects to be included
CLI11_NODISCARD int get_expected_min() const { return expected_min_; }
/// The max number of times the option expects to be included
CLI11_NODISCARD int get_expected_max() const { return expected_max_; }
/// The total min number of expected string values to be used
CLI11_NODISCARD int get_items_expected_min() const { return type_size_min_ * expected_min_; }
/// Get the maximum number of items expected to be returned and used for the callback
CLI11_NODISCARD int get_items_expected_max() const {
int t = type_size_max_;
return detail::checked_multiply(t, expected_max_) ? t : detail::expected_max_vector_size;
}
/// The total min number of expected string values to be used
CLI11_NODISCARD int get_items_expected() const { return get_items_expected_min(); }
/// True if the argument can be given directly
CLI11_NODISCARD bool get_positional() const { return !pname_.empty(); }
/// True if option has at least one non-positional name
CLI11_NODISCARD bool nonpositional() const { return (!lnames_.empty() || !snames_.empty()); }
/// True if option has description
CLI11_NODISCARD bool has_description() const { return !description_.empty(); }
/// Get the description
CLI11_NODISCARD const std::string &get_description() const { return description_; }
/// Set the description
Option *description(std::string option_description) {
description_ = std::move(option_description);
return this;
}
Option *option_text(std::string text) {
option_text_ = std::move(text);
return this;
}
CLI11_NODISCARD const std::string &get_option_text() const { return option_text_; }
///@}
/// @name Help tools
///@{
/// \brief Gets a comma separated list of names.
/// Will include / prefer the positional name if positional is true.
/// If all_options is false, pick just the most descriptive name to show.
/// Use `get_name(true)` to get the positional name (replaces `get_pname`)
/// if disable_default_flag_values is true, do not include the default values for flags such as `--no-flag{false}`
CLI11_NODISCARD std::string get_name(bool positional = false, ///< Show the positional name
bool all_options = false, ///< Show every option
bool disable_default_flag_values = false ///< Disable default values in name
) const;
///@}
/// @name Parser tools
///@{
/// Process the callback
void run_callback();
/// If options share any of the same names, find it
CLI11_NODISCARD const std::string &matching_name(const Option &other) const;
/// If options share any of the same names, they are equal (not counting positional)
bool operator==(const Option &other) const { return !matching_name(other).empty(); }
/// Check a name. Requires "-" or "--" for short / long, supports positional name
CLI11_NODISCARD bool check_name(const std::string &name) const;
/// Requires "-" to be removed from string
CLI11_NODISCARD bool check_sname(std::string name) const {
return (detail::find_member(std::move(name), snames_, ignore_case_) >= 0);
}
/// Requires "--" to be removed from string
CLI11_NODISCARD bool check_lname(std::string name) const {
return (detail::find_member(std::move(name), lnames_, ignore_case_, ignore_underscore_) >= 0);
}
/// Requires "--" to be removed from string
CLI11_NODISCARD bool check_fname(std::string name) const {
if(fnames_.empty()) {
return false;
}
return (detail::find_member(std::move(name), fnames_, ignore_case_, ignore_underscore_) >= 0);
}
/// Get the value that goes for a flag, nominally gets the default value but allows for overrides if not
/// disabled
CLI11_NODISCARD std::string get_flag_value(const std::string &name, std::string input_value) const;
/// Puts a result at the end
Option *add_result(std::string s);
/// Puts a result at the end and get a count of the number of arguments actually added
Option *add_result(std::string s, int &results_added);
/// Puts a result at the end
Option *add_result(std::vector<std::string> s);
/// Get the current complete results set
CLI11_NODISCARD const results_t &results() const { return results_; }
/// Get a copy of the results
CLI11_NODISCARD results_t reduced_results() const;
/// Get the results as a specified type
template <typename T> void results(T &output) const {
bool retval = false;
if(current_option_state_ >= option_state::reduced || (results_.size() == 1 && validators_.empty())) {
const results_t &res = (proc_results_.empty()) ? results_ : proc_results_;
if(!res.empty()) {
retval = detail::lexical_conversion<T, T>(res, output);
} else {
results_t res2;
res2.emplace_back();
proc_results_ = std::move(res2);
retval = detail::lexical_conversion<T, T>(proc_results_, output);
}
} else {
results_t res;
if(results_.empty()) {
if(!default_str_.empty()) {
// _add_results takes an rvalue only
_add_result(std::string(default_str_), res);
_validate_results(res);
results_t extra;
_reduce_results(extra, res);
if(!extra.empty()) {
res = std::move(extra);
}
} else {
res.emplace_back();
}
} else {
res = reduced_results();
}
// store the results in a stable location if the output is a view
proc_results_ = std::move(res);
retval = detail::lexical_conversion<T, T>(proc_results_, output);
}
if(!retval) {
throw ConversionError(get_name(), results_);
}
}
/// Return the results as the specified type
template <typename T> CLI11_NODISCARD T as() const {
T output;
results(output);
return output;
}
/// See if the callback has been run already
CLI11_NODISCARD bool get_callback_run() const { return (current_option_state_ == option_state::callback_run); }
///@}
/// @name Custom options
///@{
/// Set the type function to run when displayed on this option
Option *type_name_fn(std::function<std::string()> typefun) {
type_name_ = std::move(typefun);
return this;
}
/// Set a custom option typestring
Option *type_name(std::string typeval);
/// Set a custom option size
Option *type_size(int option_type_size);
/// Set a custom option type size range
Option *type_size(int option_type_size_min, int option_type_size_max);
/// Set the value of the separator injection flag
void inject_separator(bool value = true) { inject_separator_ = value; }
/// Set a capture function for the default. Mostly used by App.
Option *default_function(const std::function<std::string()> &func) {
default_function_ = func;
return this;
}
/// Capture the default value from the original value (if it can be captured)
Option *capture_default_str();
/// Set the default value string representation (does not change the contained value)
Option *default_str(std::string val) {
default_str_ = std::move(val);
return this;
}
/// Set the default value and validate the results and run the callback if appropriate to set the value into the
/// bound value only available for types that can be converted to a string
template <typename X> Option *default_val(const X &val) {
std::string val_str = detail::value_string(val);
auto old_option_state = current_option_state_;
results_t old_results{std::move(results_)};
results_.clear();
try {
add_result(val_str);
// if trigger_on_result_ is set the callback already ran
if(run_callback_for_default_ && !trigger_on_result_) {
run_callback(); // run callback sets the state, we need to reset it again
current_option_state_ = option_state::parsing;
} else {
_validate_results(results_);
current_option_state_ = old_option_state;
}
} catch(const ConversionError &err) {
// this should be done
results_ = std::move(old_results);
current_option_state_ = old_option_state;
throw ConversionError(
get_name(), std::string("given default value(\"") + val_str + "\") produces an error : " + err.what());
} catch(const CLI::Error &) {
results_ = std::move(old_results);
current_option_state_ = old_option_state;
throw;
}
results_ = std::move(old_results);
default_str_ = std::move(val_str);
return this;
}
/// Get the full typename for this option
CLI11_NODISCARD std::string get_type_name() const;
private:
/// Run the results through the Validators
void _validate_results(results_t &res) const;
/** reduce the results in accordance with the MultiOptionPolicy
@param[out] out results are assigned to res if there if they are different
*/
void _reduce_results(results_t &out, const results_t &original) const;
// Run a result through the Validators
std::string _validate(std::string &result, int index) const;
/// Add a single result to the result set, taking into account delimiters
int _add_result(std::string &&result, std::vector<std::string> &res) const;
};
// [CLI11:option_hpp:end]
} // namespace CLI
#ifndef CLI11_COMPILE
#include "impl/Option_inl.hpp" // IWYU pragma: export
#endif
+51
View File
@@ -0,0 +1,51 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// [CLI11:public_includes:set]
#include <iterator>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
// [CLI11:public_includes:end]
#include "Macros.hpp"
namespace CLI {
// [CLI11:split_hpp:verbatim]
namespace detail {
// Returns false if not a short option. Otherwise, sets opt name and rest and returns true
CLI11_INLINE bool split_short(const std::string &current, std::string &name, std::string &rest);
// Returns false if not a long option. Otherwise, sets opt name and other side of = and returns true
CLI11_INLINE bool split_long(const std::string &current, std::string &name, std::string &value);
// Returns false if not a windows style option. Otherwise, sets opt name and value and returns true
CLI11_INLINE bool split_windows_style(const std::string &current, std::string &name, std::string &value);
// Splits a string into multiple long and short names
CLI11_INLINE std::vector<std::string> split_names(std::string current);
/// extract default flag values either {def} or starting with a !
CLI11_INLINE std::vector<std::pair<std::string, std::string>> get_default_flag_values(const std::string &str);
/// Get a vector of short names, one of long names, and a single name
CLI11_INLINE std::tuple<std::vector<std::string>, std::vector<std::string>, std::string>
get_names(const std::vector<std::string> &input, bool allow_non_standard = false);
} // namespace detail
// [CLI11:split_hpp:end]
} // namespace CLI
#ifndef CLI11_COMPILE
#include "impl/Split_inl.hpp" // IWYU pragma: export
#endif
+285
View File
@@ -0,0 +1,285 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// [CLI11:public_includes:set]
#include <algorithm>
#include <cstddef>
#include <initializer_list>
#include <iterator>
#include <sstream>
#include <string>
#include <type_traits>
#include <vector>
// [CLI11:public_includes:end]
#include "Macros.hpp"
namespace CLI {
// [CLI11:string_tools_hpp:verbatim]
/// Include the items in this namespace to get free conversion of enums to/from streams.
/// (This is available inside CLI as well, so CLI11 will use this without a using statement).
namespace enums {
/// output streaming for enumerations
template <typename T, typename = typename std::enable_if<std::is_enum<T>::value>::type>
std::ostream &operator<<(std::ostream &in, const T &item) {
// make sure this is out of the detail namespace otherwise it won't be found when needed
// https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
return in << +static_cast<typename std::underlying_type<T>::type>(item);
}
} // namespace enums
/// Export to CLI namespace
using enums::operator<<;
namespace detail {
/// a constant defining an expected max vector size defined to be a big number that could be multiplied by 4 and not
/// produce overflow for some expected uses
CLI11_MODULE_INLINE constexpr int expected_max_vector_size{1 << 29};
// Based on http://stackoverflow.com/questions/236129/split-a-string-in-c
/// Split a string by a delim
CLI11_INLINE std::vector<std::string> split(const std::string &s, char delim);
/// Simple function to join a string
template <typename T> std::string join(const T &v, std::string delim = ",") {
std::ostringstream s;
auto beg = std::begin(v);
auto end = std::end(v);
if(beg != end)
s << *beg++;
while(beg != end) {
s << delim << *beg++;
}
auto rval = s.str();
if(!rval.empty() && delim.size() == 1 && rval.back() == delim[0]) {
// remove trailing delimiter if the last entry was empty
rval.pop_back();
}
return rval;
}
/// Simple function to join a string from processed elements
template <typename T,
typename Callable,
typename = typename std::enable_if<!std::is_constructible<std::string, Callable>::value>::type>
std::string join(const T &v, Callable func, std::string delim = ",") {
std::ostringstream s;
auto beg = std::begin(v);
auto end = std::end(v);
auto loc = s.tellp();
while(beg != end) {
auto nloc = s.tellp();
if(nloc > loc) {
s << delim;
loc = nloc;
}
s << func(*beg++);
}
return s.str();
}
/// Join a string in reverse order
template <typename T> std::string rjoin(const T &v, std::string delim = ",") {
std::ostringstream s;
for(std::size_t start = 0; start < v.size(); start++) {
if(start > 0)
s << delim;
s << v[v.size() - start - 1];
}
return s.str();
}
// Based roughly on http://stackoverflow.com/questions/25829143/c-trim-whitespace-from-a-string
/// Trim whitespace from left of string
CLI11_INLINE std::string &ltrim(std::string &str);
/// Trim anything from left of string
CLI11_INLINE std::string &ltrim(std::string &str, const std::string &filter);
/// Trim whitespace from right of string
CLI11_INLINE std::string &rtrim(std::string &str);
/// Trim anything from right of string
CLI11_INLINE std::string &rtrim(std::string &str, const std::string &filter);
/// Trim whitespace from string
inline std::string &trim(std::string &str) { return ltrim(rtrim(str)); }
/// Trim anything from string
inline std::string &trim(std::string &str, const std::string &filter) { return ltrim(rtrim(str, filter), filter); }
/// Make a copy of the string and then trim it
inline std::string trim_copy(const std::string &str) {
std::string s = str;
return trim(s);
}
/// remove a matching pair of outer characters (front and back) from a string if both equal `key`
CLI11_INLINE std::string &remove_outer(std::string &str, char key);
/// remove quotes at the front and back of a string either '"' or '\''
CLI11_INLINE std::string &remove_quotes(std::string &str);
/// remove quotes from all elements of a string vector and process escaped components
CLI11_INLINE void remove_quotes(std::vector<std::string> &args);
/// Add a leader to the beginning of all new lines (nothing is added
/// at the start of the first line). `"; "` would be for ini files
///
/// Can't use Regex, or this would be a subs.
CLI11_INLINE std::string fix_newlines(const std::string &leader, std::string input);
/// Make a copy of the string and then trim it, any filter string can be used (any char in string is filtered)
inline std::string trim_copy(const std::string &str, const std::string &filter) {
std::string s = str;
return trim(s, filter);
}
/// Print subcommand aliases
CLI11_INLINE std::ostream &format_aliases(std::ostream &out, const std::vector<std::string> &aliases, std::size_t wid);
/// Verify the first character of an option
/// - is a trigger character, ! has special meaning and new lines would just be annoying to deal with
template <typename T> bool valid_first_char(T c) {
return ((c != '-') && (static_cast<unsigned char>(c) > 33)); // space and '!' not allowed
}
/// Verify following characters of an option
template <typename T> bool valid_later_char(T c) {
// = and : are value separators, { has special meaning for option defaults,
// and control codes other than tab would just be annoying to deal with in many places allowing space here has too
// much potential for inadvertent entry errors and bugs
return ((c != '=') && (c != ':') && (c != '{') && ((static_cast<unsigned char>(c) > 32) || c == '\t'));
}
/// Verify an option/subcommand name
CLI11_INLINE bool valid_name_string(const std::string &str);
/// Verify an app name
inline bool valid_alias_name_string(const std::string &str) {
return ((str.find_first_of('\n') == std::string::npos) && (str.find_first_of('\0') == std::string::npos));
}
/// check if a string is a container segment separator (empty or "%%")
inline bool is_separator(const std::string &str) {
return (str.empty() || (str.size() == 2 && str[0] == '%' && str[1] == '%'));
}
/// Verify that str consists of letters only
CLI11_INLINE bool isalpha(const std::string &str);
/// Return a lower case version of a string
CLI11_INLINE std::string to_lower(std::string str);
/// remove underscores from a string
inline std::string remove_underscore(std::string str) {
str.erase(std::remove(std::begin(str), std::end(str), '_'), std::end(str));
return str;
}
/// @brief get valid group separators _' + local separator if different
/// @return a string containing the group separators
CLI11_INLINE std::string get_group_separators();
/// Find and replace a substring with another substring
CLI11_INLINE std::string find_and_replace(std::string str, std::string from, std::string to);
/// check if the flag definitions has possible false flags
inline bool has_default_flag_values(const std::string &flags) {
return (flags.find_first_of("{!") != std::string::npos);
}
CLI11_INLINE void remove_default_flag_values(std::string &flags);
/// Check if a string is a member of a list of strings and optionally ignore case or ignore underscores
CLI11_INLINE std::ptrdiff_t find_member(std::string name,
const std::vector<std::string> &names,
bool ignore_case = false,
bool ignore_underscore = false);
/// Find a trigger string and call a modify callable function that takes the current string and starting position of the
/// trigger and returns the position in the string to search for the next trigger string
template <typename Callable> inline std::string find_and_modify(std::string str, std::string trigger, Callable modify) {
std::size_t start_pos = 0;
while((start_pos = str.find(trigger, start_pos)) != std::string::npos) {
start_pos = modify(str, start_pos);
}
return str;
}
/// close a sequence of characters indicated by a closure character. Brackets allows sub sequences
/// recognized bracket sequences include double quote, single quote, backquote, [, (, <, and {; other closure
/// characters are assumed to be literal strings
CLI11_INLINE std::size_t close_sequence(const std::string &str, std::size_t start, char closure_char);
/// Split a string '"one two" "three"' into 'one two', 'three'
/// Quote characters can be backquote, ' or " or bracket characters [{(< with matching to the matching bracket
CLI11_INLINE std::vector<std::string> split_up(std::string str, char delimiter = '\0');
/// get the value of an environmental variable or empty string if empty
CLI11_INLINE std::string get_environment_value(const std::string &env_name);
/// This function detects an equal or colon followed by an escaped quote after an argument
/// then modifies the string to replace the equality with a space. This is needed
/// to allow the split up function to work properly and is intended to be used with the find_and_modify function
/// the return value is the offset+1 which is required by the find_and_modify function.
CLI11_INLINE std::size_t escape_detect(std::string &str, std::size_t offset);
/// @brief detect if a string has escapable characters
/// @param str the string to do the detection on
/// @return true if the string has escapable characters
CLI11_INLINE bool has_escapable_character(const std::string &str);
/// @brief escape all escapable characters
/// @param str the string to escape
/// @return a string with the escapable characters escaped with '\'
CLI11_INLINE std::string add_escaped_characters(const std::string &str);
/// @brief replace the escaped characters with their equivalent
CLI11_INLINE std::string remove_escaped_characters(const std::string &str);
/// generate a string with all non printable characters escaped to hex codes
CLI11_INLINE std::string binary_escape_string(const std::string &string_to_escape, bool force = false);
CLI11_INLINE bool is_binary_escaped_string(const std::string &escaped_string);
/// extract an escaped binary_string
CLI11_INLINE std::string extract_binary_string(const std::string &escaped_string);
/// escape an array-like string so it cannot be interpreted as a secondary array
CLI11_INLINE void handle_secondary_array(std::string &str);
/// process a quoted string, remove the quotes and if appropriate handle escaped characters
CLI11_INLINE bool process_quoted_string(std::string &str,
char string_char = '\"',
char literal_char = '\'',
bool disable_secondary_array_processing = false);
/// This function formats the given text as a paragraph with fixed width and applies correct line wrapping
/// with a custom line prefix. The paragraph will get streamed to the given ostream.
CLI11_INLINE std::ostream &streamOutAsParagraph(std::ostream &out,
const std::string &text,
std::size_t paragraphWidth,
const std::string &linePrefix = "",
bool skipPrefixOnFirstLine = false);
} // namespace detail
// [CLI11:string_tools_hpp:end]
} // namespace CLI
#ifndef CLI11_COMPILE
#include "impl/StringTools_inl.hpp" // IWYU pragma: export
#endif
+130
View File
@@ -0,0 +1,130 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
#include <cmath>
#include <array>
#include <chrono>
#include <cstdio>
#include <functional>
#include <iostream>
#include <string>
#include <utility>
namespace CLI {
/// This is a simple timer with pretty printing. Creating the timer starts counting.
class Timer {
protected:
/// This is a typedef to make clocks easier to use
using clock = std::chrono::steady_clock;
/// This typedef is for points in time
using time_point = std::chrono::time_point<clock>;
/// This is the type of a printing function, you can make your own
using time_print_t = std::function<std::string(std::string, std::string)>;
/// This is the title of the timer
std::string title_;
/// This is the function that is used to format most of the timing message
time_print_t time_print_;
/// This is the starting point (when the timer was created)
time_point start_;
/// This is the number of times cycles (print divides by this number)
std::size_t cycles{1};
public:
/// Standard print function, this one is set by default
static std::string Simple(std::string title, std::string time) { return title + ": " + time; }
/// This is a fancy print function with --- headers
static std::string Big(std::string title, std::string time) {
return std::string("-----------------------------------------\n") + "| " + title + " | Time = " + time + "\n" +
"-----------------------------------------";
}
public:
/// Standard constructor, can set title and print function
explicit Timer(std::string title = "Timer", time_print_t time_print = Simple)
: title_(std::move(title)), time_print_(std::move(time_print)), start_(clock::now()) {}
/// Time a function by running it multiple times. Target time is the len to target.
std::string time_it(std::function<void()> f, double target_time = 1) {
time_point start = start_;
double total_time = NAN;
start_ = clock::now();
std::size_t n = 0;
do {
f();
std::chrono::duration<double> elapsed = clock::now() - start_;
total_time = elapsed.count();
} while(n++ < 100u && total_time < target_time);
std::string out = make_time_str(total_time / static_cast<double>(n)) + " for " + std::to_string(n) + " tries";
start_ = start;
return out;
}
/// This formats the numerical value for the time string
std::string make_time_str() const { // NOLINT(modernize-use-nodiscard)
time_point stop = clock::now();
std::chrono::duration<double> elapsed = stop - start_;
double time = elapsed.count() / static_cast<double>(cycles);
return make_time_str(time);
}
// LCOV_EXCL_START
/// This prints out a time string from a time
std::string make_time_str(double time) const { // NOLINT(modernize-use-nodiscard)
auto print_it = [](double x, std::string unit) {
const unsigned int buffer_length = 50;
std::array<char, buffer_length> buffer;
std::snprintf(buffer.data(), buffer_length, "%.5g", x);
return buffer.data() + std::string(" ") + unit;
};
if(time < .000001)
return print_it(time * 1000000000, "ns");
if(time < .001)
return print_it(time * 1000000, "us");
if(time < 1)
return print_it(time * 1000, "ms");
return print_it(time, "s");
}
// LCOV_EXCL_STOP
/// This is the main function, it creates a string
std::string to_string() const { return time_print_(title_, make_time_str()); } // NOLINT(modernize-use-nodiscard)
/// Division sets the number of cycles to divide by (no graphical change)
Timer &operator/(std::size_t val) {
cycles = val;
return *this;
}
};
/// This class prints out the time upon destruction
class AutoTimer : public Timer {
public:
using Timer::Timer;
/// This destructor prints the string
~AutoTimer() { std::cout << to_string() << '\n'; }
};
} // namespace CLI
/// This prints out the time if shifted into a std::cout like stream.
inline std::ostream &operator<<(std::ostream &in, const CLI::Timer &timer) { return in << timer.to_string(); }
File diff suppressed because it is too large Load Diff
+326
View File
@@ -0,0 +1,326 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
#include "Error.hpp"
#include "Macros.hpp"
#include "StringTools.hpp"
#include "TypeTools.hpp"
// [CLI11:public_includes:set]
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <iterator>
#include <limits>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
// [CLI11:public_includes:end]
// [CLI11:validators_hpp_filesystem:verbatim]
#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
#include <filesystem>
#else
#include <sys/stat.h>
#include <sys/types.h>
#endif
// [CLI11:validators_hpp_filesystem:end]
namespace CLI {
// [CLI11:validators_hpp:verbatim]
class Option;
/// @defgroup validator_group Validators
/// @brief Some validators that are provided
///
/// These are simple `std::string(const std::string&)` validators that are useful. They return
/// a string if the validation fails. A custom struct is provided, as well, with the same user
/// semantics, but with the ability to provide a new type name.
/// @{
///
class Validator {
protected:
/// This is the description function, if empty the description_ will be used
std::function<std::string()> desc_function_{[]() { return std::string{}; }};
/// This is the base function that is to be called.
/// Returns a string error message if validation fails.
std::function<std::string(std::string &)> func_{[](std::string &) { return std::string{}; }};
/// The name for search purposes of the Validator
std::string name_{};
/// A Validator will only apply to an indexed value (-1 is all elements)
int application_index_ = -1;
/// Enable for Validator to allow it to be disabled if need be
bool active_{true};
/// specify that a validator should not modify the input
bool non_modifying_{false};
Validator(std::string validator_desc, std::function<std::string(std::string &)> func);
public:
Validator() = default;
/// Construct a Validator with just the description string
explicit Validator(std::string validator_desc) : desc_function_([validator_desc]() { return validator_desc; }) {}
/// Construct Validator from basic information
Validator(std::function<std::string(std::string &)> op,
std::string validator_desc,
std::string validator_name = "");
/// Set the Validator operation function
Validator &operation(std::function<std::string(std::string &)> op) {
func_ = std::move(op);
return *this;
}
/// This is the required operator for a Validator - provided to help
/// users (CLI11 uses the member `func` directly)
std::string operator()(std::string &str) const;
/// This is the required operator for a Validator - provided to help
/// users (CLI11 uses the member `func` directly)
std::string operator()(const std::string &str) const;
/// Specify the type string
Validator &description(std::string validator_desc) {
desc_function_ = [validator_desc]() { return validator_desc; };
return *this;
}
/// Specify the type string
CLI11_NODISCARD Validator description(std::string validator_desc) const;
/// Generate type description information for the Validator
CLI11_NODISCARD std::string get_description() const;
/// Specify the type string
Validator &name(std::string validator_name) {
name_ = std::move(validator_name);
return *this;
}
/// Specify the type string
CLI11_NODISCARD Validator name(std::string validator_name) const;
/// Get the name of the Validator
CLI11_NODISCARD const std::string &get_name() const { return name_; }
/// Specify whether the Validator is active or not
Validator &active(bool active_val = true) {
active_ = active_val;
return *this;
}
/// Specify whether the Validator is active or not
CLI11_NODISCARD Validator active(bool active_val = true) const;
/// Specify whether the Validator can be modifying or not
Validator &non_modifying(bool no_modify = true) {
non_modifying_ = no_modify;
return *this;
}
/// Specify the application index of a validator
Validator &application_index(int app_index) {
application_index_ = app_index;
return *this;
}
/// Specify the application index of a validator
CLI11_NODISCARD Validator application_index(int app_index) const;
/// Get the current value of the application index
CLI11_NODISCARD int get_application_index() const { return application_index_; }
/// Get a boolean if the validator is active
CLI11_NODISCARD bool get_active() const { return active_; }
/// Get a boolean if the validator is allowed to modify the input returns true if it can modify the input
CLI11_NODISCARD bool get_modifying() const { return !non_modifying_; }
/// Combining validators is a new validator. Type comes from left validator if function, otherwise only set if the
/// same.
Validator operator&(const Validator &other) const;
/// Combining validators is a new validator. Type comes from left validator if function, otherwise only set if the
/// same.
Validator operator|(const Validator &other) const;
/// Create a validator that fails when a given validator succeeds
Validator operator!() const;
private:
void _merge_description(const Validator &val1, const Validator &val2, const std::string &merger);
};
/// Alias for Validator for custom Validator for clarity
using CustomValidator = Validator;
// The implementation of the built in validators is using the Validator class;
// the user is only expected to use the const (static) versions (since there's no setup).
// Therefore, this is in detail.
namespace detail {
/// CLI enumeration of different file types
enum class path_type : std::uint8_t { nonexistent, file, directory };
/// get the type of the path from a file name
CLI11_INLINE path_type check_path(const char *file) noexcept;
// Static is not needed here, because global const implies static.
/// Check for an existing file (returns error message if check fails)
class ExistingFileValidator : public Validator {
public:
ExistingFileValidator();
};
/// Check for an existing directory (returns error message if check fails)
class ExistingDirectoryValidator : public Validator {
public:
ExistingDirectoryValidator();
};
/// Check for an existing path
class ExistingPathValidator : public Validator {
public:
ExistingPathValidator();
};
/// Check for an non-existing path
class NonexistentPathValidator : public Validator {
public:
NonexistentPathValidator();
};
class EscapedStringTransformer : public Validator {
public:
EscapedStringTransformer();
};
} // namespace detail
/// Check for existing file (returns error message if check fails)
CLI11_MODULE_INLINE const detail::ExistingFileValidator ExistingFile;
/// Check for an existing directory (returns error message if check fails)
CLI11_MODULE_INLINE const detail::ExistingDirectoryValidator ExistingDirectory;
/// Check for an existing path
CLI11_MODULE_INLINE const detail::ExistingPathValidator ExistingPath;
/// Check for an non-existing path
CLI11_MODULE_INLINE const detail::NonexistentPathValidator NonexistentPath;
/// convert escaped characters into their associated values
CLI11_MODULE_INLINE const detail::EscapedStringTransformer EscapedString;
/// Modify a path if the file is a particular default location, can be used as Check or transform
/// with the error return optionally disabled
class FileOnDefaultPath : public Validator {
public:
explicit FileOnDefaultPath(std::string default_path, bool enableErrorReturn = true);
};
/// Produce a range (factory). Min and max are inclusive.
class Range : public Validator {
public:
/// This produces a range with min and max inclusive.
///
/// Note that the constructor is templated, but the struct is not, so C++17 is not
/// needed to provide nice syntax for Range(a,b).
template <typename T>
Range(T min_val, T max_val, const std::string &validator_name = std::string{}) : Validator(validator_name) {
if(validator_name.empty()) {
std::stringstream out;
out << detail::type_name<T>() << " in [" << min_val << " - " << max_val << "]";
description(out.str());
}
func_ = [min_val, max_val](std::string &input) {
using CLI::detail::lexical_cast;
T val;
bool converted = lexical_cast(input, val);
if((!converted) || (val < min_val || val > max_val)) {
std::stringstream out;
out << "Value " << input << " not in range [";
out << min_val << " - " << max_val << "]";
return out.str();
}
return std::string{};
};
}
/// Range of one value is 0 to value
template <typename T>
explicit Range(T max_val, const std::string &validator_name = std::string{})
: Range(static_cast<T>(0), max_val, validator_name) {}
};
/// Check for a non negative number
CLI11_MODULE_INLINE const Range NonNegativeNumber((std::numeric_limits<double>::max)(), "NONNEGATIVE");
/// Check for a positive valued number (val>0.0), <double>::denorm_min is the smallest positive number
CLI11_MODULE_INLINE const
Range PositiveNumber((std::numeric_limits<double>::denorm_min)(), (std::numeric_limits<double>::max)(), "POSITIVE");
namespace detail {
// the following suggestion was made by Nikita Ofitserov(@himikof)
// done in templates to prevent compiler warnings on negation of unsigned numbers
/// Do a check for overflow on signed numbers
template <typename T>
inline typename std::enable_if<std::is_signed<T>::value, bool>::type overflowCheck(const T &a, const T &b) {
if((a > 0) == (b > 0)) {
return ((std::numeric_limits<T>::max)() / (std::abs)(a) < (std::abs)(b));
}
return ((std::numeric_limits<T>::min)() / (std::abs)(a) > -(std::abs)(b));
}
/// Do a check for overflow on unsigned numbers
template <typename T>
inline typename std::enable_if<!std::is_signed<T>::value, bool>::type overflowCheck(const T &a, const T &b) {
return ((std::numeric_limits<T>::max)() / a < b);
}
/// Performs a *= b; if it doesn't cause integer overflow. Returns false otherwise.
template <typename T> typename std::enable_if<std::is_integral<T>::value, bool>::type checked_multiply(T &a, T b) {
if(a == 0 || b == 0 || a == 1 || b == 1) {
a *= b;
return true;
}
if(a == (std::numeric_limits<T>::min)() || b == (std::numeric_limits<T>::min)()) {
return false;
}
if(overflowCheck(a, b)) {
return false;
}
a *= b;
return true;
}
/// Performs a *= b; if it doesn't equal infinity. Returns false otherwise.
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type checked_multiply(T &a, T b) {
T c = a * b;
if(std::isinf(c) && !std::isinf(a) && !std::isinf(b)) {
return false;
}
a = c;
return true;
}
/// Split a string into a program name and command line arguments
/// the string is assumed to contain a file name followed by other arguments
/// the return value contains is a pair with the first argument containing the program name and the second
/// everything else.
CLI11_INLINE std::pair<std::string, std::string> split_program_name(std::string commandline);
} // namespace detail
/// @}
// [CLI11:validators_hpp:end]
} // namespace CLI
#ifndef CLI11_COMPILE
#include "impl/Validators_inl.hpp" // IWYU pragma: export
#endif
+18
View File
@@ -0,0 +1,18 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// [CLI11:version_hpp:verbatim]
#define CLI11_VERSION_MAJOR 2
#define CLI11_VERSION_MINOR 7
#define CLI11_VERSION_PATCH 2
#define CLI11_VERSION "2.7.2"
// [CLI11:version_hpp:end]
File diff suppressed because it is too large Load Diff
+96
View File
@@ -0,0 +1,96 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// This include is only needed for IDEs to discover symbols
#include "../Argv.hpp"
#include "../Encoding.hpp"
// [CLI11:public_includes:set]
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
// [CLI11:public_includes:end]
// [CLI11:argv_inl_includes:verbatim]
#if defined(_WIN32)
#if !(defined(_AMD64_) || defined(_X86_) || defined(_ARM_))
#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || \
defined(_M_AMD64)
#define _AMD64_
#elif defined(i386) || defined(__i386) || defined(__i386__) || defined(__i386__) || defined(_M_IX86)
#define _X86_
#elif defined(__arm__) || defined(_M_ARM) || defined(_M_ARMT)
#define _ARM_
#elif defined(__aarch64__) || defined(_M_ARM64)
#define _ARM64_
#elif defined(_M_ARM64EC)
#define _ARM64EC_
#endif
#endif
// first
#ifndef NOMINMAX
// if NOMINMAX is already defined we don't want to mess with that either way
#define NOMINMAX
#include <windef.h>
#undef NOMINMAX
#else
#include <windef.h>
#endif
// second
#include <winbase.h>
// third
#include <processthreadsapi.h>
#include <shellapi.h>
// CommandLineToArgvW lives in shell32. CMake/Bazel already link it when using the
// CLI11 targets; this pragma covers MSVC/clang-cl consumers that only include the
// headers (or clear CMAKE_CXX_STANDARD_LIBRARIES). See #1053 and
// https://learn.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp#lib
#if defined(_MSC_VER)
#pragma comment(lib, "shell32.lib")
#endif
#endif
// [CLI11:argv_inl_includes:end]
namespace CLI {
// [CLI11:argv_inl_hpp:verbatim]
namespace detail {
#ifdef _WIN32
CLI11_INLINE std::vector<std::string> compute_win32_argv() {
std::vector<std::string> result;
int argc = 0;
auto deleter = [](wchar_t **ptr) { LocalFree(ptr); };
// NOLINTBEGIN(*-avoid-c-arrays)
auto wargv = std::unique_ptr<wchar_t *[], decltype(deleter)>(CommandLineToArgvW(GetCommandLineW(), &argc), deleter);
// NOLINTEND(*-avoid-c-arrays)
if(wargv == nullptr) {
throw std::runtime_error("CommandLineToArgvW failed with code " + std::to_string(GetLastError()));
}
result.reserve(static_cast<size_t>(argc));
for(size_t i = 0; i < static_cast<size_t>(argc); ++i) {
result.push_back(narrow(wargv[i]));
}
return result;
}
#endif
} // namespace detail
// [CLI11:argv_inl_hpp:end]
} // namespace CLI
+811
View File
@@ -0,0 +1,811 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// This include is only needed for IDEs to discover symbols
#include "../Config.hpp"
#include "../Encoding.hpp"
// [CLI11:public_includes:set]
#include <algorithm>
#include <cctype>
#include <cstddef>
#include <fstream>
#include <functional>
#include <locale>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// [CLI11:public_includes:end]
namespace CLI {
// [CLI11:config_inl_hpp:verbatim]
CLI11_NODISCARD CLI11_INLINE std::string ConfigItem::fullname() const {
std::vector<std::string> tmp = parents;
tmp.emplace_back(name);
return detail::join(tmp, ".");
(void)multiline; // suppression for cppcheck false positive
}
CLI11_INLINE std::string
Config::to_config(const App *app, ConfigOutputMode mode, bool write_description, std::string prefix) const {
return to_config(app, mode != ConfigOutputMode::Active, write_description, std::move(prefix));
}
CLI11_NODISCARD CLI11_INLINE std::string Config::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()); // LCOV_EXCL_LINE
}
CLI11_INLINE std::vector<ConfigItem> Config::from_file(const std::string &name) const {
#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
std::ifstream input{to_path(name)};
#else
std::ifstream input{name};
#endif
if(!input.good())
throw FileError::Missing(name);
return from_config(input);
}
static constexpr auto multiline_literal_quote = R"(''')";
static constexpr auto multiline_string_quote = R"(""")";
namespace detail {
CLI11_INLINE bool is_printable(const std::string &test_string) {
return std::all_of(test_string.begin(), test_string.end(), [](char x) {
return (isprint(static_cast<unsigned char>(x)) != 0 || x == '\n' || x == '\t');
});
}
CLI11_INLINE std::string
convert_arg_for_ini(const std::string &arg, char stringQuote, char literalQuote, bool disable_multi_line) {
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) {
using CLI::detail::lexical_cast;
double val = 0.0;
if(lexical_cast(arg, val)) {
if(arg.find_first_not_of("0123456789.-+eE") == std::string::npos) {
return arg;
}
}
}
// just quote a single non numeric character
if(arg.size() == 1) {
if(isprint(static_cast<unsigned char>(arg.front())) == 0) {
return binary_escape_string(arg);
}
if(arg == "'") {
return std::string(1, stringQuote) + "'" + stringQuote;
}
return std::string(1, literalQuote) + arg + literalQuote;
}
// 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(!is_printable(arg)) {
return binary_escape_string(arg);
}
if(detail::has_escapable_character(arg)) {
if(arg.size() > 100 && !disable_multi_line) {
if(arg.find(multiline_literal_quote) != std::string::npos) {
return binary_escape_string(arg, true);
}
std::string return_string{multiline_literal_quote};
return_string.reserve(7 + arg.size());
if(arg.front() == '\n') {
return_string.push_back('\n');
}
return_string.append(arg);
if(arg.back() == '\n') {
return_string.push_back('\n');
}
return_string.append(multiline_literal_quote, 3);
return return_string;
}
return std::string(1, stringQuote) + detail::add_escaped_characters(arg) + stringQuote;
}
return std::string(1, stringQuote) + arg + stringQuote;
}
CLI11_INLINE std::string ini_join(const std::vector<std::string> &args,
char sepChar,
char arrayStart,
char arrayEnd,
char stringQuote,
char literalQuote) {
bool disable_multi_line{false};
std::string joined;
if(args.size() > 1 && arrayStart != '\0') {
joined.push_back(arrayStart);
disable_multi_line = true;
}
const bool sep_is_space = std::isspace<char>(sepChar, std::locale());
std::size_t start = 0;
for(const auto &arg : args) {
if(start++ > 0) {
joined.push_back(sepChar);
if(!sep_is_space) {
joined.push_back(' ');
}
}
joined.append(convert_arg_for_ini(arg, stringQuote, literalQuote, disable_multi_line));
}
if(args.size() > 1 && arrayEnd != '\0') {
joined.push_back(arrayEnd);
}
return joined;
}
CLI11_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_up(section, parentSeparator);
} else {
parents = {section};
}
}
if(name.find(parentSeparator) != std::string::npos) {
std::vector<std::string> plist = detail::split_up(name, parentSeparator);
name = plist.back();
plist.pop_back();
parents.insert(parents.end(), plist.begin(), plist.end());
}
// clean up quotes on the parents
try {
detail::remove_quotes(parents);
} catch(const std::invalid_argument &iarg) {
throw CLI::ParseError(iarg.what(), CLI::ExitCodes::InvalidError);
}
return parents;
}
CLI11_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 = "++";
}
/// @brief checks if a string represents a multiline comment
CLI11_INLINE bool hasMLString(std::string const &fullString, char check) {
if(fullString.length() < 3) {
return false;
}
auto it = fullString.rbegin();
return (*it == check) && (*(it + 1) == check) && (*(it + 2) == check);
}
/// @brief find a matching configItem in a list
CLI11_INLINE auto find_matching_config(std::vector<ConfigItem> &items,
const std::vector<std::string> &parents,
const std::string &name,
bool fullSearch) -> decltype(items.begin()) {
if(items.empty()) {
return items.end();
}
auto search = items.end() - 1;
do {
if(search->parents == parents && search->name == name) {
return search;
}
if(search == items.begin()) {
break;
}
--search;
} while(fullSearch);
return items.end();
}
CLI11_INLINE void clean_name_string(std::string &name, const std::string &keyChars) {
if(name.find_first_of(keyChars) != std::string::npos || (name.front() == '[' && name.back() == ']') ||
(name.find_first_of("'`\"\\") != std::string::npos)) {
if(name.find_first_of('\'') == std::string::npos) {
name.insert(0, 1, '\'');
name.push_back('\'');
} else {
if(detail::has_escapable_character(name)) {
name = detail::add_escaped_characters(name);
}
name.insert(0, 1, '\"');
name.push_back('\"');
}
}
}
} // namespace detail
CLI11_INLINE std::vector<ConfigItem> ConfigBase::from_config(std::istream &input) const {
std::string line;
std::string buffer;
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};
bool inMLineComment{false};
bool inMLineValue{false};
char aStart = (isINIArray) ? '[' : arrayStart;
char aEnd = (isINIArray) ? ']' : arrayEnd;
char aSep = (isINIArray && arraySeparator == ' ') ? ',' : arraySeparator;
int currentSectionIndex{0};
std::string line_sep_chars{parentSeparatorChar, commentChar, valueDelimiter};
while(getline(input, buffer)) {
std::vector<std::string> items_buffer;
std::string name;
line = detail::trim_copy(buffer);
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.compare(0, 3, multiline_string_quote) == 0 || line.compare(0, 3, multiline_literal_quote) == 0) {
// check if the multiline comment opens and closes on the same line; the opening quotes
// themselves must not be counted as the closer hence the length requirement
if(len >= 6 && detail::hasMLString(line, line.front())) {
continue;
}
inMLineComment = true;
auto cchar = line.front();
while(inMLineComment) {
if(getline(input, line)) {
detail::trim(line);
} else {
break;
}
if(detail::hasMLString(line, cchar)) {
inMLineComment = false;
}
}
continue;
}
// strip a trailing comment (quote aware) for section headers so that "[section] # comment"
// is recognized as a section; value lines handle their own trailing comments later
if(line.front() == '[' && line.back() != ']' && line.find_first_of(commentChar) != std::string::npos) {
std::size_t comment_search = 0;
while(comment_search < line.size()) {
auto test_char = line[comment_search];
if(test_char == '\"' || test_char == '\'' || test_char == '`') {
comment_search = detail::close_sequence(line, comment_search, line[comment_search]);
++comment_search;
} else if(test_char == commentChar) {
break;
} else {
++comment_search;
}
}
if(comment_search < line.size() && line[comment_search] == commentChar) {
line = detail::trim_copy(line.substr(0, comment_search));
len = line.length();
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;
}
std::size_t search_start = 0;
if(line.find_first_of("\"'`") != std::string::npos) {
while(search_start < line.size()) {
auto test_char = line[search_start];
if(test_char == '\"' || test_char == '\'' || test_char == '`') {
search_start = detail::close_sequence(line, search_start, line[search_start]);
++search_start;
} else if(test_char == valueDelimiter || test_char == commentChar) {
--search_start;
break;
} else if(test_char == ' ' || test_char == '\t' || test_char == parentSeparatorChar) {
++search_start;
} else {
search_start = line.find_first_of(line_sep_chars, search_start);
}
}
}
// Find = in string, split and recombine
auto delimiter_pos = line.find_first_of(valueDelimiter, search_start + 1);
auto comment_pos = line.find_first_of(commentChar, search_start);
if(comment_pos < delimiter_pos) {
delimiter_pos = std::string::npos;
}
if(delimiter_pos != std::string::npos) {
name = detail::trim_copy(line.substr(0, delimiter_pos));
std::string item = detail::trim_copy(line.substr(delimiter_pos + 1, std::string::npos));
bool mlquote =
(item.compare(0, 3, multiline_literal_quote) == 0 || item.compare(0, 3, multiline_string_quote) == 0);
if(!mlquote && comment_pos != std::string::npos) {
auto citems = detail::split_up(item, commentChar);
item = detail::trim_copy(citems.front());
}
if(mlquote) {
// multiline string
auto keyChar = item.front();
auto offset = buffer.find_first_not_of(" \t");
item = buffer.substr((offset == std::string::npos ? 0 : offset) + delimiter_pos + 1, std::string::npos);
detail::ltrim(item);
item.erase(0, 3);
inMLineValue = true;
bool lineExtension{false};
bool firstLine = true;
if(!item.empty() && item.back() == '\\' && keyChar == '\"') {
item.pop_back();
lineExtension = true;
} else if(detail::hasMLString(item, keyChar)) {
// deal with the first line closing the multiline literal
item.pop_back();
item.pop_back();
item.pop_back();
if(keyChar == '\"') {
try {
item = detail::remove_escaped_characters(item);
} catch(const std::invalid_argument &iarg) {
throw CLI::ParseError(iarg.what(), CLI::ExitCodes::InvalidError);
}
}
inMLineValue = false;
}
while(inMLineValue) {
std::string l2;
if(!std::getline(input, l2)) {
break;
}
line = l2;
detail::rtrim(line);
if(detail::hasMLString(line, keyChar)) {
line.pop_back();
line.pop_back();
line.pop_back();
if(lineExtension) {
detail::ltrim(line);
} else if(!(firstLine && item.empty())) {
item.push_back('\n');
}
firstLine = false;
item += line;
inMLineValue = false;
if(!item.empty() && item.back() == '\n') {
item.pop_back();
}
if(keyChar == '\"') {
try {
item = detail::remove_escaped_characters(item);
} catch(const std::invalid_argument &iarg) {
throw CLI::ParseError(iarg.what(), CLI::ExitCodes::InvalidError);
}
}
} else {
if(lineExtension) {
detail::trim(l2);
} else if(!(firstLine && item.empty())) {
item.push_back('\n');
}
lineExtension = false;
firstLine = false;
if(!l2.empty() && l2.back() == '\\' && keyChar == '\"') {
lineExtension = true;
l2.pop_back();
}
item += l2;
}
}
items_buffer = {item};
} else if(!item.empty() && item.front() == aStart) {
for(std::string multiline; item.back() != aEnd && std::getline(input, multiline);) {
detail::trim(multiline);
item += multiline;
}
if(item.back() == aEnd) {
items_buffer = detail::split_up(item.substr(1, item.length() - 2), aSep);
} else {
items_buffer = detail::split_up(item.substr(1, std::string::npos), 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, '\0');
} else {
items_buffer = {item};
}
} else {
name = detail::trim_copy(line.substr(0, comment_pos));
items_buffer = {"true"};
}
std::vector<std::string> parents;
try {
parents = detail::generate_parents(currentSection, name, parentSeparatorChar);
detail::process_quoted_string(name, '"', '\'', true);
// clean up quotes on the items and check for escaped strings
for(auto &it : items_buffer) {
detail::process_quoted_string(it, stringQuote, literalQuote);
}
} catch(const std::invalid_argument &ia) {
throw CLI::ParseError(ia.what(), CLI::ExitCodes::InvalidError);
}
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;
}
auto match = detail::find_matching_config(output, parents, name, allowMultipleDuplicateFields);
if(match != output.end()) {
if((match->inputs.size() > 1 && items_buffer.size() > 1) || allowMultipleDuplicateFields) {
// insert a separator if one is not already present
if(!(match->inputs.back().empty() || items_buffer.front().empty() || match->inputs.back() == "%%" ||
items_buffer.front() == "%%")) {
match->inputs.emplace_back("%%");
match->multiline = true;
}
}
match->inputs.insert(match->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;
}
CLI11_INLINE std::string
ConfigBase::to_config(const App *app, bool default_also, bool write_description, std::string prefix) const {
return to_config(app,
default_also ? ConfigOutputMode::AllDefaults : ConfigOutputMode::Active,
write_description,
std::move(prefix));
}
CLI11_INLINE std::string
ConfigBase::to_config(const App *app, ConfigOutputMode mode, bool write_description, std::string prefix) const {
std::stringstream out;
const bool include_default_values = (mode != ConfigOutputMode::Active);
std::string commentLead;
commentLead.push_back(commentChar);
commentLead.push_back(' ');
std::string commentTest = "#;";
commentTest.push_back(commentChar);
commentTest.push_back(parentSeparatorChar);
std::string keyChars = commentTest;
keyChars.push_back(literalQuote);
keyChars.push_back(stringQuote);
keyChars.push_back(arrayStart);
keyChars.push_back(arrayEnd);
keyChars.push_back(valueDelimiter);
keyChars.push_back(arraySeparator);
std::vector<std::string> groups = app->get_groups();
bool defaultUsed = false;
groups.insert(groups.begin(), std::string("OPTIONS"));
const std::vector<const Option *> options = app->get_options({});
for(auto &group : groups) {
if(group == "OPTIONS" || group.empty()) {
if(defaultUsed) {
continue;
}
defaultUsed = true;
}
if(write_description && group != "OPTIONS" && !group.empty()) {
out << '\n' << commentChar << 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 single_name = opt->get_single_name();
if(single_name.empty()) {
continue;
}
auto results = opt->reduced_results();
if(results.size() > 1 && opt->get_multi_option_policy() == CLI::MultiOptionPolicy::Reverse) {
std::reverse(results.begin(), results.end());
}
if(opt->get_multi_option_policy() == CLI::MultiOptionPolicy::Sum && opt->count() >= 1 &&
results.size() == 1) {
// if the multi option policy is sum then there is a possibility of incorrect fields being produced
// best to just use the original data for config files
auto pos = opt->_validate(results[0], 0);
if(!pos.empty()) {
results = opt->results();
}
}
if(opt->get_multi_option_policy() == CLI::MultiOptionPolicy::Join && opt->count() > 1) {
char delim = opt->get_delimiter();
if(delim == '\0') {
// this branch deals with a situation where the output would not be readable by a config file
results = opt->results();
} else {
// this branch deals with the case of the strings containing the delimiter itself or empty
// strings which would be interpreted incorrectly
auto delim_count = std::count(results[0].begin(), results[0].end(), delim);
if(results[0].back() == delim ||
static_cast<decltype(delim_count)>(opt->count()) <= delim_count ||
results[0].find(std::string(2, delim)) != std::string::npos) {
results = opt->results();
}
}
}
std::string value;
if(opt->count() == 1 && results.size() == 2 && results.front() == "{}" && results.back() == "%%") {
// there is a catch to allow for {} to used as as string in the output
// it will append a sequence terminator to the output so the lexical conversion handles it
// correctly but that is meant for config files so when outputting for a config file we need to
// makes sure to get the correct output
value = "\"{}\"";
} else {
value = detail::ini_join(results, arraySeparator, arrayStart, arrayEnd, stringQuote, literalQuote);
}
bool isDefault = false;
if(value.empty() && include_default_values) {
if(!opt->get_default_str().empty()) {
results_t res;
opt->results(res);
value = detail::ini_join(res, arraySeparator, arrayStart, arrayEnd, stringQuote, literalQuote);
} else if(opt->get_expected_min() == 0) {
value = "false";
} else if(opt->get_run_callback_for_default() || !opt->get_required()) {
value = "\"\""; // empty string default value
} else {
value = "\"<REQUIRED>\"";
}
isDefault = true;
}
if(!value.empty()) {
if(!opt->get_fnames().empty()) {
try {
value = opt->get_flag_value(single_name, value);
} catch(const CLI::ArgumentMismatch &) {
bool valid{false};
for(const auto &test_name : opt->get_fnames()) {
try {
value = opt->get_flag_value(test_name, value);
single_name = test_name;
valid = true;
} catch(const CLI::ArgumentMismatch &) {
continue;
}
}
if(!valid) {
value = detail::ini_join(
opt->results(), arraySeparator, arrayStart, arrayEnd, stringQuote, literalQuote);
}
}
}
if(write_description && opt->has_description()) {
if(out.tellp() != std::streampos(0)) {
out << '\n';
}
out << commentLead << detail::fix_newlines(commentLead, opt->get_description()) << '\n';
}
detail::clean_name_string(single_name, keyChars);
std::string name = prefix + single_name;
if(commentDefaultsBool && isDefault) {
name = commentChar + name;
}
out << name << valueDelimiter << value << '\n';
}
}
}
}
auto subcommands = app->get_subcommands({});
for(const App *subcom : subcommands) {
if(subcom->get_name().empty()) {
if(!include_default_values && (subcom->count_all() == 0)) {
continue;
}
if(write_description && !subcom->get_group().empty()) {
out << '\n' << commentChar << commentLead << subcom->get_group() << " Options\n";
}
/*if (!prefix.empty() || app->get_parent() == nullptr) {
out << '[' << prefix << "___"<< subcom->get_group() << "]\n";
} else {
std::string subname = app->get_name() + parentSeparatorChar + "___"+subcom->get_group();
const 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, mode, write_description, prefix);
}
}
for(const App *subcom : subcommands) {
if(!subcom->get_name().empty()) {
if((!include_default_values && (subcom->count_all() == 0)) ||
(mode == ConfigOutputMode::ActiveSubcommandDefaults && !app->got_subcommand(subcom))) {
continue;
}
std::string subname = subcom->get_name();
detail::clean_name_string(subname, keyChars);
if(subcom->get_configurable() && (app->got_subcommand(subcom) || (mode == ConfigOutputMode::AllDefaults))) {
if(!prefix.empty() || app->get_parent() == nullptr) {
out << '[' << prefix << subname << "]\n";
} else {
std::string appname = app->get_name();
detail::clean_name_string(appname, keyChars);
subname = appname + parentSeparatorChar + subname;
const auto *p = app->get_parent();
while(p->get_parent() != nullptr) {
std::string pname = p->get_name();
detail::clean_name_string(pname, keyChars);
subname = pname + parentSeparatorChar + subname;
p = p->get_parent();
}
out << '[' << subname << "]\n";
}
out << to_config(subcom, mode, write_description, "");
} else {
out << to_config(subcom, mode, write_description, prefix + subname + parentSeparatorChar);
}
}
}
if(write_description && !out.str().empty()) {
std::string outString =
commentChar + commentLead + detail::fix_newlines(commentChar + commentLead, app->get_description()) + '\n';
return outString + out.str();
}
return out.str();
}
CLI11_INLINE ConfigINI::ConfigINI() {
commentChar = ';';
arrayStart = '\0';
arrayEnd = '\0';
arraySeparator = ' ';
valueDelimiter = '=';
}
// [CLI11:config_inl_hpp:end]
} // namespace CLI
+174
View File
@@ -0,0 +1,174 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// This include is only needed for IDEs to discover symbols
#include "../Encoding.hpp"
#include "../Macros.hpp"
// [CLI11:public_includes:set]
#include <array>
#include <clocale>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <locale>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
// [CLI11:public_includes:end]
// [CLI11:encoding_inl_includes:verbatim]
#if CLI11_HAS_CODECVT
#include <codecvt>
#endif
// [CLI11:encoding_inl_includes:end]
namespace CLI {
// [CLI11:encoding_inl_hpp:verbatim]
namespace detail {
#if !CLI11_HAS_CODECVT
/// Attempt to set one of the acceptable unicode locales for conversion
CLI11_INLINE void set_unicode_locale() {
static const std::array<const char *, 2> unicode_locales{{"C.UTF-8", ".UTF-8"}};
for(const auto &locale_name : unicode_locales) {
if(std::setlocale(LC_ALL, locale_name) != nullptr) {
return;
}
}
throw std::runtime_error("CLI::narrow: could not set locale to C.UTF-8");
}
template <typename F> struct scope_guard_t {
F closure;
explicit scope_guard_t(F closure_) : closure(closure_) {}
~scope_guard_t() { closure(); }
};
template <typename F> CLI11_NODISCARD CLI11_INLINE scope_guard_t<F> scope_guard(F &&closure) {
return scope_guard_t<F>{std::forward<F>(closure)};
}
#endif // !CLI11_HAS_CODECVT
CLI11_DIAGNOSTIC_PUSH
CLI11_DIAGNOSTIC_IGNORE_DEPRECATED
CLI11_INLINE std::string narrow_impl(const wchar_t *str, std::size_t str_size) {
#if CLI11_HAS_CODECVT
#ifdef _WIN32
return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().to_bytes(str, str + str_size);
#else
return std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(str, str + str_size);
#endif // _WIN32
#else // CLI11_HAS_CODECVT
// Copy into a local, NUL-terminated buffer so the conversion is bounded by str_size: a view into the
// middle of a larger buffer or a non-NUL-terminated buffer must not be read past str_size. Note that an
// embedded NUL inside the first str_size characters will still terminate std::wcsrtombs early; this matches
// the behavior of C-style narrow conversion and is treated as a best-effort limitation.
std::wstring input(str, str_size);
const wchar_t *src = input.c_str();
const wchar_t *it = src;
std::mbstate_t state = std::mbstate_t();
std::string old_locale = std::setlocale(LC_ALL, nullptr);
auto sg = scope_guard([&] { std::setlocale(LC_ALL, old_locale.c_str()); });
set_unicode_locale();
std::size_t new_size = std::wcsrtombs(nullptr, &it, 0, &state);
if(new_size == static_cast<std::size_t>(-1)) {
throw std::runtime_error("CLI::narrow: conversion error in std::wcsrtombs at offset " +
std::to_string(it - src));
}
std::string result(new_size, '\0');
std::wcsrtombs(const_cast<char *>(result.data()), &src, new_size, &state);
return result;
#endif // CLI11_HAS_CODECVT
}
CLI11_INLINE std::wstring widen_impl(const char *str, std::size_t str_size) {
#if CLI11_HAS_CODECVT
#ifdef _WIN32
return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().from_bytes(str, str + str_size);
#else
return std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(str, str + str_size);
#endif // _WIN32
#else // CLI11_HAS_CODECVT
// Copy into a local, NUL-terminated buffer so the conversion is bounded by str_size: a view into the
// middle of a larger buffer or a non-NUL-terminated buffer must not be read past str_size. Note that an
// embedded NUL inside the first str_size characters will still terminate std::mbsrtowcs early; this matches
// the behavior of C-style wide conversion and is treated as a best-effort limitation.
std::string input(str, str_size);
const char *src = input.c_str();
const char *it = src;
std::mbstate_t state = std::mbstate_t();
std::string old_locale = std::setlocale(LC_ALL, nullptr);
auto sg = scope_guard([&] { std::setlocale(LC_ALL, old_locale.c_str()); });
set_unicode_locale();
std::size_t new_size = std::mbsrtowcs(nullptr, &it, 0, &state);
if(new_size == static_cast<std::size_t>(-1)) {
throw std::runtime_error("CLI::widen: conversion error in std::mbsrtowcs at offset " +
std::to_string(it - src));
}
std::wstring result(new_size, L'\0');
std::mbsrtowcs(const_cast<wchar_t *>(result.data()), &src, new_size, &state);
return result;
#endif // CLI11_HAS_CODECVT
}
CLI11_DIAGNOSTIC_POP
} // namespace detail
CLI11_INLINE std::string narrow(const wchar_t *str, std::size_t str_size) { return detail::narrow_impl(str, str_size); }
CLI11_INLINE std::string narrow(const std::wstring &str) { return detail::narrow_impl(str.data(), str.size()); }
// Flawfinder: ignore
CLI11_INLINE std::string narrow(const wchar_t *str) { return detail::narrow_impl(str, std::wcslen(str)); }
CLI11_INLINE std::wstring widen(const char *str, std::size_t str_size) { return detail::widen_impl(str, str_size); }
CLI11_INLINE std::wstring widen(const std::string &str) { return detail::widen_impl(str.data(), str.size()); }
// Flawfinder: ignore
CLI11_INLINE std::wstring widen(const char *str) { return detail::widen_impl(str, std::strlen(str)); }
#ifdef CLI11_CPP17
CLI11_INLINE std::string narrow(std::wstring_view str) { return detail::narrow_impl(str.data(), str.size()); }
CLI11_INLINE std::wstring widen(std::string_view str) { return detail::widen_impl(str.data(), str.size()); }
#endif // CLI11_CPP17
#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
CLI11_INLINE std::filesystem::path to_path(std::string_view str) {
return std::filesystem::path{
#ifdef _WIN32
widen(str)
#else
str
#endif // _WIN32
};
}
#endif // CLI11_HAS_FILESYSTEM
// [CLI11:encoding_inl_hpp:end]
} // namespace CLI
@@ -0,0 +1,187 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
#include "../ExtraValidators.hpp"
#if (defined(CLI11_ENABLE_EXTRA_VALIDATORS) && CLI11_ENABLE_EXTRA_VALIDATORS != 0) || \
(!defined(CLI11_DISABLE_EXTRA_VALIDATORS) || CLI11_DISABLE_EXTRA_VALIDATORS == 0)
#include "../Encoding.hpp"
#include "../Macros.hpp"
#include "../StringTools.hpp"
#include "../TypeTools.hpp"
// [CLI11:public_includes:set]
#include <algorithm>
#include <cstdint>
#include <functional>
#include <initializer_list>
#include <map>
#include <string>
#include <system_error>
#include <vector>
// [CLI11:public_includes:end]
namespace CLI {
// [CLI11:extra_validators_inl_hpp:verbatim]
namespace detail {
CLI11_INLINE IPV4Validator::IPV4Validator() : Validator("IPV4") {
func_ = [](std::string &ip_addr) {
auto cdot = std::count(ip_addr.begin(), ip_addr.end(), '.');
if(cdot != 3u) {
return std::string("Invalid IPV4 address: must have 3 separators");
}
auto result = CLI::detail::split(ip_addr, '.');
int num = 0;
for(const auto &var : result) {
using CLI::detail::lexical_cast;
bool retval = lexical_cast(var, num);
if(!retval) {
return std::string("Failed parsing number (") + var + ')';
}
if(num < 0 || num > 255) {
return std::string("Each IP number must be between 0 and 255 ") + var;
}
}
return std::string{};
};
}
} // namespace detail
CLI11_INLINE AsSizeValue::AsSizeValue(bool kb_is_1000) : AsNumberWithUnit(get_mapping(kb_is_1000)) {
if(kb_is_1000) {
description("SIZE [b, kb(=1000b), kib(=1024b), ...]");
} else {
description("SIZE [b, kb(=1024b), ...]");
}
}
CLI11_INLINE std::map<std::string, AsSizeValue::result_t> AsSizeValue::init_mapping(bool kb_is_1000) {
std::map<std::string, result_t> m;
result_t k_factor = kb_is_1000 ? 1000 : 1024;
result_t ki_factor = 1024;
result_t k = 1;
result_t ki = 1;
m["b"] = 1;
for(std::string p : {"k", "m", "g", "t", "p", "e"}) {
k *= k_factor;
ki *= ki_factor;
m[p] = k;
m[p + "b"] = k;
m[p + "i"] = ki;
m[p + "ib"] = ki;
}
return m;
}
CLI11_INLINE const std::map<std::string, AsSizeValue::result_t> &AsSizeValue::get_mapping(bool kb_is_1000) {
if(kb_is_1000) {
static auto m = init_mapping(true);
return m;
}
static auto m = init_mapping(false);
return m;
}
#if defined(CLI11_ENABLE_EXTRA_VALIDATORS) && CLI11_ENABLE_EXTRA_VALIDATORS != 0
// new extra validators
#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
namespace detail {
CLI11_INLINE PermissionValidator::PermissionValidator(Permission permission) {
std::filesystem::perms permission_code = std::filesystem::perms::none;
std::string permission_name;
switch(permission) {
case Permission::read:
permission_code = std::filesystem::perms::owner_read | std::filesystem::perms::group_read |
std::filesystem::perms::others_read;
permission_name = "read";
break;
case Permission::write:
permission_code = std::filesystem::perms::owner_write | std::filesystem::perms::group_write |
std::filesystem::perms::others_write;
permission_name = "write";
break;
case Permission::exec:
permission_code = std::filesystem::perms::owner_exec | std::filesystem::perms::group_exec |
std::filesystem::perms::others_exec;
permission_name = "exec";
break;
case Permission::none:
default:
permission_code = std::filesystem::perms::none;
break;
}
func_ = [permission_code](std::string &path) {
std::error_code ec;
auto p = std::filesystem::path(path);
if(!std::filesystem::exists(p, ec)) {
return std::string("Path does not exist: ") + path;
}
if(ec) {
return std::string("Error checking path: ") + ec.message(); // LCOV_EXCL_LINE
}
if(permission_code == std::filesystem::perms::none) {
return std::string{};
}
auto perms = std::filesystem::status(p, ec).permissions();
if(ec) {
return std::string("Error checking path status: ") + ec.message(); // LCOV_EXCL_LINE
}
if((perms & permission_code) == std::filesystem::perms::none) {
return std::string("Path does not have required permissions: ") + path;
}
return std::string{};
};
description("Path with " + permission_name + " permission");
}
} // namespace detail
CLI11_INLINE FileSizeValidator::FileSizeValidator(std::uint64_t min_size, std::uint64_t max_size) {
std::string desc;
if(max_size == 0) {
desc = "File size at least " + std::to_string(min_size) + " bytes";
} else {
desc = "File size between " + std::to_string(min_size) + " and " + std::to_string(max_size) + " bytes";
}
description(desc);
func_ = [min_size, max_size](std::string &path) {
std::error_code ec;
auto p = std::filesystem::path(path);
if(!std::filesystem::exists(p, ec)) {
return std::string("File does not exist: ") + path;
}
if(ec) {
return std::string("Error checking file: ") + ec.message(); // LCOV_EXCL_LINE
}
auto size = std::filesystem::file_size(p, ec);
if(ec) {
return std::string("Error getting file size: ") + ec.message(); // LCOV_EXCL_LINE
}
if(size < min_size) {
return std::string("File size ") + std::to_string(size) + " bytes is less than minimum " +
std::to_string(min_size) + " bytes";
}
if(max_size > 0 && size > max_size) {
return std::string("File size ") + std::to_string(size) + " bytes exceeds maximum " +
std::to_string(max_size) + " bytes";
}
return std::string{};
};
}
#endif
#endif
// [CLI11:extra_validators_inl_hpp:end]
} // namespace CLI
#endif
@@ -0,0 +1,493 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// This include is only needed for IDEs to discover symbols
#include "../Formatter.hpp"
// [CLI11:public_includes:set]
#include <algorithm>
#include <functional>
#include <iomanip>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
// [CLI11:public_includes:end]
namespace CLI {
// [CLI11:formatter_inl_hpp:verbatim]
namespace detail {
CLI11_INLINE std::string indent_block(const std::string &input, const std::string &indent) {
std::stringstream out;
bool line_start = true;
for(char ch : input) {
if(line_start && ch != '\n') {
out << indent;
}
out << ch;
line_start = (ch == '\n');
}
return out.str();
}
} // namespace detail
CLI11_INLINE void FormatterBase::long_option_alignment_ratio(float ratio) {
long_option_alignment_ratio_ =
(ratio >= 0.0f) ? ((ratio <= 1.0f) ? ratio : 1.0f / ratio) : ((ratio < -1.0f) ? 1.0f / (-ratio) : -ratio);
}
CLI11_NODISCARD CLI11_INLINE std::string FormatterBase::get_label(std::string key) const {
auto it = labels_.find(key);
return it != labels_.end() ? it->second : default_label(key);
}
CLI11_INLINE FormatterLambda::FormatterLambda(funct_t funct) : lambda_(std::move(funct)) {}
CLI11_INLINE std::string FormatterLambda::make_help(const App *app, std::string name, AppFormatMode mode) const {
return lambda_(app, name, mode);
}
CLI11_INLINE std::string
Formatter::make_group(std::string group, bool is_positional, std::vector<const Option *> opts) const {
std::stringstream out;
out << "\n" << group << ":\n";
for(const Option *opt : opts) {
out << make_option(opt, is_positional);
}
return out.str();
}
CLI11_INLINE std::string Formatter::make_positionals(const App *app) const {
std::vector<const Option *> opts =
app->get_options([](const Option *opt) { return !opt->get_group().empty() && opt->get_positional(); });
if(opts.empty())
return {};
return make_group(get_label("POSITIONALS"), true, opts);
}
CLI11_INLINE std::string Formatter::make_groups(const App *app, AppFormatMode mode) const {
std::stringstream out;
std::vector<std::string> groups = app->get_groups();
// Options
for(const std::string &group : groups) {
std::vector<const Option *> opts = app->get_options([app, mode, &group](const Option *opt) {
return opt->get_group() == group // Must be in the right group
&& opt->nonpositional() // Must not be a positional
&& (mode != AppFormatMode::Sub // If mode is Sub, then
|| (app->get_help_ptr() != opt // Ignore help pointer
&& app->get_help_all_ptr() != opt)); // Ignore help all pointer
});
if(!group.empty() && !opts.empty()) {
out << make_group(group, false, opts);
// Removed double newline between groups for consistency of help text
// if(group != groups.back())
// out << "\n";
}
}
return out.str();
}
CLI11_INLINE std::string Formatter::make_description(const App *app) const {
std::string desc = app->get_description();
auto min_options = app->get_require_option_min();
auto max_options = app->get_require_option_max();
if(app->get_required()) {
desc += " " + get_label("REQUIRED") + " ";
}
if(min_options > 0) {
if(max_options == min_options) {
desc += " \n[Exactly " + std::to_string(min_options) + " of the following options are required]";
} else if(max_options > 0) {
desc += " \n[Between " + std::to_string(min_options) + " and " + std::to_string(max_options) +
" of the following options are required]";
} else {
desc += " \n[At least " + std::to_string(min_options) + " of the following options are required]";
}
} else if(max_options > 0) {
desc += " \n[At most " + std::to_string(max_options) + " of the following options are allowed]";
}
return (!desc.empty()) ? desc + "\n\n" : std::string{};
}
CLI11_INLINE std::string Formatter::make_usage(const App *app, std::string name) const {
std::string usage = app->get_usage();
if(!usage.empty()) {
return usage + "\n\n";
}
std::stringstream out;
out << '\n';
if(name.empty())
out << get_label("Usage") << ':';
else
out << name;
std::vector<std::string> groups = app->get_groups();
// Print an Options badge if any options exist
std::vector<const Option *> non_pos_options =
app->get_options([](const Option *opt) { return opt->nonpositional(); });
if(!non_pos_options.empty())
out << " [" << get_label("OPTIONS") << "]";
// Positionals need to be listed here
std::vector<const Option *> positionals =
app->get_options([](const Option *opt) { return !opt->get_group().empty() && opt->get_positional(); });
// Print out positionals if any are left
if(!positionals.empty()) {
// Convert to help names
std::vector<std::string> positional_names;
positional_names.reserve(positionals.size());
for(const auto *opt : positionals) {
positional_names.push_back(make_option_usage(opt));
}
out << " " << detail::join(positional_names, " ");
}
// Add a marker if subcommands are expected or optional
if(!app->get_subcommands(
[](const CLI::App *subc) { return ((!subc->get_disabled()) && (!subc->get_name().empty())); })
.empty()) {
out << ' ' << (app->get_require_subcommand_min() == 0 ? "[" : "")
<< get_label(app->get_require_subcommand_max() == 1 ? "SUBCOMMAND" : "SUBCOMMANDS")
<< (app->get_require_subcommand_min() == 0 ? "]" : "");
}
out << "\n\n";
return out.str();
}
CLI11_INLINE std::string Formatter::make_footer(const App *app) const {
std::string footer = app->get_footer();
if(footer.empty()) {
return std::string{};
}
return '\n' + footer + '\n';
}
CLI11_INLINE std::string Formatter::make_help(const App *app, std::string name, AppFormatMode mode) const {
// This immediately forwards to the make_expanded method. This is done this way so that subcommands can
// have overridden formatters
if(mode == AppFormatMode::Sub)
return make_expanded(app, mode);
std::stringstream out;
if((app->get_name().empty()) && (app->get_parent() != nullptr)) {
if(app->get_group() != "SUBCOMMANDS") {
out << app->get_group() << ':';
}
}
if(is_description_paragraph_formatting_enabled()) {
detail::streamOutAsParagraph(
out, make_description(app), description_paragraph_width_, ""); // Format description as paragraph
} else {
out << make_description(app);
}
out << make_usage(app, name);
out << make_positionals(app);
out << make_groups(app, mode);
out << make_subcommands(app, mode);
std::string footer_string = make_footer(app);
if(is_footer_paragraph_formatting_enabled()) {
detail::streamOutAsParagraph(out, footer_string, footer_paragraph_width_); // Format footer as paragraph
} else {
out << footer_string;
}
return out.str();
}
CLI11_INLINE std::string Formatter::make_subcommands(const App *app, AppFormatMode mode) const {
std::stringstream out;
std::vector<const App *> subcommands = app->get_subcommands({});
// Make a list in definition order of the groups seen
std::vector<std::string> subcmd_groups_seen;
for(const App *com : subcommands) {
if(com->get_name().empty()) {
if(!com->get_group().empty() && com->get_group().front() != '+') {
auto expanded = make_expanded(com, mode);
// add expansion in one place so each group has subgroups beneath it
out << expanded;
}
continue;
}
std::string group_key = com->get_group();
std::string group_key_lower = detail::to_lower(group_key);
if(!group_key.empty() &&
std::find_if(subcmd_groups_seen.begin(), subcmd_groups_seen.end(), [&group_key_lower](const std::string &a) {
return detail::to_lower(a) == group_key_lower;
}) == subcmd_groups_seen.end())
subcmd_groups_seen.push_back(group_key);
}
// For each group, filter out and print subcommands
for(const std::string &group : subcmd_groups_seen) {
out << '\n' << group << ":\n";
std::vector<const App *> subcommands_group = app->get_subcommands(
[&group](const App *sub_app) { return detail::to_lower(sub_app->get_group()) == detail::to_lower(group); });
for(const App *new_com : subcommands_group) {
if(new_com->get_name().empty())
continue;
if(mode != AppFormatMode::All) {
out << make_subcommand(new_com);
} else {
out << new_com->help(new_com->get_name(), AppFormatMode::Sub);
out << '\n';
}
}
}
return out.str();
}
CLI11_INLINE std::string Formatter::make_subcommand(const App *sub) const {
std::stringstream out;
std::string name = " " + sub->get_display_name(true) + (sub->get_required() ? " " + get_label("REQUIRED") : "");
out << std::setw(static_cast<int>(column_width_)) << std::left << name;
const std::string desc = sub->get_description();
if(!desc.empty()) {
bool skipFirstLinePrefix = true;
if(name.length() >= column_width_) {
out << '\n';
skipFirstLinePrefix = false;
}
detail::streamOutAsParagraph(
out, desc, right_column_width_, std::string(column_width_, ' '), skipFirstLinePrefix);
}
out << '\n';
return out.str();
}
CLI11_INLINE std::string Formatter::make_expanded(const App *sub, AppFormatMode mode) const {
std::stringstream out;
const bool is_option_group = sub->get_name().empty();
const std::string body_indent = is_option_group ? " " : "";
out << sub->get_display_name(true) << '\n';
if(is_description_paragraph_formatting_enabled()) {
detail::streamOutAsParagraph(
out, make_description(sub), description_paragraph_width_, body_indent); // Format description as paragraph
} else {
out << detail::indent_block(make_description(sub), body_indent) << '\n';
}
if(sub->get_name().empty() && !sub->get_aliases().empty()) {
detail::format_aliases(out, sub->get_aliases(), column_width_ + 2);
}
out << detail::indent_block(make_positionals(sub), body_indent);
out << detail::indent_block(make_groups(sub, mode), body_indent);
out << detail::indent_block(make_subcommands(sub, mode), body_indent);
std::string footer_string = make_footer(sub);
if(mode == AppFormatMode::Sub && !footer_string.empty()) {
const auto *parent = sub->get_parent();
std::string parent_footer = (parent != nullptr) ? make_footer(sub->get_parent()) : std::string{};
if(footer_string == parent_footer) {
footer_string = "";
}
}
if(!footer_string.empty()) {
if(is_footer_paragraph_formatting_enabled()) {
detail::streamOutAsParagraph(out, footer_string, footer_paragraph_width_); // Format footer as paragraph
} else {
out << footer_string;
}
}
return out.str();
}
CLI11_INLINE std::string Formatter::make_option(const Option *opt, bool is_positional) const {
std::stringstream out;
if(is_positional) {
const std::string left = " " + make_option_name(opt, true) + make_option_opts(opt);
const std::string desc = make_option_desc(opt);
out << std::setw(static_cast<int>(column_width_)) << std::left << left;
if(!desc.empty()) {
bool skipFirstLinePrefix = true;
if(left.length() >= column_width_) {
out << '\n';
skipFirstLinePrefix = false;
}
detail::streamOutAsParagraph(
out, desc, right_column_width_, std::string(column_width_, ' '), skipFirstLinePrefix);
}
} else {
const std::string namesCombined = make_option_name(opt, false);
const std::string opts = make_option_opts(opt);
const std::string desc = make_option_desc(opt);
// Split all names at comma and sort them into short names and long names
const auto names = detail::split(namesCombined, ',');
std::vector<std::string> vshortNames;
std::vector<std::string> vlongNames;
std::for_each(names.begin(), names.end(), [&vshortNames, &vlongNames](const std::string &name) {
if(name.find("--", 0) != std::string::npos)
vlongNames.push_back(name);
else
vshortNames.push_back(name);
});
// Assemble short and long names
std::string shortNames = detail::join(vshortNames, ", ");
std::string longNames = detail::join(vlongNames, ", ");
// Calculate setw sizes
// Short names take enough width to align long names at the desired ratio
const auto shortNamesColumnWidth =
static_cast<int>(static_cast<float>(column_width_) * long_option_alignment_ratio_);
const auto longNamesColumnWidth = static_cast<int>(column_width_) - shortNamesColumnWidth;
int shortNamesOverSize = 0;
// Print short names
if(!shortNames.empty()) {
shortNames = " " + shortNames; // Indent
if(longNames.empty() && !opts.empty())
shortNames += opts; // Add opts if only short names and no long names
if(!longNames.empty())
shortNames += ",";
if(static_cast<int>(shortNames.length()) >= shortNamesColumnWidth) {
shortNames += " ";
shortNamesOverSize = static_cast<int>(shortNames.length()) - shortNamesColumnWidth;
}
out << std::setw(shortNamesColumnWidth) << std::left << shortNames;
} else {
out << std::setw(shortNamesColumnWidth) << std::left << "";
}
// Adjust long name column width in case of short names column reaching into long names column
shortNamesOverSize =
(std::min)(shortNamesOverSize, longNamesColumnWidth); // Prevent negative result with unsigned integers
const auto adjustedLongNamesColumnWidth = longNamesColumnWidth - shortNamesOverSize;
// Print long names
if(!longNames.empty()) {
if(!opts.empty())
longNames += opts;
if(static_cast<int>(longNames.length()) >= adjustedLongNamesColumnWidth)
longNames += " ";
out << std::setw(adjustedLongNamesColumnWidth) << std::left << longNames;
} else {
out << std::setw(adjustedLongNamesColumnWidth) << std::left << "";
}
if(!desc.empty()) {
bool skipFirstLinePrefix = true;
if(out.str().length() > column_width_) {
out << '\n';
skipFirstLinePrefix = false;
}
detail::streamOutAsParagraph(
out, desc, right_column_width_, std::string(column_width_, ' '), skipFirstLinePrefix);
}
}
out << '\n';
return out.str();
}
CLI11_INLINE std::string Formatter::make_option_name(const Option *opt, bool is_positional) const {
if(is_positional)
return opt->get_name(true, false);
return opt->get_name(false, true, !enable_default_flag_values_);
}
CLI11_INLINE std::string Formatter::make_option_opts(const Option *opt) const {
std::stringstream out;
// Help output should be stable across runs, so sort pointer-based sets by option name before printing.
const auto print_option_set = [&out](const std::set<Option *> &options) {
std::vector<const Option *> sorted(options.begin(), options.end());
std::sort(sorted.begin(), sorted.end(), [](const Option *lhs, const Option *rhs) {
return lhs->get_name() < rhs->get_name();
});
for(const Option *op : sorted)
out << " " << op->get_name();
};
if(!opt->get_option_text().empty()) {
out << " " << opt->get_option_text();
} else {
if(opt->get_type_size() != 0) {
if(enable_option_type_names_) {
if(!opt->get_type_name().empty()) {
out << " " << get_label(opt->get_type_name());
// Show the delimiter on the type, a trailing "..." only means space separated values
if(opt->get_delimiter() != '\0')
out << opt->get_delimiter() << "...";
}
}
if(enable_option_defaults_) {
if(!opt->get_default_str().empty())
out << " [" << opt->get_default_str() << "] ";
}
if(opt->get_expected_max() == detail::expected_max_vector_size)
out << " ...";
else if(opt->get_expected_min() > 1)
out << " x " << opt->get_expected();
if(opt->get_required())
out << " " << get_label("REQUIRED");
}
if(!opt->get_envname().empty())
out << " (" << get_label("Env") << ":" << opt->get_envname() << ")";
if(!opt->get_needs().empty()) {
out << " " << get_label("Needs") << ":";
print_option_set(opt->get_needs());
}
if(!opt->get_excludes().empty()) {
out << " " << get_label("Excludes") << ":";
print_option_set(opt->get_excludes());
}
}
return out.str();
}
CLI11_INLINE std::string Formatter::make_option_desc(const Option *opt) const { return opt->get_description(); }
CLI11_INLINE std::string Formatter::make_option_usage(const Option *opt) const {
// Note that these are positionals usages
std::stringstream out;
out << make_option_name(opt, true);
if(opt->get_expected_max() >= detail::expected_max_vector_size)
out << "...";
else if(opt->get_expected_max() > 1)
out << "(" << opt->get_expected() << "x)";
return opt->get_required() ? out.str() : "[" + out.str() + "]";
}
// [CLI11:formatter_inl_hpp:end]
} // namespace CLI
+811
View File
@@ -0,0 +1,811 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// This include is only needed for IDEs to discover symbols
#include "../Option.hpp"
// [CLI11:public_includes:set]
#include <algorithm>
#include <cerrno>
#include <cstdlib>
#include <functional>
#include <iterator>
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
// [CLI11:public_includes:end]
namespace CLI {
// [CLI11:option_inl_hpp:verbatim]
template <typename CRTP> template <typename T> void OptionBase<CRTP>::copy_to(T *other) const {
other->group(group_);
other->required(required_);
other->ignore_case(ignore_case_);
other->ignore_underscore(ignore_underscore_);
other->configurable(configurable_);
other->disable_flag_override(disable_flag_override_);
other->delimiter(delimiter_);
other->always_capture_default(always_capture_default_);
other->multi_option_policy(multi_option_policy_);
other->callback_priority(callback_priority_);
}
CLI11_INLINE Option::Option(
std::string option_name, std::string option_description, callback_t callback, App *parent, bool allow_non_standard)
: description_(std::move(option_description)), parent_(parent), callback_(std::move(callback)) {
std::tie(snames_, lnames_, pname_) = detail::get_names(detail::split_names(option_name), allow_non_standard);
}
CLI11_INLINE void Option::clear() {
results_.clear();
proc_results_.clear();
current_option_state_ = option_state::parsing;
}
CLI11_INLINE Option *Option::expected(int value) {
if(value < 0) {
expected_min_ = -value;
if(expected_max_ < expected_min_) {
expected_max_ = expected_min_;
}
allow_extra_args_ = true;
flag_like_ = false;
} else if(value == detail::expected_max_vector_size) {
expected_min_ = 1;
expected_max_ = detail::expected_max_vector_size;
allow_extra_args_ = true;
flag_like_ = false;
} else {
expected_min_ = value;
expected_max_ = value;
flag_like_ = (expected_min_ == 0);
}
return this;
}
CLI11_INLINE Option *Option::expected(int value_min, int value_max) {
if(value_min < 0) {
value_min = -value_min;
}
if(value_max < 0) {
value_max = detail::expected_max_vector_size;
}
if(value_max < value_min) {
expected_min_ = value_max;
expected_max_ = value_min;
} else {
expected_max_ = value_max;
expected_min_ = value_min;
}
return this;
}
CLI11_INLINE Option *Option::check(Validator_p validator) {
validator->non_modifying();
validators_.push_back(std::move(validator));
return this;
}
CLI11_INLINE Option *Option::check(Validator validator, const std::string &validator_name) {
validator.non_modifying();
auto vp = std::make_shared<Validator>(std::move(validator));
if(!validator_name.empty()) {
vp->name(validator_name);
}
validators_.push_back(std::move(vp));
return this;
}
CLI11_INLINE Option *Option::check(std::function<std::string(const std::string &)> validator_func,
std::string validator_description,
std::string validator_name) {
auto vp = std::make_shared<Validator>(
std::move(validator_func), std::move(validator_description), std::move(validator_name));
vp->non_modifying();
validators_.push_back(std::move(vp));
return this;
}
CLI11_INLINE Option *Option::transform(Validator_p validator) {
validators_.insert(validators_.begin(), std::move(validator));
return this;
}
CLI11_INLINE Option *Option::transform(Validator validator, const std::string &transform_name) {
auto vp = std::make_shared<Validator>(std::move(validator));
if(!transform_name.empty()) {
vp->name(transform_name);
}
validators_.insert(validators_.begin(), std::move(vp));
return this;
}
CLI11_INLINE Option *
Option::transform(Validator validator, const std::string &transform_description, const std::string &transform_name) {
auto vp = std::make_shared<Validator>(std::move(validator));
if(!transform_name.empty()) {
vp->name(transform_name);
}
vp->description(transform_description);
validators_.insert(validators_.begin(), std::move(vp));
return this;
}
CLI11_INLINE Option *Option::transform(const std::function<std::string(std::string)> &transform_func,
std::string transform_description,
std::string transform_name) {
auto vp = std::make_shared<Validator>(
[transform_func](std::string &val) {
val = transform_func(val);
return std::string{};
},
std::move(transform_description),
std::move(transform_name));
validators_.insert(validators_.begin(), std::move(vp));
return this;
}
CLI11_INLINE Option *Option::each(const std::function<void(std::string)> &func) {
auto vp = std::make_shared<Validator>(
[func](std::string &inout) {
func(inout);
return std::string{};
},
std::string{});
validators_.push_back(std::move(vp));
return this;
}
CLI11_INLINE Validator *Option::get_validator(const std::string &validator_name) {
for(auto &validator : validators_) {
if(validator_name == validator->get_name()) {
return validator.get();
}
}
if((validator_name.empty()) && (!validators_.empty())) {
return validators_.front().get();
}
throw OptionNotFound(std::string{"Validator "} + validator_name + " Not Found");
}
CLI11_INLINE Validator *Option::get_validator(int index) {
// This is a signed int so that it is not equivalent to a pointer.
if(index >= 0 && index < static_cast<int>(validators_.size())) {
return validators_[static_cast<decltype(validators_)::size_type>(index)].get();
}
throw OptionNotFound("Validator index is not valid");
}
CLI11_INLINE Option *Option::needs(Option *opt) {
if(opt != this) {
needs_.insert(opt);
}
return this;
}
CLI11_INLINE bool Option::remove_needs(Option *opt) {
auto iterator = std::find(std::begin(needs_), std::end(needs_), opt);
if(iterator == std::end(needs_)) {
return false;
}
needs_.erase(iterator);
return true;
}
CLI11_INLINE Option *Option::excludes(Option *opt) {
if(opt == this) {
throw(IncorrectConstruction("and option cannot exclude itself"));
}
excludes_.insert(opt);
// Help text should be symmetric - excluding a should exclude b
opt->excludes_.insert(this);
// Ignoring the insert return value, excluding twice is now allowed.
// (Mostly to allow both directions to be excluded by user, even though the library does it for you.)
return this;
}
CLI11_INLINE bool Option::remove_excludes(Option *opt) {
auto iterator = std::find(std::begin(excludes_), std::end(excludes_), opt);
if(iterator == std::end(excludes_)) {
return false;
}
excludes_.erase(iterator);
return true;
}
template <typename T> Option *Option::ignore_case(bool value) {
if(!ignore_case_ && value) {
ignore_case_ = value;
auto *parent = static_cast<T *>(parent_);
for(const Option_p &opt : parent->options_) {
if(opt.get() == this) {
continue;
}
const auto &omatch = opt->matching_name(*this);
if(!omatch.empty()) {
ignore_case_ = false;
throw OptionAlreadyAdded("adding ignore case caused a name conflict with " + omatch);
}
}
} else {
ignore_case_ = value;
}
return this;
}
template <typename T> Option *Option::ignore_underscore(bool value) {
if(!ignore_underscore_ && value) {
ignore_underscore_ = value;
auto *parent = static_cast<T *>(parent_);
for(const Option_p &opt : parent->options_) {
if(opt.get() == this) {
continue;
}
const auto &omatch = opt->matching_name(*this);
if(!omatch.empty()) {
ignore_underscore_ = false;
throw OptionAlreadyAdded("adding ignore underscore caused a name conflict with " + omatch);
}
}
} else {
ignore_underscore_ = value;
}
return this;
}
CLI11_INLINE Option *Option::multi_option_policy(MultiOptionPolicy value) {
if(value != multi_option_policy_) {
if(multi_option_policy_ == MultiOptionPolicy::Throw && expected_max_ == detail::expected_max_vector_size &&
expected_min_ > 1) { // this bizarre condition is to maintain backwards compatibility
// with the previous behavior of expected_ with vectors
expected_max_ = expected_min_;
}
multi_option_policy_ = value;
current_option_state_ = option_state::parsing;
}
return this;
}
CLI11_NODISCARD CLI11_INLINE std::string
Option::get_name(bool positional, bool all_options, bool disable_default_flag_values) const {
if(get_group().empty())
return {}; // Hidden
if(all_options) {
std::vector<std::string> name_list;
/// The all list will never include a positional unless asked or that's the only name.
if((positional && (!pname_.empty())) || (snames_.empty() && lnames_.empty())) {
name_list.push_back(pname_);
}
if((get_items_expected() == 0) && (!fnames_.empty())) {
for(const std::string &sname : snames_) {
name_list.push_back("-" + sname);
if(!disable_default_flag_values && check_fname(sname)) {
name_list.back() += "{" + get_flag_value(sname, "") + "}";
}
}
for(const std::string &lname : lnames_) {
name_list.push_back("--" + lname);
if(!disable_default_flag_values && check_fname(lname)) {
name_list.back() += "{" + get_flag_value(lname, "") + "}";
}
}
} else {
for(const std::string &sname : snames_)
name_list.push_back("-" + sname);
for(const std::string &lname : lnames_)
name_list.push_back("--" + lname);
}
return detail::join(name_list);
}
// This returns the positional name no matter what
if(positional)
return pname_;
// Prefer long name
if(!lnames_.empty())
return std::string(2, '-') + lnames_[0];
// Or short name if no long name
if(!snames_.empty())
return std::string(1, '-') + snames_[0];
// If positional is the only name, it's okay to use that
return pname_;
}
CLI11_INLINE void Option::run_callback() {
bool used_default_str = false;
if(force_callback_ && results_.empty()) {
used_default_str = true;
add_result(default_str_);
}
if(current_option_state_ == option_state::parsing) {
_validate_results(results_);
current_option_state_ = option_state::validated;
}
if(current_option_state_ < option_state::reduced) {
_reduce_results(proc_results_, results_);
}
current_option_state_ = option_state::callback_run;
if(callback_) {
const results_t &send_results = proc_results_.empty() ? results_ : proc_results_;
if(send_results.empty()) {
return;
}
bool local_result = callback_(send_results);
if(used_default_str) {
// we only clear the results if the callback was actually used
// otherwise the callback is the storage of the default
results_.clear();
proc_results_.clear();
}
if(!local_result)
throw ConversionError(get_name(), results_);
}
}
CLI11_NODISCARD CLI11_INLINE const std::string &Option::matching_name(const Option &other) const {
static const std::string estring;
bool bothConfigurable = configurable_ && other.configurable_;
for(const std::string &sname : snames_) {
if(other.check_sname(sname))
return sname;
if(bothConfigurable && other.check_lname(sname))
return sname;
}
for(const std::string &lname : lnames_) {
if(other.check_lname(lname))
return lname;
if(lname.size() == 1 && bothConfigurable) {
if(other.check_sname(lname)) {
return lname;
}
}
}
if(bothConfigurable && snames_.empty() && lnames_.empty() && !pname_.empty()) {
if(other.check_sname(pname_) || other.check_lname(pname_) || pname_ == other.pname_)
return pname_;
}
if(bothConfigurable && other.snames_.empty() && other.fnames_.empty() && !other.pname_.empty()) {
if(check_sname(other.pname_) || check_lname(other.pname_) || (pname_ == other.pname_))
return other.pname_;
}
if(ignore_case_ ||
ignore_underscore_) { // We need to do the inverse, in case we are ignore_case or ignore underscore
for(const std::string &sname : other.snames_)
if(check_sname(sname))
return sname;
for(const std::string &lname : other.lnames_)
if(check_lname(lname))
return lname;
}
return estring;
}
CLI11_NODISCARD CLI11_INLINE bool Option::check_name(const std::string &name) const {
if(name.length() > 2 && name[0] == '-' && name[1] == '-')
return check_lname(name.substr(2));
if(name.length() > 1 && name.front() == '-')
return check_sname(name.substr(1));
if(!pname_.empty()) {
std::string local_pname = pname_;
std::string local_name = name;
if(ignore_underscore_) {
local_pname = detail::remove_underscore(local_pname);
local_name = detail::remove_underscore(local_name);
}
if(ignore_case_) {
local_pname = detail::to_lower(local_pname);
local_name = detail::to_lower(local_name);
}
if(local_name == local_pname) {
return true;
}
}
if(!envname_.empty()) {
// this needs to be the original since envname_ shouldn't match on case insensitivity
return (name == envname_);
}
return false;
}
CLI11_NODISCARD CLI11_INLINE std::string Option::get_flag_value(const std::string &name,
std::string input_value) const {
static const std::string trueString{"true"};
static const std::string falseString{"false"};
static const std::string emptyString{"{}"};
// check for disable flag override_
if(disable_flag_override_) {
if(!((input_value.empty()) || (input_value == emptyString))) {
auto default_ind = detail::find_member(name, fnames_, ignore_case_, ignore_underscore_);
if(default_ind >= 0) {
// We can static cast this to std::size_t because it is more than 0 in this block
if(default_flag_values_[static_cast<std::size_t>(default_ind)].second != input_value) {
if(input_value == default_str_ && force_callback_) {
return input_value;
}
throw(ArgumentMismatch::FlagOverride(name));
}
} else {
if(input_value != trueString) {
throw(ArgumentMismatch::FlagOverride(name));
}
}
}
}
auto ind = detail::find_member(name, fnames_, ignore_case_, ignore_underscore_);
if((input_value.empty()) || (input_value == emptyString)) {
if(flag_like_) {
return (ind < 0) ? trueString : default_flag_values_[static_cast<std::size_t>(ind)].second;
}
return (ind < 0) ? default_str_ : default_flag_values_[static_cast<std::size_t>(ind)].second;
}
if(ind < 0) {
return input_value;
}
if(default_flag_values_[static_cast<std::size_t>(ind)].second == falseString) {
errno = 0;
auto val = detail::to_flag_value(input_value);
if(errno != 0) {
errno = 0;
return input_value;
}
return (val == 1) ? falseString : (val == (-1) ? trueString : std::to_string(-val));
}
return input_value;
}
CLI11_INLINE Option *Option::add_result(std::string s) {
_add_result(std::move(s), results_);
current_option_state_ = option_state::parsing;
return this;
}
CLI11_INLINE Option *Option::add_result(std::string s, int &results_added) {
results_added = _add_result(std::move(s), results_);
current_option_state_ = option_state::parsing;
return this;
}
CLI11_INLINE Option *Option::add_result(std::vector<std::string> s) {
current_option_state_ = option_state::parsing;
for(auto &str : s) {
_add_result(std::move(str), results_);
}
return this;
}
CLI11_NODISCARD CLI11_INLINE results_t Option::reduced_results() const {
const bool parsing = current_option_state_ == option_state::parsing;
results_t res = (parsing || proc_results_.empty()) ? results_ : proc_results_;
if(current_option_state_ < option_state::reduced) {
if(parsing) {
_validate_results(res);
}
if(!res.empty()) {
results_t extra;
_reduce_results(extra, res);
if(!extra.empty()) {
res = std::move(extra);
}
}
}
return res;
}
CLI11_INLINE Option *Option::type_size(int option_type_size) {
if(option_type_size < 0) {
// this section is included for backwards compatibility
type_size_max_ = -option_type_size;
type_size_min_ = -option_type_size;
expected_max_ = detail::expected_max_vector_size;
} else {
type_size_max_ = option_type_size;
if(type_size_max_ < detail::expected_max_vector_size) {
type_size_min_ = option_type_size;
} else {
inject_separator_ = true;
}
if(type_size_max_ == 0)
required_ = false;
}
return this;
}
CLI11_INLINE Option *Option::type_size(int option_type_size_min, int option_type_size_max) {
if(option_type_size_min < 0 || option_type_size_max < 0) {
// this section is included for backwards compatibility
expected_max_ = detail::expected_max_vector_size;
option_type_size_min = (std::abs)(option_type_size_min);
option_type_size_max = (std::abs)(option_type_size_max);
}
if(option_type_size_min > option_type_size_max) {
type_size_max_ = option_type_size_min;
type_size_min_ = option_type_size_max;
} else {
type_size_min_ = option_type_size_min;
type_size_max_ = option_type_size_max;
}
if(type_size_max_ == 0) {
required_ = false;
}
if(type_size_max_ >= detail::expected_max_vector_size) {
inject_separator_ = true;
}
return this;
}
CLI11_NODISCARD CLI11_INLINE const std::string &Option::get_single_name() const {
if(!lnames_.empty()) {
return lnames_[0];
}
if(!snames_.empty()) {
return snames_[0];
}
if(!pname_.empty()) {
return pname_;
}
return envname_;
}
CLI11_INLINE Option *Option::type_name(std::string typeval) {
type_name_fn([typeval]() { return typeval; });
return this;
}
CLI11_INLINE Option *Option::capture_default_str() {
if(default_function_) {
default_str_ = default_function_();
}
return this;
}
CLI11_NODISCARD CLI11_INLINE std::string Option::get_type_name() const {
std::string full_type_name = type_name_();
if(!validators_.empty()) {
for(const auto &validator : validators_) {
std::string vtype = validator->get_description();
if(!vtype.empty()) {
full_type_name += ":" + vtype;
}
}
}
return full_type_name;
}
CLI11_INLINE void Option::_validate_results(results_t &res) const {
// Run the Validators (can change the string)
if(!validators_.empty()) {
if(type_size_max_ > 1) { // in this context index refers to the index in the type
int index = 0;
if(get_items_expected_max() < static_cast<int>(res.size()) &&
(multi_option_policy_ == CLI::MultiOptionPolicy::TakeLast ||
multi_option_policy_ == CLI::MultiOptionPolicy::Reverse)) {
// create a negative index for the earliest ones
index = get_items_expected_max() - static_cast<int>(res.size());
}
for(std::string &result : res) {
if(detail::is_separator(result) && type_size_max_ != type_size_min_ && index >= 0) {
index = 0; // reset index for variable size chunks
continue;
}
auto err_msg = _validate(result, (index >= 0) ? (index % type_size_max_) : index);
if(!err_msg.empty())
throw ValidationError(get_name(), err_msg);
++index;
}
} else {
int index = 0;
if(expected_max_ < static_cast<int>(res.size()) &&
(multi_option_policy_ == CLI::MultiOptionPolicy::TakeLast ||
multi_option_policy_ == CLI::MultiOptionPolicy::Reverse)) {
// create a negative index for the earliest ones
index = expected_max_ - static_cast<int>(res.size());
}
for(std::string &result : res) {
auto err_msg = _validate(result, index);
++index;
if(!err_msg.empty())
throw ValidationError(get_name(), err_msg);
}
}
}
}
CLI11_INLINE void Option::_reduce_results(results_t &out, const results_t &original) const {
// max num items expected or length of vector, always at least 1
// Only valid for a trimming policy
out.clear();
// Operation depends on the policy setting
switch(multi_option_policy_) {
case MultiOptionPolicy::TakeAll:
break;
case MultiOptionPolicy::TakeLast: {
// Allow multi-option sizes (including 0)
std::size_t trim_size = std::min<std::size_t>(
static_cast<std::size_t>(std::max<int>(get_items_expected_max(), 1)), original.size());
if(original.size() != trim_size) {
out.assign(original.end() - static_cast<results_t::difference_type>(trim_size), original.end());
}
} break;
case MultiOptionPolicy::Reverse: {
// Allow multi-option sizes (including 0)
std::size_t trim_size = std::min<std::size_t>(
static_cast<std::size_t>(std::max<int>(get_items_expected_max(), 1)), original.size());
if(original.size() != trim_size || trim_size > 1) {
out.assign(original.end() - static_cast<results_t::difference_type>(trim_size), original.end());
}
std::reverse(out.begin(), out.end());
} break;
case MultiOptionPolicy::TakeFirst: {
std::size_t trim_size = std::min<std::size_t>(
static_cast<std::size_t>(std::max<int>(get_items_expected_max(), 1)), original.size());
if(original.size() != trim_size) {
out.assign(original.begin(), original.begin() + static_cast<results_t::difference_type>(trim_size));
}
} break;
case MultiOptionPolicy::Join:
if(original.size() > 1) {
out.push_back(detail::join(original, std::string(1, (delimiter_ == '\0') ? '\n' : delimiter_)));
}
break;
case MultiOptionPolicy::Sum:
out.push_back(detail::sum_string_vector(original));
break;
case MultiOptionPolicy::Throw:
default: {
auto num_min = static_cast<std::size_t>(get_items_expected_min());
auto num_max = static_cast<std::size_t>(get_items_expected_max());
if(num_min == 0) {
num_min = 1;
}
if(num_max == 0) {
num_max = 1;
}
if(original.size() < num_min) {
throw ArgumentMismatch::AtLeast(get_name(), static_cast<int>(num_min), original.size());
}
if(original.size() > num_max) {
if(original.size() == 2 && num_max == 1 && original[1] == "%%" && original[0] == "{}") {
// this condition is a trap for the following empty indicator check on config files, it may not be used
// anymore
out = original; // LCOV_EXCL_LINE
} else {
throw ArgumentMismatch::AtMost(get_name(), static_cast<int>(num_max), original.size());
}
}
break;
}
}
// this check is to allow an empty vector in certain circumstances but not if expected is not zero.
// {} is the indicator for an empty container
if(out.empty()) {
if(original.size() == 1 && original[0] == "{}" && get_items_expected_min() > 0) {
out.emplace_back("{}");
out.emplace_back("%%");
}
} else if(out.size() == 1 && out[0] == "{}" && get_items_expected_min() > 0) {
out.emplace_back("%%");
}
}
CLI11_INLINE std::string Option::_validate(std::string &result, int index) const {
std::string err_msg;
if(result.empty() && expected_min_ == 0) {
// an empty with nothing expected is allowed
return err_msg;
}
for(const auto &vali : validators_) {
auto v = vali->get_application_index();
if(v == -1 || v == index) {
try {
err_msg = (*vali)(result);
} catch(const ValidationError &err) {
err_msg = err.what();
}
if(!err_msg.empty())
break;
}
}
return err_msg;
}
CLI11_INLINE int Option::_add_result(std::string &&result, std::vector<std::string> &res) const {
int result_count = 0;
// Handle the vector escape possibility all characters duplicated and starting with [[ ending with ]]
// this is always a single result
if(result.size() >= 4 && result[0] == '[' && result[1] == '[' && result.back() == ']' &&
(*(result.end() - 2) == ']')) {
// this is an escape clause for odd strings
std::string nstrs{'['};
bool duplicated{true};
for(std::size_t ii = 2; ii < result.size() - 2; ii += 2) {
if(result[ii] == result[ii + 1]) {
nstrs.push_back(result[ii]);
} else {
duplicated = false;
break;
}
}
if(duplicated) {
nstrs.push_back(']');
res.push_back(std::move(nstrs));
++result_count;
return result_count;
}
}
if((allow_extra_args_ || get_expected_max() > 1 || get_type_size() > 1) && !result.empty() &&
result.front() == '[' &&
result.back() == ']') { // this is now a vector string likely from the default or user entry
result.pop_back();
result.erase(result.begin());
for(auto &var : CLI::detail::split_up(result, ',')) {
if(!var.empty()) {
result_count += _add_result(std::move(var), res);
}
}
return result_count;
}
if(delimiter_ == '\0') {
res.push_back(std::move(result));
++result_count;
} else {
if((result.find_first_of(delimiter_) != std::string::npos)) {
for(const auto &var : CLI::detail::split(result, delimiter_)) {
if(!var.empty()) {
res.push_back(var);
++result_count;
}
}
} else {
res.push_back(std::move(result));
++result_count;
}
}
return result_count;
}
// [CLI11:option_inl_hpp:end]
} // namespace CLI
+160
View File
@@ -0,0 +1,160 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// This include is only needed for IDEs to discover symbols
#include "../Split.hpp"
// [CLI11:public_includes:set]
#include <algorithm>
#include <cstddef>
#include <iterator>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
// [CLI11:public_includes:end]
#include "../Error.hpp"
#include "../StringTools.hpp"
namespace CLI {
// [CLI11:split_inl_hpp:verbatim]
namespace detail {
CLI11_INLINE bool split_short(const std::string &current, std::string &name, std::string &rest) {
if(current.size() > 1 && current[0] == '-' && valid_first_char(current[1])) {
name = current.substr(1, 1);
rest = current.substr(2);
return true;
}
return false;
}
CLI11_INLINE bool split_long(const std::string &current, std::string &name, std::string &value) {
if(current.size() > 2 && current.compare(0, 2, "--") == 0 && valid_first_char(current[2])) {
auto loc = current.find_first_of('=');
if(loc != std::string::npos) {
name = current.substr(2, loc - 2);
value = current.substr(loc + 1);
} else {
name = current.substr(2);
value = "";
}
return true;
}
return false;
}
CLI11_INLINE bool split_windows_style(const std::string &current, std::string &name, std::string &value) {
if(current.size() > 1 && current[0] == '/' && valid_first_char(current[1])) {
auto loc = current.find_first_of(':');
if(loc != std::string::npos) {
name = current.substr(1, loc - 1);
value = current.substr(loc + 1);
} else {
name = current.substr(1);
value = "";
}
return true;
}
return false;
}
CLI11_INLINE std::vector<std::string> split_names(std::string current) {
std::vector<std::string> output;
std::size_t val = 0;
while((val = current.find(',')) != std::string::npos) {
output.push_back(trim_copy(current.substr(0, val)));
current = current.substr(val + 1);
}
output.push_back(trim_copy(current));
return output;
}
CLI11_INLINE std::vector<std::pair<std::string, std::string>> get_default_flag_values(const std::string &str) {
std::vector<std::string> flags = split_names(str);
flags.erase(std::remove_if(flags.begin(),
flags.end(),
[](const std::string &name) {
return ((name.empty()) || (!(((name.find_first_of('{') != std::string::npos) &&
(name.back() == '}')) ||
(name[0] == '!'))));
}),
flags.end());
std::vector<std::pair<std::string, std::string>> output;
output.reserve(flags.size());
for(auto &flag : flags) {
auto def_start = flag.find_first_of('{');
std::string defval = "false";
if((def_start != std::string::npos) && (flag.back() == '}')) {
defval = flag.substr(def_start + 1);
defval.pop_back();
flag.erase(def_start, std::string::npos); // NOLINT(readability-suspicious-call-argument)
}
flag.erase(0, flag.find_first_not_of("-!"));
output.emplace_back(flag, defval);
}
return output;
}
CLI11_INLINE std::tuple<std::vector<std::string>, std::vector<std::string>, std::string>
get_names(const std::vector<std::string> &input, bool allow_non_standard) {
std::vector<std::string> short_names;
std::vector<std::string> long_names;
std::string pos_name;
for(std::string name : input) {
if(name.empty()) {
continue;
}
if(name.length() > 1 && name[0] == '-' && name[1] != '-') {
if(name.length() == 2 && valid_first_char(name[1])) {
short_names.emplace_back(1, name[1]);
} else if(name.length() > 2) {
if(allow_non_standard) {
name = name.substr(1);
if(valid_name_string(name)) {
short_names.push_back(name);
} else {
throw BadNameString::BadLongName(name);
}
} else {
throw BadNameString::MissingDash(name);
}
} else {
throw BadNameString::OneCharName(name);
}
} else if(name.length() > 2 && name.substr(0, 2) == "--") {
name = name.substr(2);
if(valid_name_string(name)) {
long_names.push_back(name);
} else {
throw BadNameString::BadLongName(name);
}
} else if(name == "-" || name == "--" || name == "++") {
throw BadNameString::ReservedName(name);
} else {
if(!pos_name.empty()) {
throw BadNameString::MultiPositionalNames(name);
}
if(valid_name_string(name)) {
pos_name = name;
} else {
throw BadNameString::BadPositionalName(name);
}
}
}
return std::make_tuple(short_names, long_names, pos_name);
}
} // namespace detail
// [CLI11:split_inl_hpp:end]
} // namespace CLI
@@ -0,0 +1,688 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// This include is only needed for IDEs to discover symbols
#include "../StringTools.hpp"
// [CLI11:public_includes:set]
#include <algorithm>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <iomanip>
#include <iterator>
#include <locale>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// [CLI11:public_includes:end]
namespace CLI {
// [CLI11:string_tools_inl_hpp:verbatim]
namespace detail {
CLI11_INLINE bool isalpha(const std::string &str) {
return std::all_of(str.begin(), str.end(), [](char c) { return std::isalpha(c, std::locale()); });
}
CLI11_INLINE std::string to_lower(std::string str) {
std::transform(std::begin(str), std::end(str), std::begin(str), [](const std::string::value_type &x) {
return std::tolower(x, std::locale());
});
return str;
}
CLI11_INLINE std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
if(s.empty()) {
elems.emplace_back();
return elems;
}
std::size_t start = 0;
std::size_t end = 0;
while((end = s.find(delim, start)) != std::string::npos) {
elems.push_back(s.substr(start, end - start));
start = end + 1;
}
elems.push_back(s.substr(start));
return elems;
}
CLI11_INLINE std::string &ltrim(std::string &str) {
auto it = std::find_if(str.begin(), str.end(), [](char ch) { return !std::isspace<char>(ch, std::locale()); });
str.erase(str.begin(), it);
return str;
}
CLI11_INLINE std::string &ltrim(std::string &str, const std::string &filter) {
auto it = std::find_if(str.begin(), str.end(), [&filter](char ch) { return filter.find(ch) == std::string::npos; });
str.erase(str.begin(), it);
return str;
}
CLI11_INLINE std::string &rtrim(std::string &str) {
auto it = std::find_if(str.rbegin(), str.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale()); });
str.erase(it.base(), str.end());
return str;
}
CLI11_INLINE std::string &rtrim(std::string &str, const std::string &filter) {
auto it =
std::find_if(str.rbegin(), str.rend(), [&filter](char ch) { return filter.find(ch) == std::string::npos; });
str.erase(it.base(), str.end());
return str;
}
CLI11_INLINE std::string &remove_quotes(std::string &str) {
if(!str.empty() && (str.front() == '"' || str.front() == '\'' || str.front() == '`')) {
remove_outer(str, str.front());
}
return str;
}
CLI11_INLINE std::string &remove_outer(std::string &str, char key) {
if(str.length() > 1 && (str.front() == key)) {
if(str.front() == str.back()) {
str.pop_back();
str.erase(str.begin(), str.begin() + 1);
}
}
return str;
}
CLI11_INLINE std::string fix_newlines(const std::string &leader, std::string input) {
std::string::size_type n = 0;
while(n != std::string::npos && n < input.size()) {
n = input.find_first_of("\r\n", n);
if(n != std::string::npos) {
input.insert(n + 1, leader);
n += leader.size() + 1;
}
}
return input;
}
CLI11_INLINE std::ostream &format_aliases(std::ostream &out, const std::vector<std::string> &aliases, std::size_t wid) {
if(!aliases.empty()) {
out << std::setw(static_cast<int>(wid)) << " aliases: ";
bool front = true;
for(const auto &alias : aliases) {
if(!front) {
out << ", ";
} else {
front = false;
}
out << detail::fix_newlines(" ", alias);
}
out << "\n";
}
return out;
}
CLI11_INLINE bool valid_name_string(const std::string &str) {
if(str.empty() || !valid_first_char(str[0])) {
return false;
}
auto e = str.end();
for(auto c = str.begin() + 1; c != e; ++c)
if(!valid_later_char(*c))
return false;
return true;
}
CLI11_INLINE std::string get_group_separators() {
std::string separators{"_'"};
#if CLI11_HAS_RTTI != 0
char group_separator = std::use_facet<std::numpunct<char>>(std::locale()).thousands_sep();
separators.push_back(group_separator);
#endif
return separators;
}
CLI11_INLINE std::string find_and_replace(std::string str, std::string from, std::string to) {
std::size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
return str;
}
CLI11_INLINE void remove_default_flag_values(std::string &flags) {
auto loc = flags.find_first_of('{', 2);
while(loc != std::string::npos) {
auto finish = flags.find_first_of("},", loc + 1);
if((finish != std::string::npos) && (flags[finish] == '}')) {
flags.erase(flags.begin() + static_cast<std::ptrdiff_t>(loc),
flags.begin() + static_cast<std::ptrdiff_t>(finish) + 1);
}
loc = flags.find_first_of('{', loc + 1);
}
flags.erase(std::remove(flags.begin(), flags.end(), '!'), flags.end());
}
CLI11_INLINE std::ptrdiff_t
find_member(std::string name, const std::vector<std::string> &names, bool ignore_case, bool ignore_underscore) {
auto it = std::end(names);
if(ignore_case) {
if(ignore_underscore) {
name = detail::to_lower(detail::remove_underscore(name));
it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
return detail::to_lower(detail::remove_underscore(local_name)) == name;
});
} else {
name = detail::to_lower(name);
it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
return detail::to_lower(local_name) == name;
});
}
} else if(ignore_underscore) {
name = detail::remove_underscore(name);
it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
return detail::remove_underscore(local_name) == name;
});
} else {
it = std::find(std::begin(names), std::end(names), name);
}
return (it != std::end(names)) ? (it - std::begin(names)) : (-1);
}
CLI11_MODULE_INLINE const std::string &escapedChars() {
static const std::string s{"\b\t\n\f\r\"\\"};
return s;
}
CLI11_MODULE_INLINE const std::string &escapedCharsCode() {
static const std::string s{"btnfr\"\\"};
return s;
}
CLI11_MODULE_INLINE const std::string &bracketChars() {
static const std::string s{"\"'`[(<{"};
return s;
}
CLI11_MODULE_INLINE const std::string &matchBracketChars() {
static const std::string s{"\"'`])>}"};
return s;
}
CLI11_INLINE bool has_escapable_character(const std::string &str) {
return (str.find_first_of(escapedChars()) != std::string::npos);
}
CLI11_INLINE std::string add_escaped_characters(const std::string &str) {
std::string out;
out.reserve(str.size() + 4);
for(char s : str) {
auto sloc = escapedChars().find_first_of(s);
if(sloc != std::string::npos) {
out.push_back('\\');
out.push_back(escapedCharsCode()[sloc]);
} else {
out.push_back(s);
}
}
return out;
}
CLI11_INLINE std::uint32_t hexConvert(char hc) {
int hcode{0};
if(hc >= '0' && hc <= '9') {
hcode = (hc - '0');
} else if(hc >= 'A' && hc <= 'F') {
hcode = (hc - 'A' + 10);
} else if(hc >= 'a' && hc <= 'f') {
hcode = (hc - 'a' + 10);
} else {
hcode = -1;
}
return static_cast<uint32_t>(hcode);
}
CLI11_INLINE char make_char(std::uint32_t code) { return static_cast<char>(static_cast<unsigned char>(code)); }
CLI11_INLINE void append_codepoint(std::string &str, std::uint32_t code) {
if(code < 0x80) { // ascii code equivalent
str.push_back(static_cast<char>(code));
} else if(code < 0x800) { // \u0080 to \u07FF
// 110yyyyx 10xxxxxx; 0x3f == 0b0011'1111
str.push_back(make_char(0xC0 | code >> 6));
str.push_back(make_char(0x80 | (code & 0x3F)));
} else if(code < 0x10000) { // U+0800...U+FFFF
if(0xD800 <= code && code <= 0xDFFF) {
throw std::invalid_argument("[0xD800, 0xDFFF] are not valid code points.");
}
// 1110yyyy 10yxxxxx 10xxxxxx
str.push_back(make_char(0xE0 | code >> 12));
str.push_back(make_char(0x80 | (code >> 6 & 0x3F)));
str.push_back(make_char(0x80 | (code & 0x3F)));
} else if(code < 0x110000) { // U+010000 ... U+10FFFF
// 11110yyy 10yyxxxx 10xxxxxx 10xxxxxx
str.push_back(make_char(0xF0 | code >> 18));
str.push_back(make_char(0x80 | (code >> 12 & 0x3F)));
str.push_back(make_char(0x80 | (code >> 6 & 0x3F)));
str.push_back(make_char(0x80 | (code & 0x3F)));
} else { // code points above U+10FFFF are not valid
throw std::invalid_argument("values above 0x10FFFF are not valid code points.");
}
}
CLI11_INLINE std::string remove_escaped_characters(const std::string &str) {
std::string out;
out.reserve(str.size());
for(auto loc = str.begin(); loc < str.end(); ++loc) {
if(*loc == '\\') {
if(str.end() - loc < 2) {
throw std::invalid_argument("invalid escape sequence " + str);
}
auto ecloc = escapedCharsCode().find_first_of(*(loc + 1));
if(ecloc != std::string::npos) {
out.push_back(escapedChars()[ecloc]);
++loc;
} else if(*(loc + 1) == 'u') {
// must have 4 hex characters
if(str.end() - loc < 6) {
throw std::invalid_argument("unicode sequence must have 4 hex codes " + str);
}
std::uint32_t code{0};
std::uint32_t mplier{16 * 16 * 16};
for(int ii = 2; ii < 6; ++ii) {
std::uint32_t res = hexConvert(*(loc + ii));
if(res > 0x0F) {
throw std::invalid_argument("unicode sequence must have 4 hex codes " + str);
}
code += res * mplier;
mplier = mplier / 16;
}
append_codepoint(out, code);
loc += 5;
} else if(*(loc + 1) == 'U') {
// must have 8 hex characters
if(str.end() - loc < 10) {
throw std::invalid_argument("unicode sequence must have 8 hex codes " + str);
}
std::uint32_t code{0};
std::uint32_t mplier{16 * 16 * 16 * 16 * 16 * 16 * 16};
for(int ii = 2; ii < 10; ++ii) {
std::uint32_t res = hexConvert(*(loc + ii));
if(res > 0x0F) {
throw std::invalid_argument("unicode sequence must have 8 hex codes " + str);
}
code += res * mplier;
mplier = mplier / 16;
}
append_codepoint(out, code);
loc += 9;
} else if(*(loc + 1) == '0') {
out.push_back('\0');
++loc;
} else {
throw std::invalid_argument(std::string("unrecognized escape sequence \\") + *(loc + 1) + " in " + str);
}
} else {
out.push_back(*loc);
}
}
return out;
}
CLI11_INLINE std::size_t close_string_quote(const std::string &str, std::size_t start, char closure_char) {
std::size_t loc{0};
for(loc = start + 1; loc < str.size(); ++loc) {
if(str[loc] == closure_char) {
break;
}
if(str[loc] == '\\') {
// skip the next character for escaped sequences
++loc;
}
}
return loc;
}
CLI11_INLINE std::size_t close_literal_quote(const std::string &str, std::size_t start, char closure_char) {
auto loc = str.find_first_of(closure_char, start + 1);
return (loc != std::string::npos ? loc : str.size());
}
CLI11_INLINE std::size_t close_sequence(const std::string &str, std::size_t start, char closure_char) {
auto bracket_loc = matchBracketChars().find(closure_char);
switch(bracket_loc) {
case 0:
return close_string_quote(str, start, closure_char);
case 1:
case 2:
#if defined(_MSC_VER) && _MSC_VER < 1920
case(std::size_t)-1:
#else
case std::string::npos:
#endif
return close_literal_quote(str, start, closure_char);
default:
break;
}
std::string closures(1, closure_char);
auto loc = start + 1;
while(loc < str.size()) {
if(str[loc] == closures.back()) {
closures.pop_back();
if(closures.empty()) {
return loc;
}
}
bracket_loc = bracketChars().find(str[loc]);
if(bracket_loc != std::string::npos) {
switch(bracket_loc) {
case 0:
loc = close_string_quote(str, loc, str[loc]);
break;
case 1:
case 2:
loc = close_literal_quote(str, loc, str[loc]);
break;
default:
closures.push_back(matchBracketChars()[bracket_loc]);
break;
}
}
++loc;
}
if(loc > str.size()) {
loc = str.size();
}
return loc;
}
CLI11_INLINE std::vector<std::string> split_up(std::string str, char delimiter) {
auto find_ws = [delimiter](char ch) {
return (delimiter == '\0') ? std::isspace<char>(ch, std::locale()) : (ch == delimiter);
};
trim(str);
std::vector<std::string> output;
while(!str.empty()) {
if(bracketChars().find_first_of(str[0]) != std::string::npos) {
auto bracketLoc = bracketChars().find_first_of(str[0]);
auto end = close_sequence(str, 0, matchBracketChars()[bracketLoc]);
if(end >= str.size()) {
output.push_back(std::move(str));
str.clear();
} else {
output.push_back(str.substr(0, end + 1));
// The character following a closing quote/bracket is normally a delimiter and is
// consumed. If it is an ordinary character it must be retained (resume from it) so
// no characters are silently lost (e.g. `"abc"def` -> {"abc", "def"}). However if it
// is itself a quote/bracket opening character, resuming from it would start a fresh
// (potentially unterminated) quoted sequence that could swallow later delimiters, so
// it is skipped like the original delimiter case to keep splitting well behaved.
char follow = str[end + 1];
bool skip_follow = find_ws(follow) || (bracketChars().find_first_of(follow) != std::string::npos);
auto next = skip_follow ? end + 2 : end + 1;
if(next < str.size()) {
str = str.substr(next);
} else {
str.clear();
}
}
} else {
auto it = std::find_if(std::begin(str), std::end(str), find_ws);
if(it != std::end(str)) {
std::string value = std::string(str.begin(), it);
output.push_back(value);
str = std::string(it + 1, str.end());
} else {
output.push_back(str);
str.clear();
}
}
trim(str);
}
return output;
}
CLI11_INLINE std::size_t escape_detect(std::string &str, std::size_t offset) {
auto next = str[offset + 1];
if((next == '\"') || (next == '\'') || (next == '`')) {
if(offset == 0) {
// nothing precedes the trigger character, so there is nothing to reinterpret
return offset + 1;
}
auto astart = str.find_last_of("-/ \"\'`", offset - 1);
if(astart != std::string::npos) {
if(str[astart] == ((str[offset] == '=') ? '-' : '/'))
str[offset] = ' '; // interpret this as a space so the split_up works properly
}
}
return offset + 1;
}
CLI11_INLINE std::string binary_escape_string(const std::string &string_to_escape, bool force) {
// s is our escaped output string
std::string escaped_string{};
// loop through all characters
for(char c : string_to_escape) {
// check if a given character is printable
// the cast is necessary to avoid undefined behaviour
if(isprint(static_cast<unsigned char>(c)) == 0) {
std::stringstream stream;
// if the character is not printable
// we'll convert it to a hex string using a stringstream
// note that since char is signed we have to cast it to unsigned first
stream << std::hex << static_cast<unsigned int>(static_cast<unsigned char>(c));
std::string code = stream.str();
escaped_string += std::string("\\x") + (code.size() < 2 ? "0" : "") + code;
} else if(c == 'x' || c == 'X') {
// need to check for inadvertent binary sequences
if(!escaped_string.empty() && escaped_string.back() == '\\') {
escaped_string += std::string("\\x") + (c == 'x' ? "78" : "58");
} else {
escaped_string.push_back(c);
}
} else {
escaped_string.push_back(c);
}
}
if(escaped_string != string_to_escape || force) {
auto sqLoc = escaped_string.find('\'');
while(sqLoc != std::string::npos) {
escaped_string[sqLoc] = '\\';
escaped_string.insert(sqLoc + 1, "x27");
sqLoc = escaped_string.find('\'', sqLoc + 4);
}
escaped_string.insert(0, "'B\"(");
escaped_string.push_back(')');
escaped_string.push_back('"');
escaped_string.push_back('\'');
}
return escaped_string;
}
CLI11_INLINE bool is_binary_escaped_string(const std::string &escaped_string) {
size_t ssize = escaped_string.size();
if(escaped_string.compare(0, 3, "B\"(") == 0 && escaped_string.compare(ssize - 2, 2, ")\"") == 0) {
return true;
}
return (escaped_string.compare(0, 4, "'B\"(") == 0 && escaped_string.compare(ssize - 3, 3, ")\"'") == 0);
}
CLI11_INLINE std::string extract_binary_string(const std::string &escaped_string) {
std::size_t start{0};
std::size_t tail{0};
size_t ssize = escaped_string.size();
if(escaped_string.compare(0, 3, "B\"(") == 0 && escaped_string.compare(ssize - 2, 2, ")\"") == 0) {
start = 3;
tail = 2;
} else if(escaped_string.compare(0, 4, "'B\"(") == 0 && escaped_string.compare(ssize - 3, 3, ")\"'") == 0) {
start = 4;
tail = 3;
}
if(start == 0) {
return escaped_string;
}
std::string outstring;
outstring.reserve(ssize - start - tail);
std::size_t loc = start;
while(loc < ssize - tail) {
// ssize-2 to skip )" at the end
if(escaped_string[loc] == '\\' && (escaped_string[loc + 1] == 'x' || escaped_string[loc + 1] == 'X')) {
auto c1 = escaped_string[loc + 2];
auto c2 = escaped_string[loc + 3];
std::uint32_t res1 = hexConvert(c1);
std::uint32_t res2 = hexConvert(c2);
if(res1 <= 0x0F && res2 <= 0x0F) {
loc += 4;
outstring.push_back(static_cast<char>(res1 * 16 + res2));
continue;
}
}
outstring.push_back(escaped_string[loc]);
++loc;
}
return outstring;
}
CLI11_INLINE void remove_quotes(std::vector<std::string> &args) {
for(auto &arg : args) {
if(arg.empty()) {
continue;
}
if(arg.front() == '\"' && arg.back() == '\"') {
remove_quotes(arg);
// only remove escaped for string arguments not literal strings
arg = remove_escaped_characters(arg);
} else {
remove_quotes(arg);
}
}
}
CLI11_INLINE void handle_secondary_array(std::string &str) {
if(str.size() >= 2 && str.front() == '[' && str.back() == ']') {
// handle some special array processing for arguments if it might be interpreted as a secondary array
std::string tstr{"[["};
for(std::size_t ii = 1; ii < str.size(); ++ii) {
tstr.push_back(str[ii]);
tstr.push_back(str[ii]);
}
str = std::move(tstr);
}
}
CLI11_INLINE bool
process_quoted_string(std::string &str, char string_char, char literal_char, bool disable_secondary_array_processing) {
if(str.size() <= 1) {
return false;
}
if(detail::is_binary_escaped_string(str)) {
str = detail::extract_binary_string(str);
if(!disable_secondary_array_processing)
handle_secondary_array(str);
return true;
}
if(str.front() == string_char && str.back() == string_char) {
detail::remove_outer(str, string_char);
if(str.find_first_of('\\') != std::string::npos) {
str = detail::remove_escaped_characters(str);
}
if(!disable_secondary_array_processing)
handle_secondary_array(str);
return true;
}
if((str.front() == literal_char || str.front() == '`') && str.back() == str.front()) {
detail::remove_outer(str, str.front());
if(!disable_secondary_array_processing)
handle_secondary_array(str);
return true;
}
return false;
}
CLI11_INLINE std::string get_environment_value(const std::string &env_name) {
std::string ename_string;
#ifdef _MSC_VER
// Windows version
char *buffer = nullptr;
std::size_t sz = 0;
if(_dupenv_s(&buffer, &sz, env_name.c_str()) == 0 && buffer != nullptr) {
ename_string = std::string(buffer);
free(buffer);
}
#else
// This also works on Windows, but gives a warning
// MISRA static analysis need. MISRACPP2023-25_5_2-a-1
const char *buffer = nullptr;
buffer = std::getenv(env_name.c_str());
if(buffer != nullptr) {
ename_string = std::string(buffer);
}
#endif
return ename_string;
}
CLI11_INLINE std::ostream &streamOutAsParagraph(std::ostream &out,
const std::string &text,
std::size_t paragraphWidth,
const std::string &linePrefix,
bool skipPrefixOnFirstLine) {
std::istringstream lss(text);
std::string line = "";
while(std::getline(lss, line)) {
std::istringstream iss(line);
std::string word = "";
std::size_t charsWritten = 0;
if(!skipPrefixOnFirstLine)
out << linePrefix;
skipPrefixOnFirstLine = false; // subsequent lines always get the prefix
while(iss >> word) {
if(charsWritten > 0 && (word.length() + 1 + charsWritten > paragraphWidth)) {
out << '\n' << linePrefix;
charsWritten = 0;
}
if(charsWritten == 0) {
out << word;
charsWritten += word.length();
} else {
out << ' ' << word;
charsWritten += word.length() + 1;
}
}
if(!lss.eof())
out << '\n';
}
return out;
}
} // namespace detail
// [CLI11:string_tools_inl_hpp:end]
} // namespace CLI
@@ -0,0 +1,134 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
// This include is only needed for IDEs to discover symbols
#include "../TypeTools.hpp"
#include "../StringTools.hpp"
// [CLI11:public_includes:set]
#include <cerrno>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
// [CLI11:public_includes:end]
namespace CLI {
// [CLI11:type_tools_inl_hpp:verbatim]
namespace detail {
CLI11_INLINE std::int64_t to_flag_value(std::string val) noexcept {
static const std::string trueString("true");
static const std::string falseString("false");
if(val == trueString) {
return 1;
}
if(val == falseString) {
return -1;
}
val = detail::to_lower(std::move(val));
std::int64_t ret = 0;
if(val.size() == 1) {
if(val[0] >= '1' && val[0] <= '9') {
return (static_cast<std::int64_t>(val[0]) - '0');
}
switch(val[0]) {
case '0':
case 'f':
case 'n':
case '-':
ret = -1;
break;
case 't':
case 'y':
case '+':
ret = 1;
break;
default:
errno = EINVAL;
return -1;
}
return ret;
}
if(val == trueString || val == "on" || val == "yes" || val == "enable") {
ret = 1;
} else if(val == falseString || val == "off" || val == "no" || val == "disable") {
ret = -1;
} else {
char *loc_ptr{nullptr};
ret = std::strtoll(val.c_str(), &loc_ptr, 0);
if(loc_ptr != (val.c_str() + val.size()) && errno == 0) {
errno = EINVAL;
}
}
return ret;
}
CLI11_INLINE std::string sum_string_vector(const std::vector<std::string> &values) {
// First try a pure integer sum so that large integral totals (>= 1e16, or beyond the 2^53 mantissa of
// double) are preserved exactly and rendered as a plain integer rather than scientific notation
std::int64_t ival{0};
bool int_sum{true};
for(const auto &arg : values) {
std::int64_t tv{0};
if(!integral_conversion(arg, tv)) {
int_sum = false;
break;
}
// detect signed overflow before performing the addition since signed overflow is undefined behavior
if((tv > 0 && ival > (std::numeric_limits<std::int64_t>::max)() - tv) ||
(tv < 0 && ival < (std::numeric_limits<std::int64_t>::min)() - tv)) {
int_sum = false;
break;
}
ival += tv;
}
if(int_sum) {
return std::to_string(ival);
}
double val{0.0};
bool fail{false};
std::string output;
for(const auto &arg : values) {
double tv{0.0};
auto comp = lexical_cast(arg, tv);
if(!comp) {
errno = 0;
auto fv = detail::to_flag_value(arg);
fail = (errno != 0);
if(fail) {
break;
}
tv = static_cast<double>(fv);
}
val += tv;
}
if(fail) {
for(const auto &arg : values) {
output.append(arg);
}
} else {
std::ostringstream out;
out.precision(16);
out << val;
output = out.str();
}
return output;
}
} // namespace detail
// [CLI11:type_tools_inl_hpp:end]
} // namespace CLI
@@ -0,0 +1,355 @@
// Copyright (c) 2017-2026, 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
// IWYU pragma: private, include "CLI/CLI.hpp"
#include "../Validators.hpp"
#include "../Encoding.hpp"
#include "../Macros.hpp"
#include "../StringTools.hpp"
#include "../TypeTools.hpp"
// [CLI11:public_includes:set]
#include <functional>
#include <stdexcept>
#include <string>
#include <system_error>
#include <utility>
// [CLI11:public_includes:end]
namespace CLI {
// [CLI11:validators_inl_hpp:verbatim]
CLI11_INLINE Validator::Validator(std::string validator_desc, std::function<std::string(std::string &)> func)
: desc_function_([validator_desc]() { return validator_desc; }), func_(std::move(func)) {}
CLI11_INLINE Validator::Validator(std::function<std::string(std::string &)> op,
std::string validator_desc,
std::string validator_name)
: desc_function_([validator_desc]() { return validator_desc; }), func_(std::move(op)),
name_(std::move(validator_name)) {}
CLI11_INLINE std::string Validator::operator()(std::string &str) const {
std::string retstring;
if(active_) {
if(non_modifying_) {
std::string value = str;
retstring = func_(value);
} else {
retstring = func_(str);
}
}
return retstring;
}
CLI11_INLINE std::string Validator::operator()(const std::string &str) const {
std::string value = str;
return (active_) ? func_(value) : std::string{};
}
CLI11_NODISCARD CLI11_INLINE Validator Validator::description(std::string validator_desc) const {
Validator newval(*this);
newval.desc_function_ = [validator_desc]() { return validator_desc; };
return newval;
}
CLI11_NODISCARD CLI11_INLINE std::string Validator::get_description() const {
if(active_) {
return desc_function_();
}
return std::string{};
}
CLI11_NODISCARD CLI11_INLINE Validator Validator::name(std::string validator_name) const {
Validator newval(*this);
newval.name_ = std::move(validator_name);
return newval;
}
CLI11_NODISCARD CLI11_INLINE Validator Validator::active(bool active_val) const {
Validator newval(*this);
newval.active_ = active_val;
return newval;
}
CLI11_NODISCARD CLI11_INLINE Validator Validator::application_index(int app_index) const {
Validator newval(*this);
newval.application_index_ = app_index;
return newval;
}
CLI11_INLINE Validator Validator::operator&(const Validator &other) const {
Validator newval;
newval._merge_description(*this, other, " AND ");
// Give references (will make a copy in lambda function)
const std::function<std::string(std::string & filename)> &f1 = func_;
const std::function<std::string(std::string & filename)> &f2 = other.func_;
newval.func_ = [f1, f2](std::string &input) {
std::string s1 = f1(input);
std::string s2 = f2(input);
if(!s1.empty() && !s2.empty())
return std::string("(") + s1 + ") AND (" + s2 + ")";
return s1 + s2;
};
newval.active_ = active_ && other.active_;
newval.application_index_ = application_index_;
return newval;
}
CLI11_INLINE Validator Validator::operator|(const Validator &other) const {
Validator newval;
newval._merge_description(*this, other, " OR ");
// Give references (will make a copy in lambda function)
const std::function<std::string(std::string &)> &f1 = func_;
const std::function<std::string(std::string &)> &f2 = other.func_;
newval.func_ = [f1, f2](std::string &input) {
std::string s1 = f1(input);
std::string s2 = f2(input);
if(s1.empty() || s2.empty())
return std::string();
return std::string("(") + s1 + ") OR (" + s2 + ")";
};
newval.active_ = active_ && other.active_;
newval.application_index_ = application_index_;
return newval;
}
CLI11_INLINE Validator Validator::operator!() const {
Validator newval;
const std::function<std::string()> &dfunc1 = desc_function_;
newval.desc_function_ = [dfunc1]() {
auto str = dfunc1();
return (!str.empty()) ? std::string("NOT ") + str : std::string{};
};
// Give references (will make a copy in lambda function)
const std::function<std::string(std::string & res)> &f1 = func_;
newval.func_ = [f1, dfunc1](std::string &test) -> std::string {
std::string s1 = f1(test);
if(s1.empty()) {
return std::string("check ") + dfunc1() + " succeeded improperly";
}
return std::string{};
};
newval.active_ = active_;
newval.application_index_ = application_index_;
return newval;
}
CLI11_INLINE void
Validator::_merge_description(const Validator &val1, const Validator &val2, const std::string &merger) {
const std::function<std::string()> &dfunc1 = val1.desc_function_;
const std::function<std::string()> &dfunc2 = val2.desc_function_;
desc_function_ = [=]() {
std::string f1 = dfunc1();
std::string f2 = dfunc2();
if((f1.empty()) || (f2.empty())) {
return f1 + f2;
}
return std::string(1, '(') + f1 + ')' + merger + '(' + f2 + ')';
};
}
namespace detail {
#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
CLI11_INLINE path_type check_path(const char *file) noexcept {
std::error_code ec;
auto stat = std::filesystem::status(to_path(file), ec);
if(ec) {
return path_type::nonexistent;
}
switch(stat.type()) {
case std::filesystem::file_type::none: // LCOV_EXCL_LINE
case std::filesystem::file_type::not_found:
return path_type::nonexistent; // LCOV_EXCL_LINE
case std::filesystem::file_type::directory:
return path_type::directory;
case std::filesystem::file_type::symlink:
case std::filesystem::file_type::block:
case std::filesystem::file_type::character:
case std::filesystem::file_type::fifo:
case std::filesystem::file_type::socket:
case std::filesystem::file_type::regular:
case std::filesystem::file_type::unknown:
default:
return path_type::file;
}
}
#else
CLI11_INLINE path_type check_path(const char *file) noexcept {
#if defined(_MSC_VER)
struct __stat64 buffer;
if(_stat64(file, &buffer) == 0) {
return ((buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
}
#else
struct stat buffer;
if(stat(file, &buffer) == 0) {
return ((buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
}
#endif
return path_type::nonexistent;
}
#endif
CLI11_INLINE ExistingFileValidator::ExistingFileValidator() : Validator("FILE") {
func_ = [](std::string &filename) -> std::string {
if(filename.empty())
return std::string("File name is missing.");
auto path_result = check_path(filename.c_str());
if(path_result == path_type::nonexistent) {
return "File does not exist: " + filename;
}
if(path_result == path_type::directory) {
return "File is actually a directory: " + filename;
}
return std::string();
};
}
CLI11_INLINE ExistingDirectoryValidator::ExistingDirectoryValidator() : Validator("DIR") {
func_ = [](std::string &filename) {
auto path_result = check_path(filename.c_str());
if(path_result == path_type::nonexistent) {
return "Directory does not exist: " + filename;
}
if(path_result == path_type::file) {
return "Directory is actually a file: " + filename;
}
return std::string();
};
}
CLI11_INLINE ExistingPathValidator::ExistingPathValidator() : Validator("PATH(existing)") {
func_ = [](std::string &filename) {
auto path_result = check_path(filename.c_str());
if(path_result == path_type::nonexistent) {
return "Path does not exist: " + filename;
}
return std::string();
};
}
CLI11_INLINE NonexistentPathValidator::NonexistentPathValidator() : Validator("PATH(non-existing)") {
func_ = [](std::string &filename) {
auto path_result = check_path(filename.c_str());
if(path_result != path_type::nonexistent) {
return "Path already exists: " + filename;
}
return std::string();
};
}
CLI11_INLINE EscapedStringTransformer::EscapedStringTransformer() {
func_ = [](std::string &str) {
try {
if(str.size() > 1 && (str.front() == '\"' || str.front() == '\'' || str.front() == '`') &&
str.front() == str.back()) {
process_quoted_string(str);
} else if(str.find_first_of('\\') != std::string::npos) {
if(detail::is_binary_escaped_string(str)) {
str = detail::extract_binary_string(str);
} else {
str = remove_escaped_characters(str);
}
}
return std::string{};
} catch(const std::invalid_argument &ia) {
return std::string(ia.what());
}
};
}
} // namespace detail
CLI11_INLINE FileOnDefaultPath::FileOnDefaultPath(std::string default_path, bool enableErrorReturn)
: Validator("FILE") {
func_ = [default_path, enableErrorReturn](std::string &filename) {
auto path_result = detail::check_path(filename.c_str());
if(path_result == detail::path_type::nonexistent) {
std::string test_file_path = default_path;
if(!default_path.empty() && default_path.back() != '/' && default_path.back() != '\\') {
// Add folder separator
test_file_path += '/';
}
test_file_path.append(filename);
path_result = detail::check_path(test_file_path.c_str());
if(path_result == detail::path_type::file) {
filename = test_file_path;
} else {
if(enableErrorReturn) {
return "File does not exist: " + filename;
}
}
}
return std::string{};
};
}
namespace detail {
CLI11_INLINE std::pair<std::string, std::string> split_program_name(std::string commandline) {
// try to determine the programName
std::pair<std::string, std::string> vals;
trim(commandline);
auto esp = commandline.find_first_of(' ', 1);
while(detail::check_path(commandline.substr(0, esp).c_str()) != path_type::file) {
if(esp == std::string::npos) {
// if we have reached the end and haven't found a valid file just assume the first argument is the
// program name
if(commandline[0] == '"' || commandline[0] == '\'' || commandline[0] == '`') {
bool embeddedQuote = false;
auto keyChar = commandline[0];
auto end = commandline.find_first_of(keyChar, 1);
while((end != std::string::npos) && (commandline[end - 1] == '\\')) { // deal with escaped quotes
end = commandline.find_first_of(keyChar, end + 1);
embeddedQuote = true;
}
if(end != std::string::npos) {
vals.first = commandline.substr(1, end - 1);
esp = end + 1;
if(embeddedQuote) {
vals.first = find_and_replace(vals.first, std::string("\\") + keyChar, std::string(1, keyChar));
}
} else {
esp = commandline.find_first_of(' ', 1);
}
} else {
esp = commandline.find_first_of(' ', 1);
}
break;
}
esp = commandline.find_first_of(' ', esp + 1);
}
if(vals.first.empty()) {
vals.first = commandline.substr(0, esp);
rtrim(vals.first);
}
// strip the program name
vals.second = (esp < commandline.length() - 1) ? commandline.substr(esp + 1) : std::string{};
ltrim(vals.second);
return vals;
}
} // namespace detail
// [CLI11:validators_inl_hpp:end]
} // namespace CLI