From 9cfa0f44a0fabdc647c6b20496e12c467db5c797 Mon Sep 17 00:00:00 2001 From: ncihnegn Date: Sat, 19 Jan 2019 03:25:00 -0800 Subject: [PATCH] Add quotes to values containing spaces (#198) * Add test case for INI output of defaulted options * Add quotes to values with spaces * Fixing formatting * Only fix quote strings, not vectors --- include/CLI/Config.hpp | 7 ++++++- include/CLI/StringTools.hpp | 12 ++++++++++++ tests/IniTest.cpp | 15 +++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/include/CLI/Config.hpp b/include/CLI/Config.hpp index 4a72a619..a48c20e1 100644 --- a/include/CLI/Config.hpp +++ b/include/CLI/Config.hpp @@ -54,7 +54,12 @@ ConfigINI::to_config(const App *app, bool default_also, bool write_description, } out << "; " << detail::fix_newlines("; ", opt->get_description()) << std::endl; } - out << name << "=" << value << std::endl; + + // Don't try to quote anything that is not size 1 + if(opt->get_items_expected() != 1) + out << name << "=" << value << std::endl; + else + out << name << "=" << detail::add_quotes_if_needed(value) << std::endl; } } } diff --git a/include/CLI/StringTools.hpp b/include/CLI/StringTools.hpp index 5fa62352..3f9f2139 100644 --- a/include/CLI/StringTools.hpp +++ b/include/CLI/StringTools.hpp @@ -250,5 +250,17 @@ inline size_t escape_detect(std::string &str, size_t offset) { return offset + 1; } +/// Add quotes if the string contains spaces +inline std::string &add_quotes_if_needed(std::string &str) { + if((str.front() != '"' && str.front() != '\'') || str.front() != str.back()) { + char quote = str.find('"') < str.find('\'') ? '\'' : '"'; + if(str.find(' ') != std::string::npos) { + str.insert(0, 1, quote); + str.append(1, quote); + } + } + return str; +} + } // namespace detail } // namespace CLI diff --git a/tests/IniTest.cpp b/tests/IniTest.cpp index 24d24ba4..87d4414c 100644 --- a/tests/IniTest.cpp +++ b/tests/IniTest.cpp @@ -768,3 +768,18 @@ TEST_F(TApp, IniQuotedOutput) { EXPECT_THAT(str, HasSubstr("val1=\"I am a string\"")); EXPECT_THAT(str, HasSubstr("val2='I am a \"confusing\" string'")); } + +TEST_F(TApp, DefaultsIniQuotedOutput) { + + std::string val1{"I am a string"}; + app.add_option("--val1", val1, "", true); + + std::string val2{R"(I am a "confusing" string)"}; + app.add_option("--val2", val2, "", true); + + run(); + + std::string str = app.config_to_str(true); + EXPECT_THAT(str, HasSubstr("val1=\"I am a string\"")); + EXPECT_THAT(str, HasSubstr("val2='I am a \"confusing\" string'")); +}