15#include <nlohmann/json.hpp>
27 std::vector<nlohmann::json> json_storage;
31 Options(
int argc,
const char *
const argv[])
34 auto with_at = [](std::string_view s) {
return s.starts_with(
'@'); };
36 auto non_json = std::ranges::stable_partition(
opts_storage, with_at);
40 auto load = [](std::string_view s) {
41 return load_json(std::string(s.substr(1)));
43 auto json_obj = std::views::transform(
json_flags(), load);
44 json_storage =
decltype(json_storage){json_obj.begin(), json_obj.end()};
47 throw std::logic_error(
48 "This version of alpaqa was compiled without JSON support: "
49 "cannot parse options " +
55 [[nodiscard]] std::span<const std::string_view>
json_flags()
const {
58 [[nodiscard]] std::span<const std::string_view>
options()
const {
64 [[nodiscard]] std::span<const nlohmann::json> json_data()
const {
69 [[nodiscard]]
static nlohmann::json load_json(
const std::string &name) {
71 std::ifstream f{name};
73 throw std::runtime_error(
"Unable to open JSON file '" + name +
"'");
76 }
catch (nlohmann::json::exception &e) {
77 throw std::runtime_error(
"Unable to parse JSON file '" + name +
88 auto json_data = opts.json_data();
89 for (
size_t i = 0; i < json_data.size(); ++i)
91 if (
auto j = json_data[i].find(prefix); j != json_data[i].end())
94 std::string fname{opts.
json_flags()[i].substr(1)};
95 throw std::invalid_argument(
96 "Error in JSON file '" + fname +
"' at '" +
102 .quote_right =
""}) +
104 }
catch (nlohmann::json::exception &e) {
105 std::string fname{opts.
json_flags()[i].substr(1)};
106 throw std::invalid_argument(
"Error in JSON file '" + fname +
std::span< unsigned > used()
std::span< const std::string_view > json_flags() const
std::span< const std::string_view > options() const
std::vector< unsigned > used_storage
std::vector< std::string_view > opts_storage
Options(int argc, const char *const argv[])
void set_params(T &t, std::string_view prefix, std::span< const std::string_view > options, std::optional< std::span< unsigned > > used=std::nullopt)
Overwrites t based on the options that start with prefix.
void set_param(T &t, const json &j)
Update/overwrite the first argument based on the JSON object j.
std::string join_quote(std::ranges::input_range auto strings, join_quote_opt opt={})
Join the list of strings into a single string, using the separator given by opt.
decltype(auto) set_params(T &t, std::string_view prefix, Options &opts)
Custom parameter parsing exception.
std::vector< std::string > backtrace