Skip to content

Commit

Permalink
FIX: parser bug; it should not try to parse commented-out env variables
Browse files Browse the repository at this point in the history
  • Loading branch information
jlblancoc committed Feb 4, 2025
1 parent 3788c30 commit 3b0f87c
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
20 changes: 20 additions & 0 deletions mola_yaml/src/yaml_helpers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,23 @@ std::string mola::yaml_to_string(const mrpt::containers::yaml& cfg)

namespace
{

bool line_pos_is_commented_out(const std::string& text, size_t pos)
{
for (;;)
{
if (text[pos] == '#') return true;
if (!pos || text[pos] == '\n' || text[pos] == '\r') break;
pos--;
}
return false;
}

std::string parseVars(
const std::string& text, const mola::YAMLParseOptions& opts)
{
using namespace std::string_literals;

MRPT_TRY_START

const auto start = text.find("${");
Expand All @@ -111,6 +125,12 @@ std::string parseVars(

const auto [varname, defaultValue] = splitVerticalBar(varnameOrg);

if (line_pos_is_commented_out(text, start))
{
return parseVars(
pre + "$ {"s + varname + "}"s + post.substr(post_end + 1), opts);
}

// 1st try: match to env vars
std::string varvalue;
const char* v = ::getenv(varname.c_str());
Expand Down
43 changes: 40 additions & 3 deletions mola_yaml/tests/test-yaml-parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ b: "foo"
e: '${foo|default1}'
)###";

const std::string txt2 = R"###(# sample yaml
a: 3
f: '${zoo}'
)###";

const std::string txt3 = R"###(# sample yaml
a: 3
b: 3 #f: '${zoo}'
)###";

void test_parseSimple()
{
{
Expand Down Expand Up @@ -86,6 +96,36 @@ void test_parseCustomVars()
ASSERT_(y.isMap());
ASSERT_EQUAL_(y["e"].as<std::string>(), se);
}

// catch undefined variables:
{
bool did_throw = false;
try
{
const auto y =
mola::parse_yaml(mrpt::containers::yaml::FromText(txt2));
}
catch (const std::exception&)
{
did_throw = true;
}
ASSERT_(did_throw);
}

// do not throw if they are commented out:
{
bool did_throw = false;
try
{
const auto y =
mola::parse_yaml(mrpt::containers::yaml::FromText(txt3));
}
catch (const std::exception&)
{
did_throw = true;
}
ASSERT_(!did_throw);
}
}

void test_parseIncludes()
Expand Down Expand Up @@ -130,9 +170,6 @@ void test_parseIncludes()

} // namespace

MRPT_TODO("Possible bug: #$include{} shouldn't be parsed")
MRPT_TODO("bug: #${var} shouldn't be parsed")

int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv)
{
try
Expand Down

0 comments on commit 3b0f87c

Please sign in to comment.