RSTools 3.1.0
Versatile C++20 utility library
Loading...
Searching...
No Matches
quickstart.cpp

A short tour: command line, logging and strings.

A short tour: command line, logging and strings.

#include <RST/RST.hpp>
#include <memory>
#include <string>
int main(int argc, char** argv) {
// Arguments: -h/--help and errors are handled by the parser, nothing throws
RST::Parser::ArgParser parser("quickstart", "A short tour of RSTools.");
parser.addFlag({"-v", "--verbose"}, "Print more details");
parser.addOption({"-n", "--count"}, "How many greetings").integer().range(1, 10).defaultValue(1);
if (auto result = parser.parse(argc, argv); !result) {
result.print();
return result.exitCode();
}
// Logging
RST::Log::Logger logger("App");
logger.addSink(std::make_shared<RST::Log::ConsoleSink>());
// Strings
const std::string greeting = RST::String::trimCopy(" Hello RSTools! ");
for (int i = 0; i < parser.get<int>("--count").value_or(1); ++i)
logger.info("{}", greeting);
logger.debug("{} with {} cores", RST::System::getOSName(), RST::System::getCpuCores());
return 0;
}
Named logger that formats messages and sends them to its sinks; thread-safe.
Definition Logger.hpp:24
void setLevel(LogLevel level) noexcept
Minimum level to log; LogLevel::Off disables the logger.
Definition Logger.hpp:37
void debug(std::format_string< Args... > format, Args &&... args) noexcept
Definition Logger.hpp:71
void info(std::format_string< Args... > format, Args &&... args) noexcept
Definition Logger.hpp:72
void addSink(std::shared_ptr< ISink > sink)
Command-line parser with flags, options, positionals, subcommands and generated help.
Definition ArgParser.hpp:34
Argument & addOption(std::vector< std::string > flags, std::string description)
Adds an option taking a value: --name value, --name=value, -n value or -n5.
Argument & addFlag(std::vector< std::string > flags, std::string description)
Adds a flag without value; short flags can be bundled, like -abc.
ParseResult parse(int argc, const char *const *argv)
Parses the arguments of main.
bool isSet(std::string_view name) const
Shortcut for Argument::isSet(); name is a flag (-v, --verbose) or a name (verbose).
Definition ArgParser.hpp:67
std::optional< T > get(std::string_view name) const
Shortcut for Argument::get().
Definition ArgParser.hpp:73
Argument & range(double min, double max)
Only accepts numbers from min to max, inclusive.
Definition Argument.hpp:61
Argument & defaultValue(const T &value)
Value used when the argument is not given.
Definition Argument.hpp:46
std::string trimCopy(std::string_view str, std::string_view chars=Whitespace)
std::string getOSName()
Operating system family, such as Linux or Windows 64-bit.
std::size_t getCpuCores() noexcept
Number of logical cores, at least 1.