1
0
mirror of https://github.com/CLIUtils/CLI11.git synced 2025-04-30 04:33:53 +00:00
CLI11/include/CLI/Ini.hpp
2017-03-03 12:13:50 -05:00

62 lines
1.6 KiB
C++

#pragma once
// Distributed under the LGPL v2.1 license. See accompanying
// file LICENSE or https://github.com/henryiii/CLI11 for details.
#include <fstream>
#include <string>
#include <iostream>
#include <algorithm>
#include "CLI/StringTools.hpp"
namespace CLI {
namespace detail {
/// Internal parsing function
std::vector<std::string> parse_ini(std::istream &input) {
std::string line;
std::string section = "default";
std::vector<std::string> output;
while(getline(input, line)) {
detail::trim(line);
size_t len = line.length();
if(len > 1 && line[0] == '[' && line[len-1] == ']') {
section = line.substr(1,len-2);
section = detail::to_lower(section);
} else if (len > 0 && line[0] != ';') {
// Find = in string, split and recombine
auto pos = line.find("=");
if(pos != std::string::npos) {
std::string name = detail::trim_copy(line.substr(0,pos));
std::string item = detail::trim_copy(line.substr(pos+1));
trim(item, "\"\'");
line = name + "=" + item;
}
if(section == "default")
output.push_back("--" + line);
else
output.push_back("--" + section + "." + line);
}
}
return output;
}
/// Parse an INI file, throw an error (ParseError:INIParseError or FileError) on failure
std::vector<std::string> parse_ini(const std::string &name) {
std::ifstream input{name};
if(!input.good())
throw FileError(name);
return parse_ini(input);
}
}
}