Skip to content

Commit

Permalink
utils::format: Support for user defined locale
Browse files Browse the repository at this point in the history
A new class `utils::Locale` has been created. It contains C and CPP
locale.

A variant of `utils::format` has been created which adds
the `utils::Locale` argument. This allows the user to specify a locale
for formatting.
  • Loading branch information
jrohel committed Feb 4, 2025
1 parent 6935cd6 commit c6331e5
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions include/libdnf5/utils/format_locale.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ along with libdnf. If not, see <https://www.gnu.org/licenses/>.
#define LIBDNF5_UTILS_FORMAT_LOCALE_HPP

#include "bgettext/bgettext-mark-common.h"
#include "locale.hpp"

#include <fmt/format.h>

Expand Down Expand Up @@ -52,6 +53,44 @@ std::string format(bool translate, BgettextMessage format_string, unsigned long
return fmt::vformat(final_format_string, fmt::make_format_args(args...));
}


/// Format `args` according to the `format_string`, and return the result as a string.
///
/// @param locale requested locale for translation and argument formating, nullptr = use global/thread locale
/// @param translate If `true`, it will attempt to translate the message to the requested locale.
/// @param format_string message contains formating string
/// @param plural_form number is used to select the appropriate plural form of the format string
/// @param args arguments to be formated
/// @return A string object holding the formatted result.
template <typename... Args>
std::string format(
const Locale * locale, bool translate, BgettextMessage format_string, unsigned long plural_form, Args &&... args) {
const char * final_format_string{nullptr};

if (!locale) {
return utils::format(translate, format_string, plural_form, args...);
}

if (translate) {
// sets the requested C locale for this thread, needed for bgettext
::locale_t previous_locale = uselocale(locale->get_c_locale());

final_format_string = b_dmgettext(NULL, format_string, plural_form);

// restores the previous C locale for this thread
uselocale(previous_locale);
} else {
if (plural_form > 1) {
final_format_string = b_gettextmsg_get_plural_id(format_string);
}
if (!final_format_string) {
final_format_string = b_gettextmsg_get_id(format_string);
}
}

return fmt::vformat(locale->get_cpp_locale(), final_format_string, fmt::make_format_args(args...));
}

} // namespace libdnf5::utils

#endif // LIBDNF5_UTILS_FORMAT_LOCALE_HPP

0 comments on commit c6331e5

Please sign in to comment.