Skip to content

Commit

Permalink
Support obtaining values from environment variables
Browse files Browse the repository at this point in the history
  • Loading branch information
fantasy-peak committed Dec 21, 2023
1 parent 3bb4a6c commit fcf16a3
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
1 change: 1 addition & 0 deletions example/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ set_vec: [9, 5, 7]
account_type: "Personal"
v1: [8, 5, 65]
default_opt: "yyds"
ips: []
11 changes: 9 additions & 2 deletions example/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,9 @@ struct Config {
DefaultTest default_test;
std::string default_str{"hello default"};
std::optional<std::string> default_opt{std::nullopt};
std::vector<std::string> ips;
};
YCS_ADD_STRUCT(Config, ch, price, count, content, map, account_info, vec, set_vec, account_type, v1, default_test, default_str, default_opt)
YCS_ADD_STRUCT(Config, ch, price, count, content, map, account_info, vec, set_vec, account_type, v1, default_test, default_str, default_opt, ips)

std::string to_string(const Config& cfg) {
std::stringstream ss;
Expand All @@ -201,7 +202,13 @@ int main(int, char** argv) {
}
#else
spdlog::info("Load yaml config");
auto [cfg, error] = yaml_cpp_struct::from_yaml<Config>(argv[1]);
// auto [cfg, error] = yaml_cpp_struct::from_yaml<Config>(argv[1]);
// if (!cfg) {
// spdlog::error("{}", error);
// return -1;
// }
// export YCS_ENV_IPS=["Google","Runoob","Taobao"]
auto [cfg, error] = yaml_cpp_struct::from_yaml_env<Config>(argv[1], "YCS_ENV_");
if (!cfg) {
spdlog::error("{}", error);
return -1;
Expand Down
16 changes: 16 additions & 0 deletions include/yaml_cpp_struct.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,22 @@ inline std::tuple<std::optional<T>, std::string> from_yaml(const std::string& st
}
}

template <typename T>
inline std::tuple<std::optional<T>, std::string> from_yaml_env(const std::string& str, const std::string& prefix) {
YAML::Node yaml_node = YAML::LoadFile(str);
for (YAML::iterator it = yaml_node.begin(); it != yaml_node.end(); ++it) {
std::string node_name = it->first.as<std::string>();
std::transform(node_name.begin(), node_name.end(), node_name.begin(), ::toupper);
auto environment_name = prefix + node_name;
auto environment_content_ptr = std::getenv(environment_name.data());
if (!environment_content_ptr)
continue;
std::string value{environment_content_ptr};
it->second = YAML::Load(value);
}
return from_yaml<T, false>(YAML::Dump(yaml_node));
}

} // namespace yaml_cpp_struct

namespace YAML {
Expand Down

0 comments on commit fcf16a3

Please sign in to comment.