Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 51 additions & 1 deletion src/utils/yaml_node_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,57 @@ std::string mp::utils::emit_yaml(const YAML::Node& node)
{
YAML::Emitter emitter;
emitter.SetIndent(2);
emitter << node;

// Helper function to handle nodes recursively
std::function<void(const YAML::Node&)> emit_node;
emit_node = [&emitter, &emit_node](const YAML::Node& n) {
switch (n.Type())
{
case YAML::NodeType::Map:
{
emitter << YAML::BeginMap;
for (const auto& kv : n)
{
emitter << YAML::Key;
emit_node(kv.first);
emitter << YAML::Value;
emit_node(kv.second);
}
emitter << YAML::EndMap;
break;
}
case YAML::NodeType::Sequence:
{
emitter << YAML::BeginSeq;
for (const auto& v : n)
{
emit_node(v);
}
emitter << YAML::EndSeq;
break;
}
default:
{
// Special handling for strings that look like octal numbers (e.g. "0755")
if (n.IsScalar())
{
const std::string value = n.Scalar();
// If the node is a scalar string that looks like an octal number, emit
// it explicitly as a string to prevent YAML from interpreting it as an octal value.
if (value.length() >= 2 && value[0] == '0' &&
std::all_of(value.begin() + 1, value.end(), ::isdigit))
{
emitter << YAML::LocalTag("str") << value;
break;
}
}
emitter << n;
}
}
};

emit_node(node);

if (!emitter.good())
throw std::runtime_error{fmt::format("Failed to emit YAML: {}", emitter.GetLastError())};

Expand Down
22 changes: 22 additions & 0 deletions tests/test_yaml_node_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,25 @@ cloud-name: multipass)";
EXPECT_EQ(meta_data_node["local-hostname"].as<std::string>(), "vm1");
EXPECT_EQ(meta_data_node["cloud-name"].as<std::string>(), "multipass");
}

TEST(UtilsTests, emitYamlWithOctalString)
{
YAML::Node node;
node["permissions"] = "0755";
node["another_permission"] = "0644";
node["not_octal"] = "0abc";
node["regular_string"] = "hello";

const std::string result = mpu::emit_yaml(node);

// The octal strings should be tagged as strings to preserve their format
EXPECT_TRUE(result.find("permissions: !str \"0755\"") != std::string::npos ||
result.find("permissions: !str 0755") != std::string::npos);
EXPECT_TRUE(result.find("another_permission: !str \"0644\"") != std::string::npos ||
result.find("another_permission: !str 0644") != std::string::npos);
// Non-octal strings should not be tagged
EXPECT_TRUE(result.find("not_octal: 0abc") != std::string::npos ||
result.find("not_octal: \"0abc\"") != std::string::npos);
EXPECT_TRUE(result.find("regular_string: hello") != std::string::npos ||
result.find("regular_string: \"hello\"") != std::string::npos);
}
Loading