AutoAPMS
Resilient Robot Mission Management
Loading...
Searching...
No Matches
yaml.hpp
1// Copyright 2024 Robin Müller
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#pragma once
16
17#include <algorithm>
18#include <boost/core/demangle.hpp>
19#include <map>
20#include <string>
21
22#include "auto_apms_util/exceptions.hpp"
23#include "auto_apms_util/filesystem.hpp"
24#include "yaml-cpp/yaml.h"
25
28
33#define AUTO_APMS_UTIL_DEFINE_YAML_CONVERSION_METHODS(ClassType) \
34 static ClassType fromFile(const std::string & path) \
35 { \
36 if (auto_apms_util::isFileEmpty(path)) return ClassType(); \
37 try { \
38 return YAML::LoadFile(path).as<ClassType>(); \
39 } catch (const YAML::ParserException & e) { \
40 throw auto_apms_util::exceptions::YAMLFormatError( \
41 "Format error when creating " + boost::core::demangle(typeid(ClassType).name()) + \
42 " from file: " + std::string(e.what())); \
43 } \
44 } \
45 static ClassType decode(const std::string & str) \
46 { \
47 const bool empty = std::all_of(str.begin(), str.end(), [](unsigned char c) { return std::isspace(c); }); \
48 return empty ? ClassType() : YAML::Load(str).as<ClassType>(); \
49 } \
50 std::string encode() const \
51 { \
52 YAML::Node root; \
53 root = *this; \
54 YAML::Emitter out; \
55 out << root; \
56 if (!out.good()) { \
57 throw std::runtime_error( \
58 "Error trying to encode " + boost::core::demangle(typeid(ClassType).name()) + ": " + out.GetLastError()); \
59 } \
60 return out.c_str(); \
61 }
62