libcruft-util/cmdopt2/arg.hpp

101 lines
2.8 KiB
C++

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2022, Danny Robson <danny@nerdcruft.net>
*/
#pragma once
#include <cruft/util/debug/assert.hpp>
#include <cruft/util/parse/value.hpp>
#include <cruft/util/cast.hpp>
#include <optional>
#include <string>
#include <functional>
namespace cruft::cmdopt2 {
struct argument {
std::string name;
std::optional<std::string> description;
bool required = false;
using acceptor1_t = std::function<void(std::string_view)>;
std::optional<acceptor1_t> acceptor1;
};
template <typename BaseT>
struct ops : argument {
template <typename ValueT>
BaseT bind (ValueT&&) = delete;
template <typename ValueT>
BaseT
bind (ValueT &ref)
{
CHECK (!acceptor1);
if constexpr (std::is_same_v<ValueT, std::string>) {
acceptor1 = [&ref] (std::string_view str) { ref = str; };
} else {
acceptor1 = [&ref] (std::string_view str) { ref = parse::from_string<ValueT> (str); };
}
return get ();
}
template <typename ValueT>
BaseT
bind (std::optional<ValueT> &ref)
{
CHECK (!acceptor1);
if constexpr (std::is_same_v<ValueT, std::string>) {
acceptor1 = [&ref] (std::string_view str) { ref = str; };
} else {
acceptor1 = [&ref] (std::string_view str) { ref = parse::from_string<ValueT> (str); };
}
return get ();
}
BaseT
get (void) const
{
return reinterpret_cast<BaseT const&> (*this);
}
};
struct positional : public ops<positional> {
static positional create (char const *name);
static positional create (std::string_view name);
static positional create (std::string const &name);
static positional create (std::string &&name);
int count = 1;
};
struct keyword : public ops<keyword> {
using acceptor0_t = std::function<void(void)>;
std::optional<acceptor0_t> acceptor0;
static keyword create (char const *name);
static keyword create (std::string_view name);
static keyword create (std::string const &name);
static keyword create (std::string &&name);
keyword flag (void) const;
keyword flag (std::string_view long_) const;
keyword flag (char short_) const;
keyword count (int &) const;
keyword present (bool &) const;
std::optional<char> short_;
std::optional<std::string> long_;
};
}