Skip to content

Commit 5a47064

Browse files
authored
Support obtaining values from environment variables (#2)
1 parent 3bb4a6c commit 5a47064

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

example/config.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@ set_vec: [9, 5, 7]
1717
account_type: "Personal"
1818
v1: [8, 5, 65]
1919
default_opt: "yyds"
20+
ips: []

example/main.cpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,8 +174,9 @@ struct Config {
174174
DefaultTest default_test;
175175
std::string default_str{"hello default"};
176176
std::optional<std::string> default_opt{std::nullopt};
177+
std::vector<std::string> ips;
177178
};
178-
YCS_ADD_STRUCT(Config, ch, price, count, content, map, account_info, vec, set_vec, account_type, v1, default_test, default_str, default_opt)
179+
YCS_ADD_STRUCT(Config, ch, price, count, content, map, account_info, vec, set_vec, account_type, v1, default_test, default_str, default_opt, ips)
179180

180181
std::string to_string(const Config& cfg) {
181182
std::stringstream ss;
@@ -201,7 +202,13 @@ int main(int, char** argv) {
201202
}
202203
#else
203204
spdlog::info("Load yaml config");
204-
auto [cfg, error] = yaml_cpp_struct::from_yaml<Config>(argv[1]);
205+
// auto [cfg, error] = yaml_cpp_struct::from_yaml<Config>(argv[1]);
206+
// if (!cfg) {
207+
// spdlog::error("{}", error);
208+
// return -1;
209+
// }
210+
// export YCS_ENV_IPS=["Google","Runoob","Taobao"]
211+
auto [cfg, error] = yaml_cpp_struct::from_yaml_env<Config>(argv[1], "YCS_ENV_");
205212
if (!cfg) {
206213
spdlog::error("{}", error);
207214
return -1;

include/yaml_cpp_struct.hpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,22 @@ inline std::tuple<std::optional<T>, std::string> from_yaml(const std::string& st
143143
}
144144
}
145145

146+
template <typename T>
147+
inline std::tuple<std::optional<T>, std::string> from_yaml_env(const std::string& str, const std::string& prefix) {
148+
YAML::Node yaml_node = YAML::LoadFile(str);
149+
for (YAML::iterator it = yaml_node.begin(); it != yaml_node.end(); ++it) {
150+
std::string node_name = it->first.as<std::string>();
151+
std::transform(node_name.begin(), node_name.end(), node_name.begin(), ::toupper);
152+
auto environment_name = prefix + node_name;
153+
auto environment_content_ptr = std::getenv(environment_name.data());
154+
if (!environment_content_ptr)
155+
continue;
156+
std::string value{environment_content_ptr};
157+
it->second = YAML::Load(value);
158+
}
159+
return from_yaml<T, false>(YAML::Dump(yaml_node));
160+
}
161+
146162
} // namespace yaml_cpp_struct
147163

148164
namespace YAML {

0 commit comments

Comments
 (0)