Flex  0.17.9
yaml_utils.h
Go to the documentation of this file.
1 
16 #ifndef UTILS_YAML_UTILS_H_
17 #define UTILS_YAML_UTILS_H_
18 
19 #include <yaml-cpp/yaml.h>
20 #include <filesystem>
21 #include <string>
22 #include <vector>
23 #include "flex/utils/result.h"
24 
25 #include "glog/logging.h"
26 
27 namespace gs {
28 
29 std::vector<std::string> get_yaml_files(const std::string& plugin_dir);
30 
31 Result<std::string> get_json_string_from_yaml(const std::string& file_path);
32 
33 Result<std::string> get_json_string_from_yaml(const YAML::Node& yaml_node);
34 
35 Status write_yaml_node_to_yaml_string(const YAML::Node& node,
36  YAML::Emitter& emitter);
37 
38 Result<std::string> get_yaml_string_from_yaml_node(const YAML::Node& node);
39 
40 namespace config_parsing {
41 template <typename T>
42 bool get_scalar(YAML::Node node, const std::string& key, T& value) {
43  YAML::Node cur = node[key];
44  if (cur && cur.IsScalar()) {
45  value = cur.as<T>();
46  return true;
47  }
48  return false;
49 }
50 
51 template <typename T>
52 bool get_sequence(YAML::Node node, const std::string& key,
53  std::vector<T>& seq) {
54  YAML::Node cur = node[key];
55  if (cur && cur.IsSequence()) {
56  int num = cur.size();
57  seq.clear();
58  for (int i = 0; i < num; ++i) {
59  seq.push_back(cur[i].as<T>());
60  }
61  return true;
62  }
63  return false;
64 }
65 
66 template <typename V>
67 static bool expect_config(YAML::Node root, const std::string& key,
68  const V& value) {
69  V got;
70  if (!get_scalar(root, key, got)) {
71  LOG(ERROR) << "Expect key: " << key << " set to " << value
72  << " but not set";
73  return false;
74  }
75  if (got != value) {
76  LOG(ERROR) << "Expect key: " << key << " set to " << value << " but got "
77  << got;
78  return false;
79  }
80  return true;
81 }
82 
83 } // namespace config_parsing
84 } // namespace gs
85 
86 #endif // UTILS_YAML_UTILS_H_
gs::write_yaml_node_to_yaml_string
Status write_yaml_node_to_yaml_string(const YAML::Node &node, YAML::Emitter &emitter)
Definition: yaml_utils.cc:135
gs::get_yaml_files
std::vector< std::string > get_yaml_files(const std::string &plugin_dir)
Definition: yaml_utils.cc:25
gs::config_parsing::get_scalar
bool get_scalar(YAML::Node node, const std::string &key, T &value)
Definition: yaml_utils.h:42
gs
Definition: adj_list.h:23
result.h
gs::get_yaml_string_from_yaml_node
Result< std::string > get_yaml_string_from_yaml_node(const YAML::Node &node)
Definition: yaml_utils.cc:122
gs::config_parsing::get_sequence
bool get_sequence(YAML::Node node, const std::string &key, std::vector< T > &seq)
Definition: yaml_utils.h:52
gs::config_parsing::expect_config
static bool expect_config(YAML::Node root, const std::string &key, const V &value)
Definition: yaml_utils.h:67
gs::get_json_string_from_yaml
Result< std::string > get_json_string_from_yaml(const std::string &file_path)
Definition: yaml_utils.cc:94