Make lint happy
[akkoma] / lib / pleroma / web / gettext.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Gettext do
6 @moduledoc """
7 A module providing Internationalization with a gettext-based API.
8
9 By using [Gettext](https://hexdocs.pm/gettext),
10 your module gains a set of macros for translations, for example:
11
12 import Pleroma.Web.Gettext
13
14 # Simple translation
15 gettext "Here is the string to translate"
16
17 # Plural translation
18 ngettext "Here is the string to translate",
19 "Here are the strings to translate",
20 3
21
22 # Domain-based translation
23 dgettext "errors", "Here is the error message to translate"
24
25 See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
26 """
27 use Gettext, otp_app: :pleroma
28
29 def language_tag do
30 # Naive implementation: HTML lang attribute uses BCP 47, which
31 # uses - as a separator.
32 # https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang
33
34 Gettext.get_locale()
35 |> String.replace("_", "-", global: true)
36 end
37
38 def normalize_locale(locale) do
39 if is_binary(locale) do
40 String.replace(locale, "-", "_")
41 else
42 nil
43 end
44 end
45
46 def supports_locale?(locale) do
47 Pleroma.Web.Gettext
48 |> Gettext.known_locales()
49 |> Enum.member?(locale)
50 end
51
52 def variant?(locale), do: String.contains?(locale, "_")
53
54 def supported_variants_of_locale(locale) do
55 cond do
56 variant?(locale) ->
57 [locale]
58
59 supports_locale?(locale) ->
60 [locale]
61
62 true ->
63 Gettext.known_locales(Pleroma.Web.Gettext)
64 |> Enum.filter(fn l -> String.starts_with?(l, locale <> "_") end)
65 end
66 end
67
68 def locale_or_default(locale) do
69 if supports_locale?(locale) do
70 locale
71 else
72 Gettext.get_locale()
73 end
74 end
75
76 defmacro with_locale_or_default(locale, do: fun) do
77 quote do
78 Gettext.with_locale(Pleroma.Web.Gettext.locale_or_default(unquote(locale)), fn ->
79 unquote(fun)
80 end)
81 end
82 end
83 end