blob: d58822c2b596a05b6e8ba8141c072ddf7ab3f45f [file] [log] [blame]
Václav Kubernátbabbab92021-01-27 09:25:05 +01001#include <fmt/format.h>
Václav Kubernát7efd6d52021-11-09 01:31:11 +01002#include <libyang-cpp/DataNode.hpp>
3#include <libyang-cpp/Set.hpp>
Václav Kubernátcbdc98a2021-01-28 13:24:37 +01004#include "utils/libyang.h"
5
Tomáš Peckafd5ebd32021-10-07 09:48:13 +02006namespace velia::utils {
7
Václav Kubernát7efd6d52021-11-09 01:31:11 +01008const char* getValueAsString(const libyang::DataNode& node)
Václav Kubernátcbdc98a2021-01-28 13:24:37 +01009{
Václav Kubernát7efd6d52021-11-09 01:31:11 +010010 if (node.schema().nodeType() != libyang::NodeType::Leaf) {
Václav Kubernátcbdc98a2021-01-28 13:24:37 +010011 throw std::logic_error("retrieveString: invalid node");
12 }
13
Václav Kubernát7efd6d52021-11-09 01:31:11 +010014 return node.asTerm().valueStr().data();
Václav Kubernátcbdc98a2021-01-28 13:24:37 +010015}
16
Václav Kubernát7efd6d52021-11-09 01:31:11 +010017std::optional<libyang::DataNode> getUniqueSubtree(const libyang::DataNode& start, const char* path)
Václav Kubernátcbdc98a2021-01-28 13:24:37 +010018{
Václav Kubernát7efd6d52021-11-09 01:31:11 +010019 auto set = start.findXPath(path);
Václav Kubernátcbdc98a2021-01-28 13:24:37 +010020
Václav Kubernát7efd6d52021-11-09 01:31:11 +010021 switch(set.size()) {
Tomáš Peckafd90efb2021-10-07 10:40:44 +020022 case 0:
23 return std::nullopt;
24 case 1:
Václav Kubernát7efd6d52021-11-09 01:31:11 +010025 return set.front();
Tomáš Peckafd90efb2021-10-07 10:40:44 +020026 default:
Václav Kubernát7efd6d52021-11-09 01:31:11 +010027 throw std::runtime_error(fmt::format("getUniqueSubtree({}, {}): more than one match (got {})", start.path().get().get(), path, set.size()));
Tomáš Peckafd90efb2021-10-07 10:40:44 +020028 }
Václav Kubernátcbdc98a2021-01-28 13:24:37 +010029}
Tomáš Peckafd5ebd32021-10-07 09:48:13 +020030}