From 0e0842330d1ef11f9ac6fa70d9f84bdb16084c45 Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Fri, 18 Oct 2019 15:20:49 +0200 Subject: Add $quote() function for quoting values This can be useful if we want to pass a value on the command line, for example, in a testscript: $* config.cxx=$quote($recall($cxx.path) $cxx.mode, true) --- libbuild2/name.cxx | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) (limited to 'libbuild2/name.cxx') diff --git a/libbuild2/name.cxx b/libbuild2/name.cxx index 4aac32f..84e03db 100644 --- a/libbuild2/name.cxx +++ b/libbuild2/name.cxx @@ -60,9 +60,9 @@ namespace build2 } ostream& - to_stream (ostream& os, const name& n, bool quote, char pair) + to_stream (ostream& os, const name& n, bool quote, char pair, bool escape) { - auto write_string = [quote, pair, &os](const string& v) + auto write_string = [quote, pair, escape, &os](const string& v) { char sc[] = { '{', '}', '[', ']', '$', '(', ')', // Token endings. @@ -78,6 +78,7 @@ namespace build2 // Quote the string with the double quotes rather than with the single // one. Escape some of the special characters. // + if (escape) os << '\\'; os << '"'; for (auto c: v) @@ -88,10 +89,19 @@ namespace build2 os << c; } + if (escape) os << '\\'; os << '"'; } else if (quote && v.find_first_of (sc) != string::npos) - os << "'" << v << "'"; + { + if (escape) os << '\\'; + os << '\''; + + os << v; + + if (escape) os << '\\'; + os << '\''; + } else os << v; }; @@ -115,7 +125,7 @@ namespace build2 // If quoted then print empty name as '' rather than {}. // if (quote && n.empty ()) - return os << "''"; + return os << (escape ? "\\'\\'" : "''"); if (n.proj) { @@ -168,13 +178,17 @@ namespace build2 } ostream& - to_stream (ostream& os, const names_view& ns, bool quote, char pair) + to_stream (ostream& os, + const names_view& ns, + bool quote, + char pair, + bool escape) { for (auto i (ns.begin ()), e (ns.end ()); i != e; ) { const name& n (*i); ++i; - to_stream (os, n, quote, pair); + to_stream (os, n, quote, pair, escape); if (n.pair) os << n.pair; -- cgit v1.1