ClickHouse/dbms/src/Common/Macros.cpp

71 lines
1.6 KiB
C++
Raw Normal View History

2014-08-11 15:59:01 +00:00
#include <DB/Common/Macros.h>
2015-10-05 01:35:28 +00:00
#include <DB/Common/Exception.h>
2014-08-11 15:59:01 +00:00
namespace DB
{
namespace ErrorCodes
{
extern const int SYNTAX_ERROR;
}
2014-08-11 15:59:01 +00:00
Macros::Macros() {}
Macros::Macros(const Poco::Util::AbstractConfiguration & config, const String & root_key)
{
Poco::Util::AbstractConfiguration::Keys keys;
config.keys(root_key, keys);
for (const String & key : keys)
{
macros[key] = config.getString(root_key + "." + key);
}
2014-08-11 15:59:01 +00:00
}
String Macros::expand(const String & s, size_t level) const
2014-08-11 15:59:01 +00:00
{
if (s.find('{') == String::npos)
return s;
2014-08-11 15:59:01 +00:00
if (level && s.size() > 65536)
throw Exception("Too long string while expanding macros", ErrorCodes::SYNTAX_ERROR);
if (level >= 10)
throw Exception("Too deep recursion while expanding macros: '" + s + "'", ErrorCodes::SYNTAX_ERROR);
String res;
size_t pos = 0;
while (true)
{
size_t begin = s.find('{', pos);
2014-08-11 15:59:01 +00:00
if (begin == String::npos)
{
res.append(s, pos, String::npos);
break;
}
else
{
res.append(s, pos, begin - pos);
}
2014-08-11 15:59:01 +00:00
++begin;
size_t end = s.find('}', begin);
if (end == String::npos)
throw Exception("Unbalanced { and } in string with macros: '" + s + "'", ErrorCodes::SYNTAX_ERROR);
2014-08-11 15:59:01 +00:00
String macro_name = s.substr(begin, end - begin);
2014-08-11 15:59:01 +00:00
auto it = macros.find(macro_name);
if (it == macros.end())
throw Exception("No macro " + macro_name + " in config", ErrorCodes::SYNTAX_ERROR);
2014-08-11 15:59:01 +00:00
res += it->second;
2014-08-11 15:59:01 +00:00
pos = end + 1;
}
2014-08-11 15:59:01 +00:00
return expand(res, level + 1);
2014-08-11 15:59:01 +00:00
}
}