Goby3 3.7.0
2026.11.12
Loading...
Searching...
No Matches
config_file.h
Go to the documentation of this file.
1// Copyright 2026:
2// GobySoft, LLC (2013-)
3// Community contributors (see AUTHORS file)
4// File authors:
5// Toby Schneider <toby@gobysoft.org>
6//
7//
8// This file is part of the Goby Underwater Autonomy Project Libraries
9// ("The Goby Libraries").
10//
11// The Goby Libraries are free software: you can redistribute them and/or modify
12// them under the terms of the GNU Lesser General Public License as published by
13// the Free Software Foundation, either version 2.1 of the License, or
14// (at your option) any later version.
15//
16// The Goby Libraries are distributed in the hope that they will be useful,
17// but WITHOUT ANY WARRANTY; without even the implied warranty of
18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19// GNU Lesser General Public License for more details.
20//
21// You should have received a copy of the GNU Lesser General Public License
22// along with Goby. If not, see <http://www.gnu.org/licenses/>.
23
24#ifndef GOBY_MIDDLEWARE_TOOL_CONFIG_FILE_H
25#define GOBY_MIDDLEWARE_TOOL_CONFIG_FILE_H
26
27#include <fstream>
28#include <regex>
29#include <sstream>
30#include <string>
31#include <vector>
32
33#include <google/protobuf/descriptor.h>
34#include <google/protobuf/io/tokenizer.h>
36#include <google/protobuf/text_format.h>
37#include <google/protobuf/util/json_util.h>
38
39#ifdef HAS_YAML_CPP
40#include <yaml-cpp/yaml.h>
41#endif
42
43#include "goby/exception.h"
44
45namespace goby
46{
47namespace middleware
48{
49namespace tool
50{
51#ifdef HAS_YAML_CPP
52namespace detail
53{
54inline std::string yaml_path(const std::string& parent, const std::string& key)
55{
56 return parent.empty() ? key : parent + "." + key;
57}
58
59inline void yaml_to_protobuf(const YAML::Node& node, google::protobuf::Message& msg,
60 const std::string& path);
61
63inline bool is_key_value_list(const google::protobuf::FieldDescriptor* field)
64{
65 if (field->is_map())
66 return true;
67 if (!field->is_repeated() ||
68 field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE)
69 return false;
70 const auto* type = field->message_type();
71 return type->field_count() == 2 && type->FindFieldByName("key") &&
72 type->FindFieldByName("value");
73}
74
75inline void yaml_scalar_to_field(const YAML::Node& node, google::protobuf::Message& msg,
76 const google::protobuf::FieldDescriptor* field,
77 const std::string& path)
78{
79 using google::protobuf::FieldDescriptor;
80 const auto* refl = msg.GetReflection();
81 const bool repeated = field->is_repeated();
82 const std::string text = node.as<std::string>();
83
84 auto fail = [&](const std::string& what)
85 { throw goby::Exception(path + ": " + what + " (got '" + text + "')"); };
86
87 try
88 {
89 switch (field->cpp_type())
90 {
91 case FieldDescriptor::CPPTYPE_INT32:
92 repeated ? refl->AddInt32(&msg, field, node.as<std::int32_t>())
93 : refl->SetInt32(&msg, field, node.as<std::int32_t>());
94 break;
95 case FieldDescriptor::CPPTYPE_INT64:
96 repeated ? refl->AddInt64(&msg, field, node.as<std::int64_t>())
97 : refl->SetInt64(&msg, field, node.as<std::int64_t>());
98 break;
99 case FieldDescriptor::CPPTYPE_UINT32:
100 repeated ? refl->AddUInt32(&msg, field, node.as<std::uint32_t>())
101 : refl->SetUInt32(&msg, field, node.as<std::uint32_t>());
102 break;
103 case FieldDescriptor::CPPTYPE_UINT64:
104 repeated ? refl->AddUInt64(&msg, field, node.as<std::uint64_t>())
105 : refl->SetUInt64(&msg, field, node.as<std::uint64_t>());
106 break;
107 case FieldDescriptor::CPPTYPE_DOUBLE:
108 repeated ? refl->AddDouble(&msg, field, node.as<double>())
109 : refl->SetDouble(&msg, field, node.as<double>());
110 break;
111 case FieldDescriptor::CPPTYPE_FLOAT:
112 repeated ? refl->AddFloat(&msg, field, node.as<float>())
113 : refl->SetFloat(&msg, field, node.as<float>());
114 break;
115 case FieldDescriptor::CPPTYPE_BOOL:
116 repeated ? refl->AddBool(&msg, field, node.as<bool>())
117 : refl->SetBool(&msg, field, node.as<bool>());
118 break;
119 case FieldDescriptor::CPPTYPE_STRING:
120 repeated ? refl->AddString(&msg, field, text) : refl->SetString(&msg, field, text);
121 break;
122 case FieldDescriptor::CPPTYPE_ENUM:
123 {
124 const auto* value = field->enum_type()->FindValueByName(text);
125 if (!value && std::regex_match(text, std::regex("-?[0-9]+")))
126 value = field->enum_type()->FindValueByNumber(std::stoi(text));
127 if (!value)
128 fail("not a value of enum " + field->enum_type()->full_name());
129 repeated ? refl->AddEnum(&msg, field, value) : refl->SetEnum(&msg, field, value);
130 break;
131 }
132 case FieldDescriptor::CPPTYPE_MESSAGE:
133 fail("expected a map for message field " + field->message_type()->full_name());
134 }
135 }
136 catch (const YAML::Exception&)
137 {
138 fail("not a valid " + std::string(field->cpp_type_name()));
139 }
140}
141
142inline void yaml_to_field(const YAML::Node& node, google::protobuf::Message& msg,
143 const google::protobuf::FieldDescriptor* field, const std::string& path)
144{
145 using google::protobuf::FieldDescriptor;
146 const auto* refl = msg.GetReflection();
147
148 if (node.IsNull())
149 return;
150
151 if (detail::is_key_value_list(field) && node.IsMap())
152 {
153 if (!node.IsMap())
154 throw goby::Exception(path + ": expected a map");
155 const auto* entry_desc = field->message_type();
156 for (const auto& kv : node)
157 {
158 const std::string key = kv.first.as<std::string>();
159 auto& entry = *refl->AddMessage(&msg, field);
160 yaml_scalar_to_field(kv.first, entry, entry_desc->FindFieldByName("key"),
161 path + "." + key);
162 yaml_to_field(kv.second, entry, entry_desc->FindFieldByName("value"), path + "." + key);
163 }
164 return;
165 }
166
167 if (field->is_repeated())
168 {
169 // a scalar or map where a list is expected is treated as a one element list
170 if (!node.IsSequence())
171 {
172 yaml_to_field(YAML::Node(YAML::NodeType::Sequence), msg, field, path);
173 if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE)
174 yaml_to_protobuf(node, *refl->AddMessage(&msg, field), path);
175 else
176 yaml_scalar_to_field(node, msg, field, path);
177 return;
178 }
179 int i = 0;
180 for (const auto& item : node)
181 {
182 const std::string item_path = path + "[" + std::to_string(i++) + "]";
183 if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE)
184 yaml_to_protobuf(item, *refl->AddMessage(&msg, field), item_path);
185 else if (item.IsScalar())
186 yaml_scalar_to_field(item, msg, field, item_path);
187 else
188 throw goby::Exception(item_path + ": expected a scalar");
189 }
190 }
191 else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE)
192 {
193 yaml_to_protobuf(node, *refl->MutableMessage(&msg, field), path);
194 }
195 else if (node.IsScalar())
196 {
197 yaml_scalar_to_field(node, msg, field, path);
198 }
199 else
200 {
201 throw goby::Exception(path + ": expected a scalar");
202 }
203}
204
205inline void yaml_to_protobuf(const YAML::Node& node, google::protobuf::Message& msg,
206 const std::string& path)
207{
208 if (node.IsNull())
209 return;
210 if (!node.IsMap())
211 throw goby::Exception((path.empty() ? std::string("top level") : path) +
212 ": expected a map for message " + msg.GetDescriptor()->full_name());
213
214 const auto* desc = msg.GetDescriptor();
215
216 // a message that only wraps a map can be written as the map itself
217 if (desc->field_count() == 1 && is_key_value_list(desc->field(0)) &&
218 !(node[desc->field(0)->name()] || node[desc->field(0)->camelcase_name()]))
219 {
220 yaml_to_field(node, msg, desc->field(0), path);
221 return;
222 }
223
224 for (const auto& kv : node)
225 {
226 const std::string key = kv.first.as<std::string>();
227 const auto* field = desc->FindFieldByName(key);
228 if (!field)
229 field = desc->FindFieldByCamelcaseName(key);
230 if (!field)
231 throw goby::Exception(yaml_path(path, key) + " (line " +
232 std::to_string(kv.first.Mark().line + 1) +
233 "): no such field in " + desc->full_name());
234 yaml_to_field(kv.second, msg, field, yaml_path(path, key));
235 }
236}
237} // namespace detail
238
243inline void yaml_to_protobuf(const std::string& yaml, google::protobuf::Message& msg)
244{
245 YAML::Node root;
246 try
247 {
248 root = YAML::Load(yaml);
249 }
250 catch (const YAML::Exception& e)
251 {
252 throw goby::Exception(std::string("YAML parse error: ") + e.what());
253 }
254 detail::yaml_to_protobuf(root, msg, "");
255}
256#endif // HAS_YAML_CPP
257
259inline constexpr bool yaml_supported()
260{
261#ifdef HAS_YAML_CPP
262 return true;
263#else
264 return false;
265#endif
266}
267
268namespace detail
269{
271{
272 public:
273 void AddError(int line, int column, const std::string& message) override
274 {
275 errors.push_back("line " + std::to_string(line + 1) + " column " +
276 std::to_string(column + 1) + ": " + message);
277 }
278 void AddWarning(int, int, const std::string&) override {}
279 std::vector<std::string> errors;
280};
281} // namespace detail
282
289inline void parse_config_string(const std::string& contents, const std::string& path,
291{
292 auto ends_with = [&](const std::string& suffix)
293 {
294 return path.size() >= suffix.size() &&
295 path.compare(path.size() - suffix.size(), suffix.size(), suffix) == 0;
296 };
297
298 if (ends_with(".yml") || ends_with(".yaml"))
299 {
300#ifdef HAS_YAML_CPP
301 yaml_to_protobuf(contents, msg);
302#else
303 throw goby::Exception("YAML support is not compiled in (install libyaml-cpp-dev and "
304 "build with -Denable_yaml=ON), or use a JSON or TextFormat file");
305#endif
306 }
307 else if (ends_with(".json"))
308 {
309 google::protobuf::util::JsonParseOptions opts;
310 auto status = google::protobuf::util::JsonStringToMessage(contents, &msg, opts);
311 if (!status.ok())
312 throw goby::Exception("JSON parse error: " + status.ToString());
313 }
314 else
315 {
316 google::protobuf::TextFormat::Parser parser;
317 detail::CollectingErrorCollector error_collector;
318 parser.RecordErrorsTo(&error_collector);
319 if (!parser.MergeFromString(contents, &msg) || !error_collector.errors.empty())
320 {
321 std::string what = "TextFormat parse error";
322 for (const auto& e : error_collector.errors) what += "; " + e;
323 throw goby::Exception(what);
324 }
325 }
326}
327
329inline void load_config_file(const std::string& path, google::protobuf::Message& msg)
330{
331 std::ifstream fin(path);
332 if (!fin.is_open())
333 throw goby::Exception("could not open '" + path + "' for reading");
334 std::stringstream ss;
335 ss << fin.rdbuf();
336 parse_config_string(ss.str(), path, msg);
337}
338
339} // namespace tool
340} // namespace middleware
341} // namespace goby
342
343#endif
simple exception class for goby applications
Definition exception.h:35
void AddError(int line, int column, const std::string &message) override
void AddWarning(int, int, const std::string &) override
detail namespace with internal helper functions
Definition json.hpp:263
void load_config_file(const std::string &path, google::protobuf::Message &msg)
Merge a configuration file into a Protobuf message (see parse_config_string).
void parse_config_string(const std::string &contents, const std::string &path, google::protobuf::Message &msg)
Merge configuration text into a Protobuf message.
constexpr bool yaml_supported()
True if YAML configuration files are supported by this build.
The global namespace for the Goby project.
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::PROTOBUF_NAMESPACE_ID::FieldOptions, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::goby::GobyFieldOptions >, 11, false > field
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::PROTOBUF_NAMESPACE_ID::MessageOptions, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::goby::GobyMessageOptions >, 11, false > msg