diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -228,6 +228,7 @@ timedata_tests.cpp torcontrol_tests.cpp transaction_tests.cpp + translation_tests.cpp txindex_tests.cpp txpackage_tests.cpp txrequest_tests.cpp diff --git a/src/test/translation_tests.cpp b/src/test/translation_tests.cpp new file mode 100644 --- /dev/null +++ b/src/test/translation_tests.cpp @@ -0,0 +1,20 @@ +// Copyright (c) 2023 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include +#include + +#include + +BOOST_AUTO_TEST_SUITE(translation_tests) + +BOOST_AUTO_TEST_CASE(translation_namedparams) { + bilingual_str arg{"original", "translated"}; + bilingual_str format{"original [%s]", "translated [%s]"}; + bilingual_str result{strprintf(format, arg)}; + BOOST_CHECK_EQUAL(result.original, "original [original]"); + BOOST_CHECK_EQUAL(result.translated, "translated [translated]"); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/src/util/translation.h b/src/util/translation.h --- a/src/util/translation.h +++ b/src/util/translation.h @@ -37,12 +37,25 @@ return {original, original}; } +// Provide an overload of tinyformat::format which can take bilingual_str +// arguments. namespace tinyformat { +// clang-format off template bilingual_str format(const bilingual_str &fmt, const Args &...args) { - return bilingual_str{format(fmt.original, args...), - format(fmt.translated, args...)}; + const auto translate_arg{ + [](const auto &arg, [[maybe_unused]] bool translated) -> const auto & { + if constexpr (std::is_same_v) { + return translated ? arg.translated : arg.original; + } else { + return arg; + } + }}; + return bilingual_str{ + tfm::format(fmt.original, translate_arg(args, false)...), + tfm::format(fmt.translated, translate_arg(args, true)...)}; } +// clang-format on } // namespace tinyformat /** Translate a message to the native language of the user. */ diff --git a/test/lint/lint-format-strings.py b/test/lint/lint-format-strings.py --- a/test/lint/lint-format-strings.py +++ b/test/lint/lint-format-strings.py @@ -27,6 +27,7 @@ "src/util/system.cpp", "strprintf(_(COPYRIGHT_HOLDERS).translated, COPYRIGHT_HOLDERS_SUBSTITUTION)", ), + ("src/test/translation_tests.cpp", "strprintf(format, arg)"), ( "src/validationinterface.cpp", 'LogPrint(BCLog::VALIDATION, fmt "\\n", __VA_ARGS__)',