From ab4c1b8a8b67fd9ffc89c804efa260584530897d Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Sun, 28 Jul 2024 16:23:13 +0200 Subject: Factor out and generalize/extend to_stream_quoted(string) --- libbuild2/utility.cxx | 46 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) (limited to 'libbuild2/utility.cxx') diff --git a/libbuild2/utility.cxx b/libbuild2/utility.cxx index 1135851..ae7c9b0 100644 --- a/libbuild2/utility.cxx +++ b/libbuild2/utility.cxx @@ -16,7 +16,7 @@ #endif #include // ENOENT -#include // strlen(), str[n]cmp() +#include // strlen(), str[n]cmp(), strchr() #include // cerr #include @@ -1011,4 +1011,48 @@ namespace build2 return r; } + + void + to_stream_quoted (ostream& o, const char* s) + { + if (strchr (s, '\'') != nullptr) + { + o << '"'; + + for (; *s != '\0'; ++s) + { + // Escape characters special inside double quotes. + // + if (strchr ("\\\"", *s) != nullptr) + o << '\\'; + + o << *s; + } + + o << '"'; + } + else + o << '\'' << s << '\''; + } + + void + to_stream_quoted (ostream& o, const string& s, const char* special, bool e) + { + if ((e && s.empty ()) || s.find_first_of (special) != string::npos) + to_stream_quoted (o, s); + else + o << s; + } + + void + to_stream_quoted (ostream& o, const strings& ss, const char* special) + { + for (auto b (ss.begin ()), i (b), e (ss.end ()); i != e; ++i) + { + if (i != b) + o << ' '; + + to_stream_quoted (o, *i, special); + } + } } -- cgit v1.1