7 #ifndef XGBOOST_COMMON_CONFIG_H_
8 #define XGBOOST_COMMON_CONFIG_H_
19 #include "xgboost/logging.h"
33 : path_(std::move(path)),
34 line_comment_regex_(
"^#"),
35 key_regex_(R
"rx(^([^#"'=\r\n\t ]+)[\t ]*=)rx"),
36 key_regex_escaped_(R"rx(^(["'])([^"'=\r\n]+)\1[\t ]*=)rx"),
37 value_regex_(R"rx(^([^#"'\r\n\t ]+)[\t ]*(?:#.*){0,1}$)rx"),
38 value_regex_escaped_(R"rx(^(["'])([^"'\r\n]+)\1[\t ]*(?:#.*){0,1}$)rx")
41 std::string LoadConfigFile(const std::string& path) {
42 std::ifstream fin(path, std::ios_base::in | std::ios_base::binary);
43 CHECK(fin) <<
"Failed to open config file: \"" << path <<
"\"";
45 std::string content{std::istreambuf_iterator<char>(fin),
46 std::istreambuf_iterator<char>()};
48 }
catch (std::ios_base::failure
const &e) {
49 LOG(FATAL) <<
"Failed to read config file: \"" << path <<
"\"\n"
64 std::string NormalizeConfigEOL(std::string
const& config_str) {
66 std::stringstream ss(config_str);
67 for (
auto c : config_str) {
69 result.push_back(
'\n');
82 std::vector<std::pair<std::string, std::string>> Parse() {
83 std::string content { LoadConfigFile(path_) };
84 content = NormalizeConfigEOL(content);
85 std::stringstream ss { content };
86 std::vector<std::pair<std::string, std::string>> results;
88 std::string key, value;
90 while (std::getline(ss, line)) {
91 if (ParseKeyValuePair(line, &key, &value)) {
92 results.emplace_back(key, value);
100 const std::regex line_comment_regex_, key_regex_, key_regex_escaped_,
101 value_regex_, value_regex_escaped_;
109 static std::string TrimWhitespace(
const std::string& str) {
110 const auto first_char = str.find_first_not_of(
" \t\n\r");
111 const auto last_char = str.find_last_not_of(
" \t\n\r");
112 if (first_char == std::string::npos) {
116 CHECK_NE(last_char, std::string::npos);
117 const auto substr_len = last_char + 1 - first_char;
118 return str.substr(first_char, substr_len);
128 bool ParseKeyValuePair(
const std::string& str, std::string* key,
129 std::string* value) {
130 std::string buf = TrimWhitespace(str);
137 if (std::regex_search(buf, m, line_comment_regex_)) {
140 }
else if (std::regex_search(buf, m, key_regex_)) {
142 CHECK_EQ(m.size(), 2);
144 }
else if (std::regex_search(buf, m, key_regex_escaped_)) {
147 CHECK_EQ(m.size(), 3);
150 LOG(FATAL) <<
"This line is not a valid key-value pair: " << str;
154 buf = m.suffix().str();
155 buf = TrimWhitespace(buf);
156 if (std::regex_search(buf, m, value_regex_)) {
158 CHECK_EQ(m.size(), 2);
160 }
else if (std::regex_search(buf, m, value_regex_escaped_)) {
163 CHECK_EQ(m.size(), 3);
166 LOG(FATAL) <<
"This line is not a valid key-value pair: " << str;
174 #endif // XGBOOST_COMMON_CONFIG_H_