1
1
Fork 0
mirror of https://github.com/NixOS/nix.git synced 2025-11-16 15:32:43 +01:00
nix/src/libutil/xml-writer.cc
Graham Christensen e4f62e4608 Apply clang-format universally.
* It is tough to contribute to a project that doesn't use a formatter,
* It is extra hard to contribute to a project which has configured the formatter, but ignores it for some files
* Code formatting makes it harder to hide obscure / weird bugs by accident or on purpose,

Let's rip the bandaid off?

Note that PRs currently in flight should be able to be merged relatively easily by applying `clang-format` to their tip prior to merge.
2025-07-18 12:47:27 -04:00

96 lines
2.1 KiB
C++

#include <cassert>
#include "nix/util/xml-writer.hh"
namespace nix {
XMLWriter::XMLWriter(bool indent, std::ostream & output)
: output(output)
, indent(indent)
{
output << "<?xml version='1.0' encoding='utf-8'?>" << std::endl;
closed = false;
}
XMLWriter::~XMLWriter()
{
close();
}
void XMLWriter::close()
{
if (closed)
return;
while (!pendingElems.empty())
closeElement();
closed = true;
}
void XMLWriter::indent_(size_t depth)
{
if (!indent)
return;
output << std::string(depth * 2, ' ');
}
void XMLWriter::openElement(std::string_view name, const XMLAttrs & attrs)
{
assert(!closed);
indent_(pendingElems.size());
output << "<" << name;
writeAttrs(attrs);
output << ">";
if (indent)
output << std::endl;
pendingElems.push_back(std::string(name));
}
void XMLWriter::closeElement()
{
assert(!pendingElems.empty());
indent_(pendingElems.size() - 1);
output << "</" << pendingElems.back() << ">";
if (indent)
output << std::endl;
pendingElems.pop_back();
if (pendingElems.empty())
closed = true;
}
void XMLWriter::writeEmptyElement(std::string_view name, const XMLAttrs & attrs)
{
assert(!closed);
indent_(pendingElems.size());
output << "<" << name;
writeAttrs(attrs);
output << " />";
if (indent)
output << std::endl;
}
void XMLWriter::writeAttrs(const XMLAttrs & attrs)
{
for (auto & i : attrs) {
output << " " << i.first << "=\"";
for (size_t j = 0; j < i.second.size(); ++j) {
char c = i.second[j];
if (c == '"')
output << "&quot;";
else if (c == '<')
output << "&lt;";
else if (c == '>')
output << "&gt;";
else if (c == '&')
output << "&amp;";
/* Escape newlines to prevent attribute normalisation (see
XML spec, section 3.3.3. */
else if (c == '\n')
output << "&#xA;";
else
output << c;
}
output << "\"";
}
}
} // namespace nix