【问题标题】:How to expand environment variables in .ini files using Boost如何使用 Boost 扩展 .ini 文件中的环境变量
【发布时间】:2013-06-11 08:08:47
【问题描述】:

我有一个类似的 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 解析此类文件,我将不胜感激。

【问题讨论】:

标签: c++ boost ini boost-propertytree


【解决方案1】:

我很确定这可以使用手写解析器轻松完成 (see my newer answer),但我个人是 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!

在我的盒子上

备注

【讨论】:

    【解决方案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 上的表现

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 2012-06-06
      • 2023-03-30
      • 2018-10-18
      • 2011-06-29
      • 1970-01-01
      相关资源
      最近更新 更多