3

我有一个类似的 INI 文件

[Section1]
Value1 = /home/%USER%/Desktop
Value2 = /home/%USER%/%SOME_ENV%/Test

并想使用 Boost 解析它。我尝试使用 Boost property_tree 之类的

boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini("config.ini", pt);

std::cout << pt.get<std::string>("Section1.Value1") << std::endl;
std::cout << pt.get<std::string>("Section1.Value2") << std::endl;

但它没有扩展环境变量。输出看起来像

/home/%USER%/Desktop
/home/%USER%/%SOME_ENV%/Test

我期待类似的东西

/home/Maverick/Desktop
/home/Maverick/Doc/Test

我不确定是否可以使用 boost property_tree。

我将不胜感激使用 boost 解析此类文件的任何提示。

4

2 回答 2

2

这是另一种使用旧工艺的方法:

  • 不需要Spirit,或者确实是Boost
  • 不将接口硬连接到std::string(而是允许输入迭代器输出迭代器的任意组合)
  • 将“正确”处理%%为单个% 1

精华:

#include <string>
#include <algorithm>

static std::string safe_getenv(std::string const& macro) {
    auto var = getenv(macro.c_str());
    return var? var : macro;
}

template <typename It, typename Out>
Out expand_env(It f, It l, Out o)
{
    bool in_var = false;
    std::string accum;
    while (f!=l)
    {
        switch(auto ch = *f++)
        {
            case '%':
                if (in_var || (*f!='%'))
                {
                    in_var = !in_var;
                    if (in_var) 
                        accum.clear();
                    else
                    {
                        accum = safe_getenv(accum);
                        o = std::copy(begin(accum), end(accum), o);
                    }
                    break;
                } else 
                    ++f; // %% -> %
            default:
                if (in_var)
                    accum += ch;
                else
                    *o++ = ch;
        }
    }
    return o;
}

#include <iterator>

std::string expand_env(std::string const& input)
{
    std::string result;
    expand_env(begin(input), end(input), std::back_inserter(result));
    return result;
}

#include <iostream>
#include <sstream>
#include <list>

int main()
{
    // same use case as first answer, show `%%` escape
    std::cout << "'" << expand_env("Greeti%%ng is %HOME% world!")  << "'\n";

    // can be done streaming, to any container
    std::istringstream iss("Greeti%%ng is %HOME% world!");
    std::list<char> some_target;

    std::istreambuf_iterator<char> f(iss), l;
    expand_env(f, l, std::back_inserter(some_target));
    std::cout << "Streaming results: '" << std::string(begin(some_target), end(some_target)) << "'\n";

    // some more edge cases uses to validate the algorithm (note `%%` doesn't
    // act as escape if the first ends a 'pending' variable)
    std::cout << "'" << expand_env("")                           << "'\n";
    std::cout << "'" << expand_env("%HOME%")                     << "'\n";
    std::cout << "'" << expand_env(" %HOME%")                    << "'\n";
    std::cout << "'" << expand_env("%HOME% ")                    << "'\n";
    std::cout << "'" << expand_env("%HOME%%HOME%")               << "'\n";
    std::cout << "'" << expand_env(" %HOME%%HOME% ")             << "'\n";
    std::cout << "'" << expand_env(" %HOME% %HOME% ")            << "'\n";
}

在我的盒子上,打印:

'Greeti%ng is /home/sehe world!'
Streaming results: 'Greeti%ng is /home/sehe world!'
''
'/home/sehe'
' /home/sehe'
'/home/sehe '
'/home/sehe/home/sehe'
' /home/sehe/home/sehe '
' /home/sehe /home/sehe '

1当然,“适当地”是主观的。至少,我认为这

  • 会很有用(否则您将如何配置合法包含的值%?)
  • 是 cmd.exe 在 Windows 上的表现
于 2013-06-15T22:43:34.543 回答
1

我很确定这可以使用手写解析器轻松完成(请参阅我的新答案),但我个人是 Spirit 的粉丝:

grammar %= (*~char_("%")) % as_string ["%" >> +~char_("%") >> "%"] 
                                      [ _val += phx::bind(safe_getenv, _1) ];

意义:

  • 取所有非%字符,如果有的话
  • 然后从 s 内部获取任何单词并在附加之前将%其传递safe_getenv

现在,safe_getenv 是一个简单的包装器:

static std::string safe_getenv(std::string const& macro) {
    auto var = getenv(macro.c_str());
    return var? var : macro;
}

这是一个完整的最小实现:

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

static std::string safe_getenv(std::string const& macro) {
    auto var = getenv(macro.c_str());
    return var? var : macro;
}

std::string expand_env(std::string const& input) 
{
    using namespace boost::spirit::qi;
    using boost::phoenix::bind;

    static const rule<std::string::const_iterator, std::string()> compiled =
          *(~char_("%"))                         [ _val+=_1 ] 
        % as_string ["%" >> +~char_("%") >> "%"] [ _val += bind(safe_getenv, _1) ];

    std::string::const_iterator f(input.begin()), l(input.end());
    std::string result;

    parse(f, l, compiled, result);
    return result;
}

int main()
{
    std::cout << expand_env("Greeting is %HOME% world!\n");
}

这打印

Greeting is /home/sehe world!

在我的盒子上

笔记

于 2013-06-15T19:04:26.703 回答