ConfigReader.cpp 8.37 KB
Newer Older
1
2
3
/**
 * @file
 * @brief Implementation of config reader
Simon Spannagel's avatar
Simon Spannagel committed
4
 * @copyright Copyright (c) 2017 CERN and the Corryvreckan authors.
5
6
 * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
 * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 * Intergovernmental Organization or submit itself to any jurisdiction.
 */

#include "ConfigReader.hpp"

#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <string>
#include <vector>

#include "core/utils/file.h"
#include "core/utils/log.h"
#include "exceptions.h"

using namespace corryvreckan;

ConfigReader::ConfigReader() = default;
ConfigReader::ConfigReader(std::istream& stream, std::string file_name) : ConfigReader() {
    add(stream, std::move(file_name));
}

ConfigReader::ConfigReader(const ConfigReader& other) : conf_array_(other.conf_array_) {
    copy_init_map();
}
ConfigReader& ConfigReader::operator=(const ConfigReader& other) {
    conf_array_ = other.conf_array_;
    copy_init_map();
    return *this;
}

void ConfigReader::copy_init_map() {
    conf_map_.clear();
    for(auto iter = conf_array_.begin(); iter != conf_array_.end(); ++iter) {
        conf_map_[iter->getName()].push_back(iter);
    }
}

/**
46
 * @throws KeyValueParseError If the key / value pair could not be parsed
47
 *
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
 * The key / value pair is split according to the format specifications
 */
std::pair<std::string, std::string> ConfigReader::parseKeyValue(std::string line) {
    line = corryvreckan::trim(line);
    size_t equals_pos = line.find('=');
    if(equals_pos != std::string::npos) {
        std::string key = trim(std::string(line, 0, equals_pos));
        std::string value = trim(std::string(line, equals_pos + 1));
        char last_quote = 0;
        for(size_t i = 0; i < value.size(); ++i) {
            if(value[i] == '\'' || value[i] == '\"') {
                if(last_quote == 0) {
                    last_quote = value[i];
                } else if(last_quote == value[i]) {
                    last_quote = 0;
                }
            }
            if(last_quote == 0 && value[i] == '#') {
                value = std::string(value, 0, i);
                break;
            }
        }

        // Check if key contains only alphanumeric or underscores
        bool valid_key = true;
        for(auto& ch : key) {
            if(isalnum(ch) == 0 && ch != '_' && ch != '.' && ch != ':') {
                valid_key = false;
                break;
            }
        }

        // Check if value is not empty and key is valid
        if(!valid_key) {
            throw KeyValueParseError(line, "key is not valid");
        }
        if(value.empty()) {
            throw KeyValueParseError(line, "value is empty");
        }

        return std::make_pair(key, corryvreckan::trim(value));
    }
    // Key / value pair does not contain equal sign
    throw KeyValueParseError(line, "missing equality sign to split key and value");
}

/**
 * @throws ConfigParseError If an error occurred during the parsing of the stream
 *
 * The configuration is immediately parsed and all of its configurations are available after the functions returns.
98
99
100
101
102
103
 */
