У меня есть файл test.yml,
test1:
test1_file: 'test.yml'
Я хочу загрузить этот файл yaml в код C++ и получить из него данные.
В моем случае есть дополнительные файлы, которые необходимо объединить с данными. Я нашел ответ на этот вопрос здесь (я думаю...). Итак, yaml-cpp, что кажется изящным. Честно говоря, его интерфейс показался немного странным, но мне очень не хотелось изобретать велосипед. Этот const YAML::Node & cnode(const YAML::Node & node) { return node;}
довольно пахнет кодом.
Итак, у меня есть код, который пытается перейти к заданному узлу...
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <yaml-cpp/yaml.h>
using node_name = std::string;
using node_path = std::vector<node_name>;
const YAML::Node & constify(const YAML::Node & node) {
return node;
}
YAML::Node navigate(const YAML::Node & root_node, const node_path & path) {
// no path elements?
if ( path.empty() ) {
return root_node;
}
// any elements are empty?
if ( std::any_of(path.begin(), path.end(), [](const auto & part){return part.empty();}) ) {
throw std::invalid_argument{"navigate to node_path with empty elements"};
}
// set up initial root node info
YAML::Node current = root_node;
const node_name * parent_node_name = nullptr;
auto throw_path_not_found = [&](const node_name & element_name) {
node_path not_found_node_path;
if ( parent_node_name ) {
// parent_node_name points to the last processed parent
// if we pass it as-is as an end-iterator, then it will
// not be included in the container. So increment it.
//
// Then, we're at the current node name (which wasn't found)
// so increment it once more to have the full path.
parent_node_name += 2;
not_found_node_path = {&*path.begin(), parent_node_name};
} else {
not_found_node_path = {path.begin(), path.begin() + 1};
}
// throw yaml_path_not_found{not_found_node_path, current, element_name};
std::string err_msg{"path not found: "};
std::for_each(not_found_node_path.begin(), not_found_node_path.end(), [&](const node_name & n){err_msg += n + ".";});
throw std::runtime_error{std::move(err_msg)};
};
// query node to see if we can continue
auto query_node_type = [&](const node_name & element_name){
switch (current.Type()) {
case YAML::NodeType::Scalar:
// Reached end of node chain before reaching end of desired node path?
if ( &element_name != &path.back() ) {
throw_path_not_found(element_name);
}
return;
case YAML::NodeType::Sequence: // aka array
// this can be fine if the next node element is an integer to access the array
// otherwise we'll get an Undefined node on the next iteration.
return;
case YAML::NodeType::Map:
// this can be fine if the next node element is a key into the map
// otherwise we'll get an Undefined node on the next iteration.
return;
case YAML::NodeType::Null:
// the node path exists but contains no value ???
// more like a std::set, I think?
// if this causes issues, then fix it.
return;
case YAML::NodeType::Undefined:
throw_path_not_found(element_name);
// no-default:
// allow compiler to warn on changes to enum
}
throw std::logic_error{std::string{"unexpected node type "} + std::to_string(current.Type()) + " returned from yaml-cpp"};
};
// loop through path elements querying to see if we've prematurely stopped
for ( const auto & element : path ) {
current = current[element];
query_node_type(element);
parent_node_name = &element;
}
return current;
}
node_path split_node_path(const std::string & path) {
node_path result;
result.emplace_back();
// prod code just uses boost::algorithm::string::split
for ( char c : path ) {
if ( '.' == c ) {
result.emplace_back();
continue;
}
result.back().push_back(c);
}
return result;
}
Идея состоит в том, что я должен предоставить путь к узлу, например "test1.test1_file"
, и для этого он должен получить узел. Но я заметил, что это отлично работает в первый раз, но во второй раз заканчивается вылетом, потому что узел не найден. Чего ждать?
Да, хорошо:
void dump(const YAML::Node & node) {
std::cout << "...DUMP...\n" << YAML::Dump(node) << std::endl;
}
int main(int argc, char **argv) {
if ( 3 != argc ) {
std::cerr << "Usage: ./a.out test.yml test1.test1.file\n";
return EXIT_FAILURE;
}
try {
YAML::Node root_node = YAML::LoadFile(argv[1]);
dump(root_node);
navigate(root_node, split_node_path(argv[2]));
dump(root_node);
navigate(root_node, split_node_path(argv[2]));
} catch (const std::exception & e) {
std::cerr << "exception: " << e.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Построить это и выполнить g++ test.cpp -lyaml-cpp -std=c++17
с g++ (Ubuntu 6.2.0-3ubuntu11~16.04) 6.2.0 20160901
удается. Однако его вызов дает неожиданный результат:
$ ./a.out test.yml test1.test1_file
...DUMP...
test1:
test1_file: test.yml
...DUMP...
test1_file: test.yml
exception: path not found: test1.
Я полностью ожидаю, что дампы будут идентичными (и никаких исключений не будет): navigate()
принимает const YAML::Node &
. Это говорит мне, что он не должен изменять корневой узел. Так где именно он модифицируется? Что еще более важно, что я делаю неправильно?
Я подозреваю, что это связано с другим ответом, требующим, чтобы функция cnode()
была константой YAML::Node
s. Но когда я попытался сделать то же самое, похоже, это не помогло (о чем свидетельствует функция constify()
, которая не используется в этом минимальном примере).