diff options
author | Rebecca Turner <rbt@sent.as> | 2024-03-28 16:26:42 -0700 |
---|---|---|
committer | jade <lix@jade.fyi> | 2024-04-03 16:25:54 +0000 |
commit | ea10fe7ab0df085b51189adabdb079fc4442c6be (patch) | |
tree | 7183a388ed91b09978fe333b880985ef3c2ed49f /src/libutil/escape-string.cc | |
parent | 56c7dfd65290dea957de6fad4e2df26f1630e407 (diff) |
Add `EscapeStringOptions` and `escapeString` tests
Change-Id: I86ead2f969c9e03c9edfa51bbc92ee06393fd7d6
Diffstat (limited to 'src/libutil/escape-string.cc')
-rw-r--r-- | src/libutil/escape-string.cc | 57 |
1 files changed, 39 insertions, 18 deletions
diff --git a/src/libutil/escape-string.cc b/src/libutil/escape-string.cc index 8160403cd..c3cea96d2 100644 --- a/src/libutil/escape-string.cc +++ b/src/libutil/escape-string.cc @@ -11,30 +11,51 @@ namespace nix { std::ostream & -escapeString(std::ostream & str, const std::string_view string, size_t maxLength, bool ansiColors) +escapeString(std::ostream & output, std::string_view string, EscapeStringOptions options) { size_t charsPrinted = 0; - if (ansiColors) - str << ANSI_MAGENTA; - str << "\""; + if (options.outputAnsiColors) { + output << ANSI_MAGENTA; + } + output << "\""; for (auto i = string.begin(); i != string.end(); ++i) { - if (charsPrinted >= maxLength) { - str << "\" "; - printElided(str, string.length() - charsPrinted, "byte", "bytes", ansiColors); - return str; + if (charsPrinted >= options.maxLength) { + output << "\" "; + printElided( + output, string.length() - charsPrinted, "byte", "bytes", options.outputAnsiColors + ); + return output; + } + + if (*i == '\"' || *i == '\\') { + output << "\\" << *i; + } else if (*i == '\n') { + output << "\\n"; + } else if (*i == '\r') { + output << "\\r"; + } else if (*i == '\t') { + output << "\\t"; + } else if (*i == '$' && *(i + 1) == '{') { + output << "\\" << *i; + } else if (options.escapeNonPrinting && !isprint(*i)) { + output << MaybeHexEscapedChar{*i}; + } else { + output << *i; } - if (*i == '\"' || *i == '\\') str << "\\" << *i; - else if (*i == '\n') str << "\\n"; - else if (*i == '\r') str << "\\r"; - else if (*i == '\t') str << "\\t"; - else if (*i == '$' && *(i+1) == '{') str << "\\" << *i; - else str << *i; charsPrinted++; } - str << "\""; - if (ansiColors) - str << ANSI_NORMAL; - return str; + output << "\""; + if (options.outputAnsiColors) { + output << ANSI_NORMAL; + } + return output; +} + +std::string escapeString(std::string_view s, EscapeStringOptions options) +{ + std::ostringstream output; + escapeString(output, s, options); + return output.str(); } }; // namespace nix |