void ConfigReader::add(std::istream& stream, std::string file_name) {
    LOG(TRACE) << "Parsing configuration file " << file_name;

    // Convert file name to absolute path (if given)
    if(!file_name.empty()) {
Simon Spannagel's avatar
Simon Spannagel committed
104
        file_name = corryvreckan::get_canonical_path(file_name);
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
    }

    // Build first empty configuration
    std::string section_name;
    Configuration conf(section_name, file_name);

    int line_num = 0;
    while(true) {
        // Process config line by line
        std::string line;
        if(stream.eof()) {
            break;
        }
        std::getline(stream, line);
        ++line_num;

121
122
123
        // Trim whitespaces at beginning and end of line:
        line = corryvreckan::trim(line);

124
125
126
127
        // Ignore empty lines or comments
        if(line.empty() || line.front() == '#') {
            continue;
        }
128

129
        // Check if section header or key-value pair
Simon Spannagel's avatar
Simon Spannagel committed
130
131
132
133
134
135
136
        if(line.front() == '[') {
            // Line should be a section header with an alphanumeric name
            size_t idx = 1;
            for(; idx < line.length() - 1; ++idx) {
                if(isalnum(line[idx]) == 0 && line[idx] != '_') {
                    break;
                }
137
            }
Simon Spannagel's avatar
Simon Spannagel committed
138
139
140
141
142
143
144
            std::string remain = corryvreckan::trim(line.substr(idx + 1));
            if(line[idx] == ']' && (remain.empty() || remain.front() == '#')) {
                // Ignore empty sections if they contain no configurations
                if(!conf.getName().empty() || conf.countSettings() > 0) {
                    // Add previous section
                    addConfiguration(std::move(conf));
                }
145

Simon Spannagel's avatar
Simon Spannagel committed
146
147
148
149
150
151
152
                // Begin new section
                section_name = std::string(line, 1, idx - 1);
                conf = Configuration(section_name, file_name);
            } else {
                // Section header is not valid
                throw ConfigParseError(file_name, line_num);
            }
153
154
155
156
157
158
159
160
161
162
163
        } else if(isalpha(line.front()) != 0) {
            // Line should be a key / value pair with an equal sign
            try {
                // Parse the key value pair
                auto key_value = parseKeyValue(line);

                // Add the config key
                conf.setText(key_value.first, key_value.second);
            } catch(KeyValueParseError& e) {
                // Rethrow key / value parse error as a configuration parse error
                throw ConfigParseError(file_name, line_num);
164
            }
165
166
167
        } else {
            // Line is not a comment, key/value pair or section header
            throw ConfigParseError(file_name, line_num);
168
169
170
        }
    }
    // Add last section
171
    addConfiguration(std::move(conf));
172
173
}

174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
void ConfigReader::addConfiguration(Configuration config) {
    conf_array_.push_back(std::move(config));

    std::string section_name = conf_array_.back().getName();
    std::transform(section_name.begin(), section_name.end(), section_name.begin(), ::tolower);
    conf_map_[section_name].push_back(--conf_array_.end());
}

void ConfigReader::clear() {
    conf_map_.clear();
    conf_array_.clear();
}

bool ConfigReader::hasConfiguration(std::string name) const {
    std::transform(name.begin(), name.end(), name.begin(), ::tolower);
    return conf_map_.find(name) != conf_map_.end();
}

unsigned int ConfigReader::countConfigurations(std::string name) const {
    std::transform(name.begin(), name.end(), name.begin(), ::tolower);
    if(!hasConfiguration(name)) {
        return 0;
    }
    return static_cast<unsigned int>(conf_map_.at(name).size());
}

/**
 * @warning This will have the file path of the first header section
 * @note An empty configuration is returned if no empty section is found
 */
Configuration ConfigReader::getHeaderConfiguration() const {
    // Get empty configurations
    std::vector<Configuration> configurations = getConfigurations("");
    if(configurations.empty()) {
        // Use all configurations to find the file name if no empty
        configurations = getConfigurations();
        std::string file_name;
        if(!configurations.empty()) {
            file_name = configurations.at(0).getFilePath();
        }
        return Configuration("", file_name);
    }

    // Merge all configurations
    Configuration header_config = configurations.at(0);
    for(auto& config : configurations) {
        // NOTE: Merging first configuration again has no effect
        header_config.merge(config);
    }
    return header_config;
}

std::vector<Configuration> ConfigReader::getConfigurations(std::string name) const {
    std::transform(name.begin(), name.end(), name.begin(), ::tolower);
    if(!hasConfiguration(name)) {
        return std::vector<Configuration>();
    }

    std::vector<Configuration> result;
    for(auto& iter : conf_map_.at(name)) {
        result.push_back(*iter);
    }
    return result;
}

std::vector<Configuration> ConfigReader::getConfigurations() const {
    return std::vector<Configuration>(conf_array_.begin(), conf_array_.end());
}
242
243
244
245
246
247
248
249
250
251

void ConfigReader::write(std::ostream& stream) {
    for(auto& conf : conf_array_) {
        stream << "[" << conf.getName() << "]" << std::endl;
        for(auto& key : conf.getAll()) {
            stream << key.first << " = " << key.second << std::endl;
        }
        stream << std::endl;
    }
}