{-|
Internationalization support for hledger's user-facing output.

Translations live in catalogs in the gettext PO file format, which the
usual translator tools (Poedit, Weblate, Lokalize) understand. Built-in
catalogs are embedded in the executables; a user can override one, or add
a language, with a file in their hledger config directory (see
'translationsOverrideDir'). Lookups are pure functions of a 'Translations'
value, so there is no process-global locale state, and hledger-web can
serve a different language to each request.

Conventions:

- The msgid is the English text. A missing or empty translation falls
  back to it, and 'noTranslations' is the identity, so English output is
  unaffected by this machinery.

- Parameters are @{name}@ placeholders substituted after lookup ('trf'),
  never printf formats: a translation can not crash the program.

- Short words used in more than one sense carry a context ('trc').

- Use 'tr' (or 'trc', 'trf') where text is displayed and a 'Translations'
  value is at hand, usually from the report options. Use 'i18n' (or
  'i18nc') only to mark a literal that is stored earlier, in data such as
  a report spec or a menu item, before any catalog is available; it is
  then translated with 'tr' at display time. Both forms are what the
  catalog extraction tool looks for.

- A malformed catalog is reported as a warning and ignored.

This module is experimental and its API may change.
-}

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell   #-}

module Hledger.Utils.I18n (
  -- * Translations
  Translations(..),
  PluralForms(..),
  noTranslations,
  tr,
  trc,
  trf,
  trn,
  i18n,
  i18nc,
  trTimeLocale,
  translationsForLangOption,
  substitutePlaceholders,
  placeholders,
  -- * Catalogs
  parsePo,
  mergeTranslations,
  builtinTranslations,
  builtinLanguages,
  availableLanguages,
  loadTranslations,
  loadAllTranslations,
  translationsOverrideDir,
  startingCatalog,
  writeStartingCatalog,
  -- * Language tags
  isValidLangTag,
  normalizeLangTag,
  langTagCandidates,
  shortLangTag,
  resolveLang,
  langPrefsFromEnv,
  -- * Plural forms
  parsePluralForms,
  -- * Tests
  tests_I18n,
) where

import Control.Monad (unless, void, when)
import Control.Monad.Combinators.Expr (Operator(..), makeExprParser)
import Data.Bifunctor (first)
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.Char (chr, isAlpha, isAlphaNum, isAscii, isHexDigit, toLower)
import Data.Either (isLeft, rights)
import Data.List (inits, intercalate, partition, sort, sortOn)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as M
import Data.Maybe (fromMaybe, isJust, isNothing, listToMaybe, mapMaybe)
import Data.Set (Set)
import Data.Set qualified as S
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TE
import Data.Text.Encoding.Error (lenientDecode)
import Data.Time.Clock (UTCTime, diffUTCTime, getCurrentTime)
import Data.Time.Format (TimeLocale(..), defaultTimeLocale)
import Data.Void (Void)
import Numeric (readHex, readOct)
import System.Directory (XdgDirectory(..), createDirectoryIfMissing, doesDirectoryExist, getFileSize, getXdgDirectory, listDirectory)
import System.Environment (getEnvironment)
import System.FilePath ((</>), dropExtension, takeExtension)
import Text.Megaparsec
import Text.Megaparsec.Char
import Text.Megaparsec.Char.Lexer qualified as L
import Text.Printf (printf)
import Text.Read (readMaybe)

import Hledger.Utils.Debug (debugLevel, dbg1MsgIO)
import Hledger.Utils.IO (embedFileRelativeBytes, usageError, warnIO)
import Hledger.Utils.Test

-- * Translations

-- | A set of translations for one language, looked up by English text
-- (optionally qualified by a context, see 'trc').
data Translations = Translations
  { Translations -> Text
trLang        :: Text               -- ^ language tag, eg "de", "pt-BR", "zh-Hans"
  , Translations -> Map Text Text
trMessages    :: Map Text Text      -- ^ msgid (or "context\x04msgid") -> translation
  , Translations -> Map Text [Text]
trPlurals     :: Map Text [Text]    -- ^ singular msgid -> one translation per plural form
  , Translations -> Maybe PluralForms
trPluralForms :: Maybe PluralForms  -- ^ this language's plural rule, from the catalog header
  }

-- | A language's plural rule: how many forms it has, and which form a
-- count selects.
data PluralForms = PluralForms
  { PluralForms -> Int
pfCount :: Int
  , PluralForms -> Int -> Int
pfRule  :: Int -> Int
  }

-- | Shows only the language, so that option dumps stay readable.
instance Show Translations where
  show :: Translations -> FilePath
show Translations
t = FilePath
"Translations " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ Text -> FilePath
forall a. Show a => a -> FilePath
show (Translations -> Text
trLang Translations
t)

-- | English: every lookup returns its argument.
noTranslations :: Translations
noTranslations :: Translations
noTranslations = Text
-> Map Text Text
-> Map Text [Text]
-> Maybe PluralForms
-> Translations
Translations Text
"en" Map Text Text
forall k a. Map k a
M.empty Map Text [Text]
forall k a. Map k a
M.empty Maybe PluralForms
forall a. Maybe a
Nothing

-- | Translate this English text, or return it unchanged if there is no translation.
tr :: Translations -> Text -> Text
tr :: Translations -> Text -> Text
tr Translations
t Text
s = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
s (Maybe Text -> Text) -> Maybe Text -> Text
forall a b. (a -> b) -> a -> b
$ Text -> Map Text Text -> Maybe Text
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Text
s (Translations -> Map Text Text
trMessages Translations
t)

-- | Like 'tr', but for a short text that is used in more than one sense.
-- The context (eg "column heading") disambiguates it in the catalog.
trc :: Translations -> Text -> Text -> Text
trc :: Translations -> Text -> Text -> Text
trc Translations
t Text
ctx Text
s = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
s (Maybe Text -> Text) -> Maybe Text -> Text
forall a b. (a -> b) -> a -> b
$ Text -> Map Text Text -> Maybe Text
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup (Maybe Text -> Text -> Text
msgKey (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
ctx) Text
s) (Translations -> Map Text Text
trMessages Translations
t)

-- | Translate this English template, then fill in its @{name}@ placeholders.
-- Placeholders that are not given stay as they are. Values are inserted
-- verbatim, without being scanned for placeholders themselves.
trf :: Translations -> Text -> [(Text, Text)] -> Text
trf :: Translations -> Text -> [(Text, Text)] -> Text
trf Translations
t Text
s [(Text, Text)]
params = [(Text, Text)] -> Text -> Text
substitutePlaceholders [(Text, Text)]
params (Translations -> Text -> Text
tr Translations
t Text
s)

-- | Translate a count phrase, choosing the plural form this language uses
-- for the count, then fill in the @{n}@ placeholder. The two English forms
-- are the msgid and msgid_plural; without a translation, the singular is
-- used for 1 and the plural otherwise.
trn :: Translations -> Int -> Text -> Text -> Text
trn :: Translations -> Int -> Text -> Text -> Text
trn Translations
t Int
n Text
singular Text
plural = [(Text, Text)] -> Text -> Text
substitutePlaceholders [(Text
"n", FilePath -> Text
T.pack (Int -> FilePath
forall a. Show a => a -> FilePath
show Int
n))] Text
form
  where
    form :: Text
form = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
english (Maybe Text -> Text) -> Maybe Text -> Text
forall a b. (a -> b) -> a -> b
$ do
      forms <- Text -> Map Text [Text] -> Maybe [Text]
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Text
singular (Translations -> Map Text [Text]
trPlurals Translations
t)
      let i = (Int -> Int)
-> (PluralForms -> Int -> Int) -> Maybe PluralForms -> Int -> Int
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (\Int
k -> if Int
k Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1 then Int
0 else Int
1) PluralForms -> Int -> Int
pfRule (Translations -> Maybe PluralForms
trPluralForms Translations
t) Int
n
      f <- if i >= 0 && i < length forms then Just (forms !! i) else Nothing
      if T.null f then Nothing else Just f
    english :: Text
english = if Int
n Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1 then Text
singular else Text
plural

-- | Mark an English literal that is stored now, in data such as a report
-- spec or a menu item, and translated later by 'tr' at the point where it
-- is displayed. This is the identity; its purpose is to make the catalog
-- extraction tool collect the literal. (Like gettext's N_.) Where a
-- 'Translations' value is already at hand, use 'tr' directly instead.
i18n :: Text -> Text
i18n :: Text -> Text
i18n = Text -> Text
forall a. a -> a
id

-- | Like 'i18n', for a literal that will be translated with a context by 'trc'.
i18nc :: Text -> Text -> Text
i18nc :: Text -> Text -> Text
i18nc Text
_ctx Text
s = Text
s

-- | The default time locale with month names translated, for formatting
-- dates. The names are looked up with contexts "month" (full name) and
-- "month abbrev" (short name, used as a column heading).
trTimeLocale :: Translations -> TimeLocale
trTimeLocale :: Translations -> TimeLocale
trTimeLocale Translations
t = TimeLocale
defaultTimeLocale{ months = zipWith (\Text
f Text
a -> (Text -> Text -> FilePath
name Text
"month" Text
f, Text -> Text -> FilePath
name Text
"month abbrev" Text
a)) fulls abbrevs }
  where
    name :: Text -> Text -> FilePath
name Text
ctx = Text -> FilePath
T.unpack (Text -> FilePath) -> (Text -> Text) -> Text -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Translations -> Text -> Text -> Text
trc Translations
t Text
ctx
    -- TRANSLATORS: stand-alone (nominative) month names, as used in a column heading.
    fulls :: [Text]
fulls =
      [ Text -> Text -> Text
i18nc Text
"month" Text
"January", Text -> Text -> Text
i18nc Text
"month" Text
"February", Text -> Text -> Text
i18nc Text
"month" Text
"March"
      , Text -> Text -> Text
i18nc Text
"month" Text
"April", Text -> Text -> Text
i18nc Text
"month" Text
"May", Text -> Text -> Text
i18nc Text
"month" Text
"June"
      , Text -> Text -> Text
i18nc Text
"month" Text
"July", Text -> Text -> Text
i18nc Text
"month" Text
"August", Text -> Text -> Text
i18nc Text
"month" Text
"September"
      , Text -> Text -> Text
i18nc Text
"month" Text
"October", Text -> Text -> Text
i18nc Text
"month" Text
"November", Text -> Text -> Text
i18nc Text
"month" Text
"December"
      ]
    -- TRANSLATORS: short stand-alone month names, as used in a column heading.
    abbrevs :: [Text]
abbrevs =
      [ Text -> Text -> Text
i18nc Text
"month abbrev" Text
"Jan", Text -> Text -> Text
i18nc Text
"month abbrev" Text
"Feb", Text -> Text -> Text
i18nc Text
"month abbrev" Text
"Mar"
      , Text -> Text -> Text
i18nc Text
"month abbrev" Text
"Apr", Text -> Text -> Text
i18nc Text
"month abbrev" Text
"May", Text -> Text -> Text
i18nc Text
"month abbrev" Text
"Jun"
      , Text -> Text -> Text
i18nc Text
"month abbrev" Text
"Jul", Text -> Text -> Text
i18nc Text
"month abbrev" Text
"Aug", Text -> Text -> Text
i18nc Text
"month abbrev" Text
"Sep"
      , Text -> Text -> Text
i18nc Text
"month abbrev" Text
"Oct", Text -> Text -> Text
i18nc Text
"month abbrev" Text
"Nov", Text -> Text -> Text
i18nc Text
"month abbrev" Text
"Dec"
      ]

-- | Choose translations according to the value of a --lang option.
-- No option means English, without reading any files. "auto" follows the
-- LANGUAGE, LC_ALL, LC_MESSAGES and LANG environment variables (see
-- 'langPrefsFromEnv'), falling back to English. Anything else is a
-- language tag, which must have a catalog, built-in or in
-- 'translationsOverrideDir'; otherwise a usage error is raised.
translationsForLangOption :: Maybe String -> IO Translations
translationsForLangOption :: Maybe FilePath -> IO Translations
translationsForLangOption Maybe FilePath
Nothing = Translations -> IO Translations
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Translations
noTranslations
translationsForLangOption (Just FilePath
"auto") = do
  available <- IO [Text]
availableLanguages
  prefs <- langPrefsFromEnv <$> getEnvironment
  maybe (return noTranslations) loadTranslations $ resolveLang available prefs
translationsForLangOption (Just FilePath
s)
  | (Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower FilePath
s FilePath -> [FilePath] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [FilePath
"c", FilePath
"posix"] = Translations -> IO Translations
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Translations
noTranslations
  | Bool
otherwise = do
      available <- IO [Text]
availableLanguages
      case resolveLang available [T.pack s] of
        Just Text
lang -> Text -> IO Translations
loadTranslations Text
lang
        Maybe Text
Nothing -> FilePath -> IO Translations
forall a. FilePath -> a
usageError (FilePath -> IO Translations) -> FilePath -> IO Translations
forall a b. (a -> b) -> a -> b
$ FilePath
"--lang: no translations are available for " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ ShowS
forall a. Show a => a -> FilePath
show FilePath
s
                     FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
" (available: " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ Text -> FilePath
T.unpack (Text -> [Text] -> Text
T.intercalate Text
", " ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Text
shortLangTag [Text]
available) FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
")"

-- | Split a template into its literal text and its @{name}@ placeholders.
scanPlaceholders :: Text -> [Either Text Text]
scanPlaceholders :: Text -> [Either Text Text]
scanPlaceholders Text
s = case HasCallStack => Text -> Text -> (Text, Text)
Text -> Text -> (Text, Text)
T.breakOn Text
"{" Text
s of
  (Text
before, Text
rest)
    | Text -> Bool
T.null Text
rest -> [Text -> Either Text Text
forall a b. a -> Either a b
Left Text
before | Bool -> Bool
not (Text -> Bool
T.null Text
before)]
    | Bool
otherwise ->
        let (Text
name, Text
rest') = (Char -> Bool) -> Text -> (Text, Text)
T.break (\Char
c -> Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'}' Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'{' Bool -> Bool -> Bool
|| Bool -> Bool
not (Char -> Bool
isNameChar Char
c)) (Int -> Text -> Text
T.drop Int
1 Text
rest)
        in case Text -> Maybe (Char, Text)
T.uncons Text
rest' of
             Just (Char
'}', Text
remaining) | Bool -> Bool
not (Text -> Bool
T.null Text
name) -> Text -> Either Text Text
forall a b. a -> Either a b
Left Text
before Either Text Text -> [Either Text Text] -> [Either Text Text]
forall a. a -> [a] -> [a]
: Text -> Either Text Text
forall a b. b -> Either a b
Right Text
name Either Text Text -> [Either Text Text] -> [Either Text Text]
forall a. a -> [a] -> [a]
: Text -> [Either Text Text]
scanPlaceholders Text
remaining
             Maybe (Char, Text)
_ -> Text -> Either Text Text
forall a b. a -> Either a b
Left (Text
before Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"{") Either Text Text -> [Either Text Text] -> [Either Text Text]
forall a. a -> [a] -> [a]
: Text -> [Either Text Text]
scanPlaceholders (Int -> Text -> Text
T.drop Int
1 Text
rest)

-- | Replace each @{name}@ in the text with the value given for that name.
-- Names not given are left in place; values are not scanned again.
substitutePlaceholders :: [(Text, Text)] -> Text -> Text
substitutePlaceholders :: [(Text, Text)] -> Text -> Text
substitutePlaceholders [(Text, Text)]
params = [Text] -> Text
T.concat ([Text] -> Text) -> (Text -> [Text]) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Either Text Text -> Text) -> [Either Text Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map ((Text -> Text) -> (Text -> Text) -> Either Text Text -> Text
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either Text -> Text
forall a. a -> a
id Text -> Text
fill) ([Either Text Text] -> [Text])
-> (Text -> [Either Text Text]) -> Text -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Either Text Text]
scanPlaceholders
  where fill :: Text -> Text
fill Text
name = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe (Text
"{" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
name Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"}") (Text -> [(Text, Text)] -> Maybe Text
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Text
name [(Text, Text)]
params)

-- | The placeholder names in a template.
placeholders :: Text -> Set Text
placeholders :: Text -> Set Text
placeholders = [Text] -> Set Text
forall a. Ord a => [a] -> Set a
S.fromList ([Text] -> Set Text) -> (Text -> [Text]) -> Text -> Set Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Either Text Text] -> [Text]
forall a b. [Either a b] -> [b]
rights ([Either Text Text] -> [Text])
-> (Text -> [Either Text Text]) -> Text -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Either Text Text]
scanPlaceholders

isNameChar :: Char -> Bool
isNameChar :: Char -> Bool
isNameChar Char
c = Char -> Bool
isAlphaNum Char
c Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'_'

msgKey :: Maybe Text -> Text -> Text
msgKey :: Maybe Text -> Text -> Text
msgKey Maybe Text
mctx Text
s = Text -> (Text -> Text) -> Maybe Text -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
s (\Text
c -> Text
c Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\x04" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
s) Maybe Text
mctx

-- * Catalogs

-- | The built-in catalogs, embedded at build time.
builtinCatalogSources :: [(Text, ByteString)]
builtinCatalogSources :: [(Text, ByteString)]
builtinCatalogSources =
  [ (Text
"de",      $(embedFileRelativeBytes "locale/de.po"))
  , (Text
"es",      $(embedFileRelativeBytes "locale/es.po"))
  , (Text
"fr",      $(embedFileRelativeBytes "locale/fr.po"))
  , (Text
"ga",      $(embedFileRelativeBytes "locale/ga.po"))
  , (Text
"haw",     $(embedFileRelativeBytes "locale/haw.po"))
  , (Text
"it",      $(embedFileRelativeBytes "locale/it.po"))
  , (Text
"ja",      $(embedFileRelativeBytes "locale/ja.po"))
  , (Text
"pt-BR",   $(embedFileRelativeBytes "locale/pt-BR.po"))
  , (Text
"ru",      $(embedFileRelativeBytes "locale/ru.po"))
  , (Text
"uk",      $(embedFileRelativeBytes "locale/uk.po"))
  , (Text
"zh-Hans", $(embedFileRelativeBytes "locale/zh-Hans.po"))
  ]

-- | The built-in catalogs, parsed. A catalog that fails to parse is
-- omitted; the unit tests ensure that does not happen in a release.
builtinTranslations :: Map Text Translations
builtinTranslations :: Map Text Translations
builtinTranslations = [(Text, Translations)] -> Map Text Translations
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList
  [ (Text
lang, Translations
t)
  | (Text
lang, ByteString
bs) <- [(Text, ByteString)]
builtinCatalogSources
  , Right Text
s <- [ByteString -> Either UnicodeException Text
TE.decodeUtf8' ByteString
bs]
  , Right Translations
t <- [FilePath -> Text -> Text -> Either FilePath Translations
parsePo (FilePath
"built-in catalog " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ Text -> FilePath
T.unpack Text
lang) Text
lang Text
s]
  ]

-- | The languages with a built-in catalog, plus English.
builtinLanguages :: [Text]
builtinLanguages :: [Text]
builtinLanguages = Text
"en" Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: Map Text Translations -> [Text]
forall k a. Map k a -> [k]
M.keys Map Text Translations
builtinTranslations

-- | The directory where a user can put a translation catalog named
-- LANG.po, to override a built-in one or to add a language:
-- the locale subdirectory of hledger's config directory
-- (~/.config/hledger/locale on unix, %APPDATA%\\hledger\\locale on windows).
translationsOverrideDir :: IO FilePath
translationsOverrideDir :: IO FilePath
translationsOverrideDir = (FilePath -> ShowS
</> FilePath
"locale") ShowS -> IO FilePath -> IO FilePath
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> XdgDirectory -> FilePath -> IO FilePath
getXdgDirectory XdgDirectory
XdgConfig FilePath
"hledger"

-- | The template that catalogs are made from, embedded at build time.
catalogTemplate :: ByteString
catalogTemplate :: ByteString
catalogTemplate = $(embedFileRelativeBytes "locale/hledger.pot")

-- | The catalog to start translating a language from, for --write-lang:
-- the language's canonical tag, whether the catalog is a built-in one, and
-- its content. That is the built-in catalog for the language if there is
-- one (found as --lang finds it, so de-AT gives de), otherwise the template,
-- with its header filled in so that hledger can use it straight away.
-- English, or something that is not a language tag, gives an error message.
startingCatalog :: Text -> Either String (Text, Bool, ByteString)
startingCatalog :: Text -> Either FilePath (Text, Bool, ByteString)
startingCatalog Text
raw = case Text -> Maybe Text
normalizeLangTag Text
raw of
  Maybe Text
Nothing -> FilePath -> Either FilePath (Text, Bool, ByteString)
forall a b. a -> Either a b
Left (FilePath -> Either FilePath (Text, Bool, ByteString))
-> FilePath -> Either FilePath (Text, Bool, ByteString)
forall a b. (a -> b) -> a -> b
$ Text -> FilePath
forall a. Show a => a -> FilePath
show Text
raw FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
" is not a language tag; try eg de, fr or pt-BR"
  Just Text
"en" -> FilePath -> Either FilePath (Text, Bool, ByteString)
forall a b. a -> Either a b
Left FilePath
"English is hledger's own language, and has no catalog"
  Just Text
tag -> (Text, Bool, ByteString)
-> Either FilePath (Text, Bool, ByteString)
forall a b. b -> Either a b
Right ((Text, Bool, ByteString)
 -> Either FilePath (Text, Bool, ByteString))
-> (Text, Bool, ByteString)
-> Either FilePath (Text, Bool, ByteString)
forall a b. (a -> b) -> a -> b
$ (Text, Bool, ByteString)
-> Maybe (Text, Bool, ByteString) -> (Text, Bool, ByteString)
forall a. a -> Maybe a -> a
fromMaybe (Text
tag, Bool
False, Text -> ByteString
TE.encodeUtf8 (Text -> ByteString) -> Text -> ByteString
forall a b. (a -> b) -> a -> b
$ Text -> Text
newCatalog Text
tag) (Maybe (Text, Bool, ByteString) -> (Text, Bool, ByteString))
-> Maybe (Text, Bool, ByteString) -> (Text, Bool, ByteString)
forall a b. (a -> b) -> a -> b
$ do
    b <- [Text] -> [Text] -> Maybe Text
resolveLang (((Text, ByteString) -> Text) -> [(Text, ByteString)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text, ByteString) -> Text
forall a b. (a, b) -> a
fst [(Text, ByteString)]
builtinCatalogSources) [Text
tag]
    (\ByteString
c -> (Text
b, Bool
True, ByteString
c)) <$> lookup b builtinCatalogSources
  where
    -- the template, with its header filled in as a translator tool would
    newCatalog :: Text -> Text
newCatalog Text
tag =
        HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
T.replace Text
"# Translation template for hledger.\n"
          (Text
"# hledger's " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
tag Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" translations, made from its translation template.\n"
          Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"# Check the Plural-Forms rule below: see https://hledger.org/TRANSLATING.html\n")
      (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
T.replace Text
"#, fuzzy\nmsgid \"\"\n" Text
"msgid \"\"\n"
      (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
T.replace Text
"\"Language: \\n\"" (Text
"\"Language: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
tag Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\\n\"")
      (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
T.replace Text
"\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"" (Text
"\"Plural-Forms: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text -> Text
pluralFormsFor Text
tag Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\\n\"")
      (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ OnDecodeError -> ByteString -> Text
TE.decodeUtf8With OnDecodeError
lenientDecode ByteString
catalogTemplate

-- | The Plural-Forms rule to start a new catalog with: the language's rule
-- if it is in 'commonPluralForms' (looked up by the whole tag, then by the
-- language alone, so zh-Hant gets zh's), otherwise the most common one.
pluralFormsFor :: Text -> Text
pluralFormsFor :: Text -> Text
pluralFormsFor Text
tag = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
"nplurals=2; plural=(n != 1);" (Maybe Text -> Text) -> Maybe Text -> Text
forall a b. (a -> b) -> a -> b
$
  Text -> [(Text, Text)] -> Maybe Text
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Text
tag [(Text, Text)]
commonPluralForms Maybe Text -> Maybe Text -> Maybe Text
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Text -> [(Text, Text)] -> Maybe Text
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup ((Char -> Bool) -> Text -> Text
T.takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'-') Text
tag) [(Text, Text)]
commonPluralForms

-- | The plural rules of languages whose rule is not the most common one,
-- as given in the GNU gettext manual.
commonPluralForms :: [(Text, Text)]
commonPluralForms :: [(Text, Text)]
commonPluralForms =
     [ (Text
l, Text
"nplurals=1; plural=0;") | Text
l <- [Text
"id", Text
"ja", Text
"ko", Text
"th", Text
"vi", Text
"zh"] ]
  [(Text, Text)] -> [(Text, Text)] -> [(Text, Text)]
forall a. [a] -> [a] -> [a]
++ [ (Text
l, Text
"nplurals=2; plural=(n > 1);") | Text
l <- [Text
"fr", Text
"pt-BR"] ]
  [(Text, Text)] -> [(Text, Text)] -> [(Text, Text)]
forall a. [a] -> [a] -> [a]
++ [ (Text
l, Text
"nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);")
     | Text
l <- [Text
"be", Text
"bs", Text
"hr", Text
"ru", Text
"sr", Text
"uk"] ]
  [(Text, Text)] -> [(Text, Text)] -> [(Text, Text)]
forall a. [a] -> [a] -> [a]
++ [ (Text
l, Text
"nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;") | Text
l <- [Text
"cs", Text
"sk"] ]
  [(Text, Text)] -> [(Text, Text)] -> [(Text, Text)]
forall a. [a] -> [a] -> [a]
++ [ (Text
"pl", Text
"nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);")
     , (Text
"lt", Text
"nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);")
     , (Text
"lv", Text
"nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2);")
     , (Text
"ro", Text
"nplurals=3; plural=(n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);")
     , (Text
"ga", Text
"nplurals=3; plural=(n==1 ? 0 : n==2 ? 1 : 2);")
     , (Text
"sl", Text
"nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);")
     , (Text
"ar", Text
"nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);")
     ]

-- | Write the catalog to start translating a language from (see
-- 'startingCatalog') into 'translationsOverrideDir', where --lang will find
-- it, returning its path, tag and whether it is a built-in catalog.
-- If the user has a catalog for that language already, it is left alone
-- and an error message returned.
writeStartingCatalog :: Text -> IO (Either String (FilePath, Text, Bool))
writeStartingCatalog :: Text -> IO (Either FilePath (FilePath, Text, Bool))
writeStartingCatalog Text
raw = case Text -> Either FilePath (Text, Bool, ByteString)
startingCatalog Text
raw of
  Left FilePath
e -> Either FilePath (FilePath, Text, Bool)
-> IO (Either FilePath (FilePath, Text, Bool))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either FilePath (FilePath, Text, Bool)
 -> IO (Either FilePath (FilePath, Text, Bool)))
-> Either FilePath (FilePath, Text, Bool)
-> IO (Either FilePath (FilePath, Text, Bool))
forall a b. (a -> b) -> a -> b
$ FilePath -> Either FilePath (FilePath, Text, Bool)
forall a b. a -> Either a b
Left FilePath
e
  Right (Text
tag, Bool
builtin, ByteString
content) -> do
    dir <- IO FilePath
translationsOverrideDir
    let path = FilePath
dir FilePath -> ShowS
</> Text -> FilePath
T.unpack Text
tag FilePath -> ShowS
forall a. Semigroup a => a -> a -> a
<> FilePath
".po"
    existing <- lookup tag <$> overrideCatalogFiles
    case existing of
      Just FilePath
f -> Either FilePath (FilePath, Text, Bool)
-> IO (Either FilePath (FilePath, Text, Bool))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either FilePath (FilePath, Text, Bool)
 -> IO (Either FilePath (FilePath, Text, Bool)))
-> Either FilePath (FilePath, Text, Bool)
-> IO (Either FilePath (FilePath, Text, Bool))
forall a b. (a -> b) -> a -> b
$ FilePath -> Either FilePath (FilePath, Text, Bool)
forall a b. a -> Either a b
Left (FilePath -> Either FilePath (FilePath, Text, Bool))
-> FilePath -> Either FilePath (FilePath, Text, Bool)
forall a b. (a -> b) -> a -> b
$ FilePath
f FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
" exists already; to start afresh, move it aside first"
      Maybe FilePath
Nothing -> do
        Bool -> FilePath -> IO ()
createDirectoryIfMissing Bool
True FilePath
dir
        FilePath -> ByteString -> IO ()
BS.writeFile FilePath
path ByteString
content
        Either FilePath (FilePath, Text, Bool)
-> IO (Either FilePath (FilePath, Text, Bool))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either FilePath (FilePath, Text, Bool)
 -> IO (Either FilePath (FilePath, Text, Bool)))
-> Either FilePath (FilePath, Text, Bool)
-> IO (Either FilePath (FilePath, Text, Bool))
forall a b. (a -> b) -> a -> b
$ (FilePath, Text, Bool) -> Either FilePath (FilePath, Text, Bool)
forall a b. b -> Either a b
Right (FilePath
path, Text
tag, Bool
builtin)

-- | The largest user catalog we will read.
maxCatalogSize :: Integer
maxCatalogSize :: Integer
maxCatalogSize = Integer
1024 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
1024

-- | The user's catalog files, by language tag. The tag is taken from the
-- file name and normalized, so DE.po and de.po both serve "de".
overrideCatalogFiles :: IO [(Text, FilePath)]
overrideCatalogFiles :: IO [(Text, FilePath)]
overrideCatalogFiles = do
  dir <- IO FilePath
translationsOverrideDir
  exists <- doesDirectoryExist dir
  files <- if exists then listDirectory dir else return []
  return [ (tag, dir </> f) | f <- sort files, takeExtension f == ".po"
         , Just tag <- [normalizeLangTag (T.pack (dropExtension f))] ]

-- | Read the user's catalog for this language tag, if there is one and it
-- is usable, returning it with its path. Problems are reported as
-- warnings and the catalog ignored; or, for a translation whose
-- placeholders are wrong, just that translation.
readOverrideCatalog :: Text -> IO (Maybe (FilePath, Translations))
readOverrideCatalog :: Text -> IO (Maybe (FilePath, Translations))
readOverrideCatalog Text
lang = do
  files <- IO [(Text, FilePath)]
overrideCatalogFiles
  case lookup lang files of
    Maybe FilePath
Nothing -> Maybe (FilePath, Translations)
-> IO (Maybe (FilePath, Translations))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (FilePath, Translations)
forall a. Maybe a
Nothing
    Just FilePath
f -> do
      size <- FilePath -> IO Integer
getFileSize FilePath
f
      if size > maxCatalogSize
        then Nothing <$ warnIO ("ignoring translation catalog " ++ f ++ ": it is larger than 1 MiB")
        else do
          bs <- BS.readFile f
          case TE.decodeUtf8' bs of
            Left UnicodeException
_ -> Maybe (FilePath, Translations)
forall a. Maybe a
Nothing Maybe (FilePath, Translations)
-> IO () -> IO (Maybe (FilePath, Translations))
forall a b. a -> IO b -> IO a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ FilePath -> IO ()
forall (m :: * -> *). MonadIO m => FilePath -> m ()
warnIO (FilePath
"ignoring translation catalog " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
f FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
": it is not valid UTF-8")
            Right Text
t -> case FilePath -> Text -> Text -> Either FilePath Translations
parsePo FilePath
f Text
lang Text
t of
              Left FilePath
err -> Maybe (FilePath, Translations)
forall a. Maybe a
Nothing Maybe (FilePath, Translations)
-> IO () -> IO (Maybe (FilePath, Translations))
forall a b. a -> IO b -> IO a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ FilePath -> IO ()
forall (m :: * -> *). MonadIO m => FilePath -> m ()
warnIO (FilePath
"ignoring translation catalog " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
f FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
":\n" FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
err)
              Right Translations
c  -> do
                let (Translations
c', [FilePath]
problems) = Translations -> (Translations, [FilePath])
withoutPlaceholderMismatches Translations
c
                Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([FilePath] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [FilePath]
problems) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ FilePath -> IO ()
forall (m :: * -> *). MonadIO m => FilePath -> m ()
warnIO (FilePath -> IO ()) -> FilePath -> IO ()
forall a b. (a -> b) -> a -> b
$
                  FilePath
"translation catalog " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
f FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
": ignoring translations whose {placeholders} differ from the English text's:\n"
                  FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath -> [FilePath] -> FilePath
forall a. [a] -> [[a]] -> [a]
intercalate FilePath
"\n" (ShowS -> [FilePath] -> [FilePath]
forall a b. (a -> b) -> [a] -> [b]
map (FilePath
"  " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++) [FilePath]
problems)
                Maybe (FilePath, Translations)
-> IO (Maybe (FilePath, Translations))
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ((FilePath, Translations) -> Maybe (FilePath, Translations)
forall a. a -> Maybe a
Just (FilePath
f, Translations
c'))

-- | The language tags for which a catalog exists, built-in or in the
-- user's override directory. Always includes "en".
--
-- Listing the built-in languages parses the built-in catalogs (whichever
-- of them parse are the ones available), once per process. With --debug,
-- reports how long that took.
availableLanguages :: IO [Text]
availableLanguages :: IO [Text]
availableLanguages = do
  t0 <- IO UTCTime
getCurrentTime
  let nbuiltin = [Text] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Text]
builtinLanguages Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1
  t1 <- nbuiltin `seq` getCurrentTime
  when (debugLevel >= 1) $
    dbg1MsgIO $ printf "translations: parsed %d built-in catalogs, %.1f ms" nbuiltin (msSince t0 t1)
  overrides <- map fst <$> overrideCatalogFiles
  return $ S.toList $ S.fromList $ builtinLanguages ++ overrides

-- | Load the translations for this language tag (which should be one
-- returned by 'availableLanguages'): the built-in catalog if any, with
-- the user's catalog merged over it if any. With --debug, reports what
-- was loaded, its size, and how long it took.
loadTranslations :: Text -> IO Translations
loadTranslations :: Text -> IO Translations
loadTranslations Text
lang = do
  t0 <- IO UTCTime
getCurrentTime
  let mbuiltin = Text -> Map Text Translations -> Maybe Translations
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Text
lang Map Text Translations
builtinTranslations
      builtin = Translations -> Maybe Translations -> Translations
forall a. a -> Maybe a -> a
fromMaybe Translations
noTranslations{trLang = lang} Maybe Translations
mbuiltin
  moverride <- readOverrideCatalog lang
  let trs = Translations
-> ((FilePath, Translations) -> Translations)
-> Maybe (FilePath, Translations)
-> Translations
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Translations
builtin (Translations -> Translations -> Translations
mergeTranslations Translations
builtin (Translations -> Translations)
-> ((FilePath, Translations) -> Translations)
-> (FilePath, Translations)
-> Translations
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FilePath, Translations) -> Translations
forall a b. (a, b) -> b
snd) Maybe (FilePath, Translations)
moverride
  when (debugLevel >= 1) $ do
    -- Force the merged catalog so that the time is real.
    let entries = Map Text Text -> Int
forall k a. Map k a -> Int
M.size (Translations -> Map Text Text
trMessages Translations
trs) Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Map Text [Text] -> Int
forall k a. Map k a -> Int
M.size (Translations -> Map Text [Text]
trPlurals Translations
trs)
    t1 <- entries `seq` getCurrentTime
    let chars = [Int] -> Int
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ((Text -> Int) -> [Text] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Int
T.length (Map Text Text -> [Text]
forall k a. Map k a -> [k]
M.keys (Translations -> Map Text Text
trMessages Translations
trs) [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ Map Text Text -> [Text]
forall k a. Map k a -> [a]
M.elems (Translations -> Map Text Text
trMessages Translations
trs)))
              Int -> Int -> Int
forall a. Num a => a -> a -> a
+ [Int] -> Int
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ((Text -> Int) -> [Text] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Int
T.length (Map Text [Text] -> [Text]
forall k a. Map k a -> [k]
M.keys (Translations -> Map Text [Text]
trPlurals Translations
trs) [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [[Text]] -> [Text]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat (Map Text [Text] -> [[Text]]
forall k a. Map k a -> [a]
M.elems (Translations -> Map Text [Text]
trPlurals Translations
trs))))
    let sources = [ FilePath
"built-in" | Maybe Translations -> Bool
forall a. Maybe a -> Bool
isJust Maybe Translations
mbuiltin ] [FilePath] -> [FilePath] -> [FilePath]
forall a. [a] -> [a] -> [a]
++ [ FilePath
f | Just (FilePath
f, Translations
_) <- [Maybe (FilePath, Translations)
moverride] ]
    dbg1MsgIO $ printf "translations: loaded %s (%s): %d entries, ~%d KB of text, %.1f ms"
      (T.unpack lang) (if null sources then "no catalog" else intercalate ", " sources) entries (chars `div` 1024) (msSince t0 t1)
  return trs

-- | Milliseconds between two times, for debug output.
msSince :: UTCTime -> UTCTime -> Double
msSince :: UTCTime -> UTCTime -> Double
msSince UTCTime
t0 UTCTime
t1 = NominalDiffTime -> Double
forall a b. (Real a, Fractional b) => a -> b
realToFrac (UTCTime -> UTCTime -> NominalDiffTime
diffUTCTime UTCTime
t1 UTCTime
t0) Double -> Double -> Double
forall a. Num a => a -> a -> a
* Double
1000

-- | Load the translations for every available language.
loadAllTranslations :: IO (Map Text Translations)
loadAllTranslations :: IO (Map Text Translations)
loadAllTranslations = do
  langs <- IO [Text]
availableLanguages
  M.fromList <$> mapM (\Text
l -> (,) Text
l (Translations -> (Text, Translations))
-> IO Translations -> IO (Text, Translations)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text -> IO Translations
loadTranslations Text
l) langs

-- | Merge two catalogs; entries in the second take precedence.
mergeTranslations :: Translations -> Translations -> Translations
mergeTranslations :: Translations -> Translations -> Translations
mergeTranslations Translations
base Translations
override = Translations
  { trLang :: Text
trLang        = Translations -> Text
trLang Translations
override
  , trMessages :: Map Text Text
trMessages    = Map Text Text -> Map Text Text -> Map Text Text
forall k a. Ord k => Map k a -> Map k a -> Map k a
M.union (Translations -> Map Text Text
trMessages Translations
override) (Translations -> Map Text Text
trMessages Translations
base)
  , trPlurals :: Map Text [Text]
trPlurals     = Map Text [Text] -> Map Text [Text] -> Map Text [Text]
forall k a. Ord k => Map k a -> Map k a -> Map k a
M.union (Translations -> Map Text [Text]
trPlurals Translations
override) (Translations -> Map Text [Text]
trPlurals Translations
base)
  , trPluralForms :: Maybe PluralForms
trPluralForms = Translations -> Maybe PluralForms
trPluralForms Translations
override Maybe PluralForms -> Maybe PluralForms -> Maybe PluralForms
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Translations -> Maybe PluralForms
trPluralForms Translations
base
  }

-- | Remove the translations whose placeholders do not match their English
-- text's, since using them would drop filled-in values (like a report's
-- dates) or show a placeholder literally. A translation must have exactly
-- the English text's placeholders; a plural form may have only those and
-- {n}. Also returns a description of each translation removed.
withoutPlaceholderMismatches :: Translations -> (Translations, [String])
withoutPlaceholderMismatches :: Translations -> (Translations, [FilePath])
withoutPlaceholderMismatches Translations
t =
  ( Translations
t{trMessages = okmsgs, trPlurals = okplurals}
  , ((Text, Text) -> FilePath) -> [(Text, Text)] -> [FilePath]
forall a b. (a -> b) -> [a] -> [b]
map (Text, Text) -> FilePath
describe (Map Text Text -> [(Text, Text)]
forall k a. Map k a -> [(k, a)]
M.toList (Map Text Text
badmsgs Map Text Text -> Map Text [Text] -> Map Text Text
forall k a b. Ord k => Map k a -> Map k b -> Map k a
`M.difference` Translations -> Map Text [Text]
trPlurals Translations
t)) [FilePath] -> [FilePath] -> [FilePath]
forall a. [a] -> [a] -> [a]
++ ((Text, [Text]) -> FilePath) -> [(Text, [Text])] -> [FilePath]
forall a b. (a -> b) -> [a] -> [b]
map (Text, [Text]) -> FilePath
describePlural (Map Text [Text] -> [(Text, [Text])]
forall k a. Map k a -> [(k, a)]
M.toList Map Text [Text]
badplurals) )
  where
    (Map Text [Text]
okplurals, Map Text [Text]
badplurals) = (Text -> [Text] -> Bool)
-> Map Text [Text] -> (Map Text [Text], Map Text [Text])
forall k a. (k -> a -> Bool) -> Map k a -> (Map k a, Map k a)
M.partitionWithKey (\Text
k [Text]
vs -> (Text -> Bool) -> [Text] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Text -> Text -> Bool
fitsPlural Text
k) [Text]
vs) (Translations -> Map Text [Text]
trPlurals Translations
t)
    -- A plural entry's first form is also stored as a message; it is judged,
    -- and kept or removed, as part of the plural entry.
    (Map Text Text
okmsgs, Map Text Text
badmsgs) = (Text -> Text -> Bool)
-> Map Text Text -> (Map Text Text, Map Text Text)
forall k a. (k -> a -> Bool) -> Map k a -> (Map k a, Map k a)
M.partitionWithKey Text -> Text -> Bool
okmsg (Translations -> Map Text Text
trMessages Translations
t)
    okmsg :: Text -> Text -> Bool
okmsg Text
k Text
v
      | Text
k Text -> Map Text [Text] -> Bool
forall k a. Ord k => k -> Map k a -> Bool
`M.member` Translations -> Map Text [Text]
trPlurals Translations
t = Text
k Text -> Map Text [Text] -> Bool
forall k a. Ord k => k -> Map k a -> Bool
`M.member` Map Text [Text]
okplurals
      | Bool
otherwise                = Text -> Set Text
placeholders Text
v Set Text -> Set Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text -> Set Text
expected Text
k
    fitsPlural :: Text -> Text -> Bool
fitsPlural Text
k Text
v = Text -> Set Text
placeholders Text
v Set Text -> Set Text -> Bool
forall a. Ord a => Set a -> Set a -> Bool
`S.isSubsetOf` Text -> Set Text -> Set Text
forall a. Ord a => a -> Set a -> Set a
S.insert Text
"n" (Text -> Set Text
expected Text
k)
    expected :: Text -> Set Text
expected = Text -> Set Text
placeholders (Text -> Set Text) -> (Text -> Text) -> Text -> Set Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
keyMsgid
    describe :: (Text, Text) -> FilePath
describe (Text
k, Text
v) =
      Text -> FilePath
forall a. Show a => a -> FilePath
show (Text -> Text
keyMsgid Text
k) FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
": the translation has " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ Set Text -> FilePath
showPlaceholders (Text -> Set Text
placeholders Text
v)
      FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
", but the English text has " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ Set Text -> FilePath
showPlaceholders (Text -> Set Text
expected Text
k)
    describePlural :: (Text, [Text]) -> FilePath
describePlural (Text
k, [Text]
vs) =
      Text -> FilePath
forall a. Show a => a -> FilePath
show (Text -> Text
keyMsgid Text
k) FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
": a plural form has " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ Set Text -> FilePath
showPlaceholders ([Set Text] -> Set Text
forall (f :: * -> *) a. (Foldable f, Ord a) => f (Set a) -> Set a
S.unions [Text -> Set Text
placeholders Text
v | Text
v <- [Text]
vs, Bool -> Bool
not (Text -> Text -> Bool
fitsPlural Text
k Text
v)])
      FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
", but only these are allowed: " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ Set Text -> FilePath
showPlaceholders (Text -> Set Text -> Set Text
forall a. Ord a => a -> Set a -> Set a
S.insert Text
"n" (Text -> Set Text
expected Text
k))
    showPlaceholders :: Set Text -> FilePath
showPlaceholders Set Text
s
      | Set Text -> Bool
forall a. Set a -> Bool
S.null Set Text
s  = FilePath
"none"
      | Bool
otherwise = [FilePath] -> FilePath
unwords [FilePath
"{" FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ Text -> FilePath
T.unpack Text
p FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
"}" | Text
p <- Set Text -> [Text]
forall a. Set a -> [a]
S.toList Set Text
s]

-- | The msgid part of a catalog key, without any context.
keyMsgid :: Text -> Text
keyMsgid :: Text -> Text
keyMsgid = (Char -> Bool) -> Text -> Text
T.takeWhileEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\x04')

-- ** PO parsing

type PoParser = Parsec Void Text

data PoEntry = PoEntry
  { PoEntry -> [Text]
peFlags    :: [Text]
  , PoEntry -> Maybe Text
peCtx      :: Maybe Text
  , PoEntry -> Text
peId       :: Text
  , PoEntry -> Maybe Text
peIdPlural :: Maybe Text
  , PoEntry -> Text
peStr      :: Text
  , PoEntry -> [(Int, Text)]
peStrs     :: [(Int, Text)]
  }

-- | Parse a catalog in PO format. The arguments are a name for error
-- messages, the language tag to record, and the file's content.
--
-- Handles what translator tools produce: the header entry, translator and
-- extracted comments, references, flags, previous-msgid comments,
-- obsolete entries, contexts, plural forms, multi-line strings, C escapes,
-- a byte order mark and CRLF line endings. Entries flagged fuzzy are
-- skipped (except that the header's Plural-Forms is still used), and an
-- empty translation counts as untranslated. Duplicate entries and a
-- non-UTF-8 charset are errors.
parsePo :: String -> Text -> Text -> Either String Translations
parsePo :: FilePath -> Text -> Text -> Either FilePath Translations
parsePo FilePath
name Text
lang Text
input = do
  entries <- (ParseErrorBundle Text Void -> FilePath)
-> Either (ParseErrorBundle Text Void) [PoEntry]
-> Either FilePath [PoEntry]
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first ParseErrorBundle Text Void -> FilePath
forall s e.
(VisualStream s, TraversableStream s, ShowErrorComponent e) =>
ParseErrorBundle s e -> FilePath
errorBundlePretty (Either (ParseErrorBundle Text Void) [PoEntry]
 -> Either FilePath [PoEntry])
-> Either (ParseErrorBundle Text Void) [PoEntry]
-> Either FilePath [PoEntry]
forall a b. (a -> b) -> a -> b
$ Parsec Void Text [PoEntry]
-> FilePath
-> Text
-> Either (ParseErrorBundle Text Void) [PoEntry]
forall e s a.
Parsec e s a -> FilePath -> s -> Either (ParseErrorBundle s e) a
runParser Parsec Void Text [PoEntry]
poEntries FilePath
name (Text -> Text
cleanup Text
input)
  buildTranslations name lang entries
  where
    cleanup :: Text -> Text
cleanup = HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
T.replace Text
"\r\n" Text
"\n" (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char -> Bool) -> Text -> Text
T.dropWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\xFEFF')

poEntries :: PoParser [PoEntry]
poEntries :: Parsec Void Text [PoEntry]
poEntries = do
  ParsecT Void Text Identity ()
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m ()
space
  done <- ParsecT Void Text Identity Bool
forall e s (m :: * -> *). MonadParsec e s m => m Bool
atEnd
  if done
    then return []
    else do
      flagss <- many commentLine
      mentry <- optional entryFields
      case mentry of
        Maybe PoEntry
Nothing
          | [[Text]] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [[Text]]
flagss -> FilePath -> Parsec Void Text [PoEntry]
forall a. HasCallStack => FilePath -> ParsecT Void Text Identity a
forall (m :: * -> *) a.
(MonadFail m, HasCallStack) =>
FilePath -> m a
fail FilePath
"expected a comment line or a msgid"
          | Bool
otherwise   -> Parsec Void Text [PoEntry]
poEntries  -- comments with no entry, eg an obsolete (#~) entry
        Just PoEntry
e -> (PoEntry
e{peFlags = concat flagss} PoEntry -> [PoEntry] -> [PoEntry]
forall a. a -> [a] -> [a]
:) ([PoEntry] -> [PoEntry])
-> Parsec Void Text [PoEntry] -> Parsec Void Text [PoEntry]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Parsec Void Text [PoEntry]
poEntries

-- | A comment line. Returns the flags if it is a "#," flags line.
commentLine :: PoParser [Text]
commentLine :: ParsecT Void Text Identity [Text]
commentLine = do
  _ <- Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'#'
  flags <- (char ',' *> (map T.strip . T.splitOn "," <$> restOfLine)) <|> ([] <$ restOfLine)
  space
  return flags
  where restOfLine :: ParsecT Void Text Identity (Tokens Text)
restOfLine = Maybe FilePath
-> (Token Text -> Bool) -> ParsecT Void Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe FilePath -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe FilePath
forall a. Maybe a
Nothing (Token Text -> Token Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
Token Text
'\n')

entryFields :: PoParser PoEntry
entryFields :: ParsecT Void Text Identity PoEntry
entryFields = do
  ctx <- ParsecT Void Text Identity Text
-> ParsecT Void Text Identity (Maybe Text)
forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional (Text -> ParsecT Void Text Identity ()
keyword Text
"msgctxt" ParsecT Void Text Identity ()
-> ParsecT Void Text Identity Text
-> ParsecT Void Text Identity Text
forall a b.
ParsecT Void Text Identity a
-> ParsecT Void Text Identity b -> ParsecT Void Text Identity b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT Void Text Identity Text
strings)
  mid <- keyword "msgid" *> strings
  mpl <- optional (keyword "msgid_plural" *> strings)
  case mpl of
    Maybe Text
Nothing -> do
      s <- Text -> ParsecT Void Text Identity ()
keyword Text
"msgstr" ParsecT Void Text Identity ()
-> ParsecT Void Text Identity Text
-> ParsecT Void Text Identity Text
forall a b.
ParsecT Void Text Identity a
-> ParsecT Void Text Identity b -> ParsecT Void Text Identity b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT Void Text Identity Text
strings
      return PoEntry{peFlags = [], peCtx = ctx, peId = mid, peIdPlural = Nothing, peStr = s, peStrs = []}
    Just Text
pl -> do
      ss <- ParsecT Void Text Identity (Int, Text)
-> ParsecT Void Text Identity [(Int, Text)]
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
some ParsecT Void Text Identity (Int, Text)
indexedMsgstr
      return PoEntry{peFlags = [], peCtx = ctx, peId = mid, peIdPlural = Just pl, peStr = "", peStrs = ss}

keyword :: Text -> PoParser ()
keyword :: Text -> ParsecT Void Text Identity ()
keyword Text
k = ParsecT Void Text Identity (Tokens Text)
-> ParsecT Void Text Identity ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (ParsecT Void Text Identity (Tokens Text)
 -> ParsecT Void Text Identity ())
-> ParsecT Void Text Identity (Tokens Text)
-> ParsecT Void Text Identity ()
forall a b. (a -> b) -> a -> b
$ ParsecT Void Text Identity (Tokens Text)
-> ParsecT Void Text Identity (Tokens Text)
forall a.
ParsecT Void Text Identity a -> ParsecT Void Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (Tokens Text -> ParsecT Void Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Text
Tokens Text
k ParsecT Void Text Identity (Tokens Text)
-> ParsecT Void Text Identity ()
-> ParsecT Void Text Identity (Tokens Text)
forall a b.
ParsecT Void Text Identity a
-> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT Void Text Identity (Token Text)
-> ParsecT Void Text Identity ()
forall a.
ParsecT Void Text Identity a -> ParsecT Void Text Identity ()
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m ()
notFollowedBy ((Token Text -> Bool) -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy (\Token Text
c -> Char -> Bool
isAlphaNum Char
Token Text
c Bool -> Bool -> Bool
|| Char
Token Text
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'_' Bool -> Bool -> Bool
|| Char
Token Text
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'[')) ParsecT Void Text Identity (Tokens Text)
-> ParsecT Void Text Identity ()
-> ParsecT Void Text Identity (Tokens Text)
forall a b.
ParsecT Void Text Identity a
-> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT Void Text Identity ()
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m ()
hspace)

indexedMsgstr :: PoParser (Int, Text)
indexedMsgstr :: ParsecT Void Text Identity (Int, Text)
indexedMsgstr = do
  _ <- ParsecT Void Text Identity (Tokens Text)
-> ParsecT Void Text Identity (Tokens Text)
forall a.
ParsecT Void Text Identity a -> ParsecT Void Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (Tokens Text -> ParsecT Void Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"msgstr[")
  n <- L.decimal
  _ <- char ']'
  hspace
  s <- strings
  return (n, s)

-- | One or more quoted strings, possibly on several lines, concatenated.
strings :: PoParser Text
strings :: ParsecT Void Text Identity Text
strings = [Text] -> Text
T.concat ([Text] -> Text)
-> ParsecT Void Text Identity [Text]
-> ParsecT Void Text Identity Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT Void Text Identity Text
-> ParsecT Void Text Identity [Text]
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
some (ParsecT Void Text Identity Text
quotedString ParsecT Void Text Identity Text
-> ParsecT Void Text Identity () -> ParsecT Void Text Identity Text
forall a b.
ParsecT Void Text Identity a
-> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT Void Text Identity ()
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m ()
space)

-- Runs of ordinary characters are taken as slices of the input; only
-- escapes are handled a character at a time.
quotedString :: PoParser Text
quotedString :: ParsecT Void Text Identity Text
quotedString = [Text] -> Text
T.concat ([Text] -> Text)
-> ParsecT Void Text Identity [Text]
-> ParsecT Void Text Identity Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'"' ParsecT Void Text Identity Char
-> ParsecT Void Text Identity [Text]
-> ParsecT Void Text Identity [Text]
forall a b.
ParsecT Void Text Identity a
-> ParsecT Void Text Identity b -> ParsecT Void Text Identity b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT Void Text Identity Text
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity [Text]
forall (m :: * -> *) a end. MonadPlus m => m a -> m end -> m [a]
manyTill ParsecT Void Text Identity Text
piece (Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'"'))
  where
    piece :: ParsecT Void Text Identity Text
piece = Maybe FilePath
-> (Token Text -> Bool) -> ParsecT Void Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe FilePath -> (Token s -> Bool) -> m (Tokens s)
takeWhile1P Maybe FilePath
forall a. Maybe a
Nothing (\Token Text
c -> Char
Token Text
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'"' Bool -> Bool -> Bool
&& Char
Token Text
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\\' Bool -> Bool -> Bool
&& Char
Token Text
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n')
        ParsecT Void Text Identity Text
-> ParsecT Void Text Identity Text
-> ParsecT Void Text Identity Text
forall a.
ParsecT Void Text Identity a
-> ParsecT Void Text Identity a -> ParsecT Void Text Identity a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> (Char -> Text
T.singleton (Char -> Text)
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'\\' ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall a b.
ParsecT Void Text Identity a
-> ParsecT Void Text Identity b -> ParsecT Void Text Identity b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT Void Text Identity Char
escape))
    escape :: ParsecT Void Text Identity Char
escape = [ParsecT Void Text Identity Char]
-> ParsecT Void Text Identity Char
forall (f :: * -> *) (m :: * -> *) a.
(Foldable f, Alternative m) =>
f (m a) -> m a
choice
      [ Char
'\n' Char
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall a b.
a -> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'n'
      , Char
'\t' Char
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall a b.
a -> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
't'
      , Char
'\r' Char
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall a b.
a -> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'r'
      , Char
'\\' Char
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall a b.
a -> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'\\'
      , Char
'"'  Char
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall a b.
a -> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'"'
      , Char
'\a' Char
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall a b.
a -> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'a'
      , Char
'\b' Char
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall a b.
a -> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'b'
      , Char
'\f' Char
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall a b.
a -> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'f'
      , Char
'\v' Char
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall a b.
a -> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'v'
      , Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'x' ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall a b.
ParsecT Void Text Identity a
-> ParsecT Void Text Identity b -> ParsecT Void Text Identity b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ((FilePath -> [(Int, FilePath)]) -> Text -> Char
forall {a}.
(Eq a, IsString a) =>
(FilePath -> [(Int, a)]) -> Text -> Char
fromCode FilePath -> [(Int, FilePath)]
forall a. (Eq a, Num a) => ReadS a
readHex (Text -> Char)
-> ParsecT Void Text Identity Text
-> ParsecT Void Text Identity Char
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe FilePath
-> (Token Text -> Bool) -> ParsecT Void Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe FilePath -> (Token s -> Bool) -> m (Tokens s)
takeWhile1P (FilePath -> Maybe FilePath
forall a. a -> Maybe a
Just FilePath
"hex digit") Char -> Bool
Token Text -> Bool
isHexDigit)
      , (FilePath -> [(Int, FilePath)]) -> Text -> Char
forall {a}.
(Eq a, IsString a) =>
(FilePath -> [(Int, a)]) -> Text -> Char
fromCode FilePath -> [(Int, FilePath)]
forall a. (Eq a, Num a) => ReadS a
readOct (Text -> Char) -> (FilePath -> Text) -> FilePath -> Char
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FilePath -> Text
T.pack (FilePath -> Char)
-> ParsecT Void Text Identity FilePath
-> ParsecT Void Text Identity Char
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Int
-> Int
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity FilePath
forall (m :: * -> *) a. MonadPlus m => Int -> Int -> m a -> m [a]
count' Int
1 Int
3 ParsecT Void Text Identity Char
ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
octDigitChar
      , ParsecT Void Text Identity Char
ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *). MonadParsec e s m => m (Token s)
anySingle  -- an unknown escape: keep the character
      ]
    fromCode :: (FilePath -> [(Int, a)]) -> Text -> Char
fromCode FilePath -> [(Int, a)]
reader Text
s = case FilePath -> [(Int, a)]
reader (Text -> FilePath
T.unpack Text
s) of
      [(Int
n, a
"")] | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
0x10FFFF -> Int -> Char
chr Int
n
      [(Int, a)]
_ -> Char
'\xFFFD'

buildTranslations :: String -> Text -> [PoEntry] -> Either String Translations
buildTranslations :: FilePath -> Text -> [PoEntry] -> Either FilePath Translations
buildTranslations FilePath
name Text
lang [PoEntry]
entries = do
  let ([PoEntry]
headers, [PoEntry]
rest) = (PoEntry -> Bool) -> [PoEntry] -> ([PoEntry], [PoEntry])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition PoEntry -> Bool
isHeader [PoEntry]
entries
      headerFields :: [(Text, Text)]
headerFields = [(Text, Text)]
-> (PoEntry -> [(Text, Text)]) -> Maybe PoEntry -> [(Text, Text)]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] (Text -> [(Text, Text)]
parseHeader (Text -> [(Text, Text)])
-> (PoEntry -> Text) -> PoEntry -> [(Text, Text)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PoEntry -> Text
peStr) ([PoEntry] -> Maybe PoEntry
forall a. [a] -> Maybe a
listToMaybe [PoEntry]
headers)
  case Text -> [(Text, Text)] -> Maybe Text
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Text
"content-type" [(Text, Text)]
headerFields Maybe Text -> (Text -> Maybe Text) -> Maybe Text
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Maybe Text
charsetOf of
    Just Text
cs | Text
cs Text -> [Text] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Text
"utf-8", Text
"utf8", Text
"charset"] ->
      FilePath -> Either FilePath ()
forall a b. a -> Either a b
Left (FilePath -> Either FilePath ()) -> FilePath -> Either FilePath ()
forall a b. (a -> b) -> a -> b
$ FilePath
name FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
": unsupported charset " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ Text -> FilePath
T.unpack Text
cs FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
" (translation catalogs must be UTF-8)"
    Maybe Text
_ -> () -> Either FilePath ()
forall a b. b -> Either a b
Right ()
  pf <- case Text -> [(Text, Text)] -> Maybe Text
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Text
"plural-forms" [(Text, Text)]
headerFields of
    Maybe Text
Nothing -> Maybe PluralForms -> Either FilePath (Maybe PluralForms)
forall a b. b -> Either a b
Right Maybe PluralForms
forall a. Maybe a
Nothing
    Just Text
s  -> Either FilePath (Maybe PluralForms)
-> (PluralForms -> Either FilePath (Maybe PluralForms))
-> Maybe PluralForms
-> Either FilePath (Maybe PluralForms)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (FilePath -> Either FilePath (Maybe PluralForms)
forall a b. a -> Either a b
Left (FilePath -> Either FilePath (Maybe PluralForms))
-> FilePath -> Either FilePath (Maybe PluralForms)
forall a b. (a -> b) -> a -> b
$ FilePath
name FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
": could not parse the Plural-Forms header: " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ Text -> FilePath
T.unpack Text
s)
                     (Maybe PluralForms -> Either FilePath (Maybe PluralForms)
forall a b. b -> Either a b
Right (Maybe PluralForms -> Either FilePath (Maybe PluralForms))
-> (PluralForms -> Maybe PluralForms)
-> PluralForms
-> Either FilePath (Maybe PluralForms)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PluralForms -> Maybe PluralForms
forall a. a -> Maybe a
Just) (Text -> Maybe PluralForms
parsePluralForms Text
s)
  let live = (PoEntry -> Bool) -> [PoEntry] -> [PoEntry]
forall a. (a -> Bool) -> [a] -> [a]
filter (Text -> [Text] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
notElem Text
"fuzzy" ([Text] -> Bool) -> (PoEntry -> [Text]) -> PoEntry -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PoEntry -> [Text]
peFlags) [PoEntry]
rest
      dups = Map Text Int -> [Text]
forall k a. Map k a -> [k]
M.keys (Map Text Int -> [Text]) -> Map Text Int -> [Text]
forall a b. (a -> b) -> a -> b
$ (Int -> Bool) -> Map Text Int -> Map Text Int
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1) (Map Text Int -> Map Text Int) -> Map Text Int -> Map Text Int
forall a b. (a -> b) -> a -> b
$ (Int -> Int -> Int) -> [(Text, Int)] -> Map Text Int
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith Int -> Int -> Int
forall a. Num a => a -> a -> a
(+) [ (PoEntry -> Text
entryKey PoEntry
e, Int
1 :: Int) | PoEntry
e <- [PoEntry]
live ]
  unless (null dups) $
    Left $ name ++ ": duplicate entries for: " ++ unwords (map (show . T.replace "\x04" "|") dups)
  let msgs    = [(Text, Text)] -> Map Text Text
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [ (PoEntry -> Text
entryKey PoEntry
e, Text
s) | PoEntry
e <- [PoEntry]
live, let s :: Text
s = PoEntry -> Text
singularStr PoEntry
e, Bool -> Bool
not (Text -> Bool
T.null Text
s) ]
      plurals = [(Text, [Text])] -> Map Text [Text]
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [ (PoEntry -> Text
entryKey PoEntry
e, [Text]
forms) | PoEntry
e <- [PoEntry]
live, Maybe Text -> Bool
forall a. Maybe a -> Bool
isJust (PoEntry -> Maybe Text
peIdPlural PoEntry
e)
                           , let forms :: [Text]
forms = ((Int, Text) -> Text) -> [(Int, Text)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Text) -> Text
forall a b. (a, b) -> b
snd (((Int, Text) -> Int) -> [(Int, Text)] -> [(Int, Text)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Int, Text) -> Int
forall a b. (a, b) -> a
fst (PoEntry -> [(Int, Text)]
peStrs PoEntry
e)), (Text -> Bool) -> [Text] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Bool -> Bool
not (Bool -> Bool) -> (Text -> Bool) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Bool
T.null) [Text]
forms ]
  return Translations{trLang = lang, trMessages = msgs, trPlurals = plurals, trPluralForms = pf}
  where
    isHeader :: PoEntry -> Bool
isHeader PoEntry
e = Text -> Bool
T.null (PoEntry -> Text
peId PoEntry
e) Bool -> Bool -> Bool
&& Maybe Text -> Bool
forall a. Maybe a -> Bool
isNothing (PoEntry -> Maybe Text
peCtx PoEntry
e) Bool -> Bool -> Bool
&& Maybe Text -> Bool
forall a. Maybe a -> Bool
isNothing (PoEntry -> Maybe Text
peIdPlural PoEntry
e)
    entryKey :: PoEntry -> Text
entryKey PoEntry
e = Maybe Text -> Text -> Text
msgKey (PoEntry -> Maybe Text
peCtx PoEntry
e) (PoEntry -> Text
peId PoEntry
e)
    singularStr :: PoEntry -> Text
singularStr PoEntry
e = case PoEntry -> Maybe Text
peIdPlural PoEntry
e of
      Maybe Text
Nothing -> PoEntry -> Text
peStr PoEntry
e
      Just Text
_  -> Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
"" (Int -> [(Int, Text)] -> Maybe Text
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Int
0 (PoEntry -> [(Int, Text)]
peStrs PoEntry
e))
    parseHeader :: Text -> [(Text, Text)]
parseHeader Text
s =
      [ (Text -> Text
T.toLower (Text -> Text
T.strip Text
k), Text -> Text
T.strip (Int -> Text -> Text
T.drop Int
1 Text
v))
      | Text
l <- Text -> [Text]
T.lines Text
s, let (Text
k, Text
v) = HasCallStack => Text -> Text -> (Text, Text)
Text -> Text -> (Text, Text)
T.breakOn Text
":" Text
l, Bool -> Bool
not (Text -> Bool
T.null Text
v) ]
    charsetOf :: Text -> Maybe Text
charsetOf Text
ct = [Text] -> Maybe Text
forall a. [a] -> Maybe a
listToMaybe
      [ Text -> Text
T.strip (Int -> Text -> Text
T.drop Int
8 Text
p) | Text
p <- (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> Text
T.toLower (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
T.strip) (HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
";" Text
ct), Text
"charset=" Text -> Text -> Bool
`T.isPrefixOf` Text
p ]

-- ** Plural forms

-- | Parse a PO header's Plural-Forms value, eg
-- "nplurals=2; plural=(n != 1);". The plural expression is the C
-- expression subset gettext allows: n, integers, parentheses, !, %,
-- comparisons, &&, ||, and ?:.
parsePluralForms :: Text -> Maybe PluralForms
parsePluralForms :: Text -> Maybe PluralForms
parsePluralForms Text
s = do
  let fields :: [(Text, Text)]
fields = [ (Text -> Text
T.strip Text
k, Text -> Text
T.strip (Int -> Text -> Text
T.drop Int
1 Text
v)) | Text
p <- HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
";" Text
s, let (Text
k, Text
v) = HasCallStack => Text -> Text -> (Text, Text)
Text -> Text -> (Text, Text)
T.breakOn Text
"=" Text
p, Bool -> Bool
not (Text -> Bool
T.null Text
v) ]
  n <- Text -> [(Text, Text)] -> Maybe Text
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Text
"nplurals" [(Text, Text)]
fields Maybe Text -> (Text -> Maybe Int) -> Maybe Int
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= FilePath -> Maybe Int
forall a. Read a => FilePath -> Maybe a
readMaybe (FilePath -> Maybe Int) -> (Text -> FilePath) -> Text -> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> FilePath
T.unpack
  e <- lookup "plural" fields
  expr <- parseMaybe (space *> pluralExpr <* eof) e
  return PluralForms{pfCount = n, pfRule = \Int
k -> Int -> PExpr -> Int
evalPlural Int
k PExpr
expr}

data PExpr
  = PN
  | PLit Int
  | PNot PExpr
  | PBin Text PExpr PExpr
  | PCond PExpr PExpr PExpr

evalPlural :: Int -> PExpr -> Int
evalPlural :: Int -> PExpr -> Int
evalPlural Int
n = PExpr -> Int
go
  where
    go :: PExpr -> Int
go PExpr
PN = Int
n
    go (PLit Int
i) = Int
i
    go (PNot PExpr
e) = if PExpr -> Int
go PExpr
e Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 then Int
1 else Int
0
    go (PCond PExpr
c PExpr
a PExpr
b) = if PExpr -> Int
go PExpr
c Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
0 then PExpr -> Int
go PExpr
a else PExpr -> Int
go PExpr
b
    go (PBin Text
op PExpr
a PExpr
b) =
      let x :: Int
x = PExpr -> Int
go PExpr
a
          y :: Int
y = PExpr -> Int
go PExpr
b
      in case Text
op of
        Text
"%"  -> if Int
y Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 then Int
0 else Int
x Int -> Int -> Int
forall a. Integral a => a -> a -> a
`mod` Int
y
        Text
"<"  -> Bool -> Int
forall {a}. Num a => Bool -> a
fromBool (Int
x Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
y)
        Text
"<=" -> Bool -> Int
forall {a}. Num a => Bool -> a
fromBool (Int
x Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
y)
        Text
">"  -> Bool -> Int
forall {a}. Num a => Bool -> a
fromBool (Int
x Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
y)
        Text
">=" -> Bool -> Int
forall {a}. Num a => Bool -> a
fromBool (Int
x Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
y)
        Text
"==" -> Bool -> Int
forall {a}. Num a => Bool -> a
fromBool (Int
x Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
y)
        Text
"!=" -> Bool -> Int
forall {a}. Num a => Bool -> a
fromBool (Int
x Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
y)
        Text
"&&" -> Bool -> Int
forall {a}. Num a => Bool -> a
fromBool (Int
x Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
0 Bool -> Bool -> Bool
&& Int
y Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
0)
        Text
"||" -> Bool -> Int
forall {a}. Num a => Bool -> a
fromBool (Int
x Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
0 Bool -> Bool -> Bool
|| Int
y Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
0)
        Text
_    -> Int
0
    fromBool :: Bool -> a
fromBool Bool
b = if Bool
b then a
1 else a
0

pluralExpr :: PoParser PExpr
pluralExpr :: Parsec Void Text PExpr
pluralExpr = do
  c <- Parsec Void Text PExpr
binaryExpr
  (do _ <- sym "?"
      a <- pluralExpr
      _ <- sym ":"
      b <- pluralExpr
      return (PCond c a b))
    <|> return c
  where
    sym :: Tokens Text -> ParsecT Void Text Identity (Tokens Text)
sym = ParsecT Void Text Identity ()
-> Tokens Text -> ParsecT Void Text Identity (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
m () -> Tokens s -> m (Tokens s)
L.symbol ParsecT Void Text Identity ()
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m ()
space
    binaryExpr :: Parsec Void Text PExpr
binaryExpr = Parsec Void Text PExpr
-> [[Operator (ParsecT Void Text Identity) PExpr]]
-> Parsec Void Text PExpr
forall (m :: * -> *) a.
MonadPlus m =>
m a -> [[Operator m a]] -> m a
makeExprParser Parsec Void Text PExpr
term [[Operator (ParsecT Void Text Identity) PExpr]]
table
    table :: [[Operator (ParsecT Void Text Identity) PExpr]]
table =
      [ [ParsecT Void Text Identity (PExpr -> PExpr)
-> Operator (ParsecT Void Text Identity) PExpr
forall (m :: * -> *) a. m (a -> a) -> Operator m a
Prefix (PExpr -> PExpr
PNot (PExpr -> PExpr)
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity (PExpr -> PExpr)
forall a b.
a -> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ ParsecT Void Text Identity ()
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall e s (m :: * -> *) a. MonadParsec e s m => m () -> m a -> m a
L.lexeme ParsecT Void Text Identity ()
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m ()
space (ParsecT Void Text Identity Char -> ParsecT Void Text Identity Char
forall a.
ParsecT Void Text Identity a -> ParsecT Void Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'!' ParsecT Void Text Identity Char
-> ParsecT Void Text Identity () -> ParsecT Void Text Identity Char
forall a b.
ParsecT Void Text Identity a
-> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT Void Text Identity Char -> ParsecT Void Text Identity ()
forall a.
ParsecT Void Text Identity a -> ParsecT Void Text Identity ()
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m ()
notFollowedBy (Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'='))))]
      , [Text -> Operator (ParsecT Void Text Identity) PExpr
binary Text
"%"]
      , [Text -> Operator (ParsecT Void Text Identity) PExpr
binary Text
"<=", Text -> Operator (ParsecT Void Text Identity) PExpr
binary Text
">=", Text -> Operator (ParsecT Void Text Identity) PExpr
binary Text
"<", Text -> Operator (ParsecT Void Text Identity) PExpr
binary Text
">"]
      , [Text -> Operator (ParsecT Void Text Identity) PExpr
binary Text
"==", Text -> Operator (ParsecT Void Text Identity) PExpr
binary Text
"!="]
      , [Text -> Operator (ParsecT Void Text Identity) PExpr
binary Text
"&&"]
      , [Text -> Operator (ParsecT Void Text Identity) PExpr
binary Text
"||"]
      ]
    binary :: Text -> Operator (ParsecT Void Text Identity) PExpr
binary Text
op = ParsecT Void Text Identity (PExpr -> PExpr -> PExpr)
-> Operator (ParsecT Void Text Identity) PExpr
forall (m :: * -> *) a. m (a -> a -> a) -> Operator m a
InfixL (Text -> PExpr -> PExpr -> PExpr
PBin Text
op (PExpr -> PExpr -> PExpr)
-> ParsecT Void Text Identity (Tokens Text)
-> ParsecT Void Text Identity (PExpr -> PExpr -> PExpr)
forall a b.
a -> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Tokens Text -> ParsecT Void Text Identity (Tokens Text)
sym Text
Tokens Text
op)
    term :: Parsec Void Text PExpr
term = [Parsec Void Text PExpr] -> Parsec Void Text PExpr
forall (f :: * -> *) (m :: * -> *) a.
(Foldable f, Alternative m) =>
f (m a) -> m a
choice
      [ PExpr
PN PExpr -> ParsecT Void Text Identity Char -> Parsec Void Text PExpr
forall a b.
a -> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ ParsecT Void Text Identity ()
-> ParsecT Void Text Identity Char
-> ParsecT Void Text Identity Char
forall e s (m :: * -> *) a. MonadParsec e s m => m () -> m a -> m a
L.lexeme ParsecT Void Text Identity ()
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m ()
space (ParsecT Void Text Identity Char -> ParsecT Void Text Identity Char
forall a.
ParsecT Void Text Identity a -> ParsecT Void Text Identity a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (Token Text -> ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'n' ParsecT Void Text Identity Char
-> ParsecT Void Text Identity () -> ParsecT Void Text Identity Char
forall a b.
ParsecT Void Text Identity a
-> ParsecT Void Text Identity b -> ParsecT Void Text Identity a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT Void Text Identity Char -> ParsecT Void Text Identity ()
forall a.
ParsecT Void Text Identity a -> ParsecT Void Text Identity ()
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m ()
notFollowedBy ParsecT Void Text Identity Char
ParsecT Void Text Identity (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
alphaNumChar))
      , Int -> PExpr
PLit (Int -> PExpr)
-> ParsecT Void Text Identity Int -> Parsec Void Text PExpr
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT Void Text Identity ()
-> ParsecT Void Text Identity Int -> ParsecT Void Text Identity Int
forall e s (m :: * -> *) a. MonadParsec e s m => m () -> m a -> m a
L.lexeme ParsecT Void Text Identity ()
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m ()
space ParsecT Void Text Identity Int
forall e s (m :: * -> *) a.
(MonadParsec e s m, Token s ~ Char, Num a) =>
m a
L.decimal
      , ParsecT Void Text Identity (Tokens Text)
-> ParsecT Void Text Identity (Tokens Text)
-> Parsec Void Text PExpr
-> Parsec Void Text PExpr
forall (m :: * -> *) open close a.
Applicative m =>
m open -> m close -> m a -> m a
between (Tokens Text -> ParsecT Void Text Identity (Tokens Text)
sym Tokens Text
"(") (Tokens Text -> ParsecT Void Text Identity (Tokens Text)
sym Tokens Text
")") Parsec Void Text PExpr
pluralExpr
      ]

-- * Language tags

-- | Is this a well-formed language tag, safe to use in a cookie ? Two or three letters, then optional subtags of one to eight
-- letters or digits, separated by hyphens.
isValidLangTag :: Text -> Bool
isValidLangTag :: Text -> Bool
isValidLangTag Text
t = case HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
"-" Text
t of
  (Text
l : [Text]
subs) -> Text -> Int
T.length Text
l Int -> [Int] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Int
2, Int
3] Bool -> Bool -> Bool
&& (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
isAsciiAlpha Text
l Bool -> Bool -> Bool
&& (Text -> Bool) -> [Text] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Text -> Bool
okSub [Text]
subs Bool -> Bool -> Bool
&& Text -> Int
T.length Text
t Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
35
  [Text]
_ -> Bool
False
  where
    okSub :: Text -> Bool
okSub Text
s = Bool -> Bool
not (Text -> Bool
T.null Text
s) Bool -> Bool -> Bool
&& Text -> Int
T.length Text
s Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
8 Bool -> Bool -> Bool
&& (Char -> Bool) -> Text -> Bool
T.all (\Char
c -> Char -> Bool
isAscii Char
c Bool -> Bool -> Bool
&& Char -> Bool
isAlphaNum Char
c) Text
s
    isAsciiAlpha :: Char -> Bool
isAsciiAlpha Char
c = Char -> Bool
isAscii Char
c Bool -> Bool -> Bool
&& Char -> Bool
isAlpha Char
c

-- | Convert a language tag as found in the environment or an HTTP header
-- to canonical form, or Nothing if it does not name a language.
--
-- Handles POSIX locale names (de_DE.UTF-8\@euro becomes de-DE; C, POSIX
-- and an empty value become Nothing), Accept-Language quality suffixes,
-- and letter case (pt-br becomes pt-BR). Chinese region tags map to the
-- script tags zh-Hans and zh-Hant, and Norwegian's no to nb.
normalizeLangTag :: Text -> Maybe Text
normalizeLangTag :: Text -> Maybe Text
normalizeLangTag Text
raw
  | Text -> Bool
T.null Text
base Bool -> Bool -> Bool
|| Bool
isC = Maybe Text
forall a. Maybe a
Nothing
  | Bool
otherwise = do
      let parts :: [Text]
parts = (Text -> Bool) -> [Text] -> [Text]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Text -> Bool) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Bool
T.null) ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
"-" (Text -> [Text]) -> Text -> [Text]
forall a b. (a -> b) -> a -> b
$ HasCallStack => Text -> Text -> Text -> Text
Text -> Text -> Text -> Text
T.replace Text
"_" Text
"-" Text
base
      tag <- case [Text]
parts of
        (Text
l : [Text]
rest) | Text -> Int
T.length Text
l Int -> [Int] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Int
2, Int
3] Bool -> Bool -> Bool
&& (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
isAlpha Text
l ->
          Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ Text -> [Text] -> Text
T.intercalate Text
"-" (Text -> Text
T.toLower Text
l Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: [Text]
modifierSubtag [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Text
canonSub [Text]
rest)
        [Text]
_ -> Maybe Text
forall a. Maybe a
Nothing
      let tag' = Text -> Text
alias Text
tag
      if isValidLangTag tag' then Just tag' else Nothing
  where
    value :: Text
value = Text -> Text
T.strip (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Text -> Text
T.takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
';') Text
raw
    (Text
base, Text
suffix) = (Char -> Bool) -> Text -> (Text, Text)
T.break (\Char
c -> Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'.' Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'@') Text
value
    modifier :: Text
modifier = Int -> Text -> Text
T.drop Int
1 (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Text -> Text
T.dropWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'@') Text
suffix
    modifierSubtag :: [Text]
modifierSubtag = case Text -> Text
T.toLower Text
modifier of
      Text
"latin"    -> [Text
"Latn"]
      Text
"cyrillic" -> [Text
"Cyrl"]
      Text
_          -> []
    isC :: Bool
isC = Text -> Text
T.toLower Text
base Text -> [Text] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Text
"c", Text
"posix"]
    canonSub :: Text -> Text
canonSub Text
s
      | Text -> Int
T.length Text
s Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
4 Bool -> Bool -> Bool
&& (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
isAlpha Text
s = Text -> Text
T.toTitle Text
s  -- script
      | Text -> Int
T.length Text
s Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
2 Bool -> Bool -> Bool
&& (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
isAlpha Text
s = Text -> Text
T.toUpper Text
s  -- region
      | Bool
otherwise = Text
s
    alias :: Text -> Text
alias Text
t = case Text -> Text
T.toLower Text
t of
      Text
"zh"      -> Text
"zh-Hans"
      Text
"zh-cn"   -> Text
"zh-Hans"
      Text
"zh-sg"   -> Text
"zh-Hans"
      Text
"zh-hans" -> Text
"zh-Hans"
      Text
"zh-tw"   -> Text
"zh-Hant"
      Text
"zh-hk"   -> Text
"zh-Hant"
      Text
"zh-mo"   -> Text
"zh-Hant"
      Text
"zh-hant" -> Text
"zh-Hant"
      Text
"no"      -> Text
"nb"
      Text
"no-no"   -> Text
"nb"
      Text
_         -> Text
t

-- | The tags to try for a language tag, most specific first:
-- the tag itself, then with subtags dropped from the right.
langTagCandidates :: Text -> [Text]
langTagCandidates :: Text -> [Text]
langTagCandidates Text
t = ([Text] -> Text) -> [[Text]] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> [Text] -> Text
T.intercalate Text
"-") ([[Text]] -> [Text]) -> [[Text]] -> [Text]
forall a b. (a -> b) -> a -> b
$ [[Text]] -> [[Text]]
forall a. [a] -> [a]
reverse ([[Text]] -> [[Text]]) -> [[Text]] -> [[Text]]
forall a b. (a -> b) -> a -> b
$ Int -> [[Text]] -> [[Text]]
forall a. Int -> [a] -> [a]
drop Int
1 ([[Text]] -> [[Text]]) -> [[Text]] -> [[Text]]
forall a b. (a -> b) -> a -> b
$ [Text] -> [[Text]]
forall a. [a] -> [[a]]
inits ([Text] -> [[Text]]) -> [Text] -> [[Text]]
forall a b. (a -> b) -> a -> b
$ HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
"-" Text
t

-- | The shortest spelling of a language tag that selects it, for showing to
-- users: the tag with subtags dropped from the right, as far as the result
-- still normalizes to the tag. Eg zh-Hans is shown as zh, since zh means
-- zh-Hans; but pt-BR stays pt-BR, since pt is a different language tag.
shortLangTag :: Text -> Text
shortLangTag :: Text -> Text
shortLangTag Text
t = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
t (Maybe Text -> Text) -> Maybe Text -> Text
forall a b. (a -> b) -> a -> b
$ [Text] -> Maybe Text
forall a. [a] -> Maybe a
listToMaybe
  [ Text
c | Text
c <- [Text] -> [Text]
forall a. [a] -> [a]
reverse (Text -> [Text]
langTagCandidates Text
t), Text -> Maybe Text
normalizeLangTag Text
c Maybe Text -> Maybe Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text -> Maybe Text
forall a. a -> Maybe a
Just Text
t ]

-- | Given the available language tags and a list of preferred tags in
-- order of preference (raw, as from the environment or a browser),
-- choose the first available one. Each preference is tried with its
-- subtags dropped from the right before moving on to the next, so that
-- de-CH followed by en chooses de over en when only de is available.
resolveLang :: [Text] -> [Text] -> Maybe Text
resolveLang :: [Text] -> [Text] -> Maybe Text
resolveLang [Text]
available [Text]
prefs = [Text] -> Maybe Text
forall a. [a] -> Maybe a
listToMaybe
  [ Text
a
  | Text
p <- (Text -> Maybe Text) -> [Text] -> [Text]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe Text -> Maybe Text
normalizeLangTag [Text]
prefs
  , Text
c <- Text -> [Text]
langTagCandidates Text
p
  , Text
a <- [Text]
available
  , Text -> Text
T.toLower Text
a Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text -> Text
T.toLower Text
c
  ]

-- | The languages a user prefers, in order, according to these
-- environment variables, following gettext: the effective locale is
-- LC_ALL, else LC_MESSAGES, else LANG; if that is unset or C/POSIX the
-- result is empty (English) and LANGUAGE is ignored; otherwise the
-- colon-separated LANGUAGE list is consulted first, then the locale.
langPrefsFromEnv :: [(String, String)] -> [Text]
langPrefsFromEnv :: [(FilePath, FilePath)] -> [Text]
langPrefsFromEnv [(FilePath, FilePath)]
env = case Maybe Text
effective of
  Maybe Text
Nothing -> []
  Just Text
loc
    | Maybe Text -> Bool
forall a. Maybe a -> Bool
isNothing (Text -> Maybe Text
normalizeLangTag Text
loc) -> []
    | Bool
otherwise -> (Text -> Maybe Text) -> [Text] -> [Text]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe Text -> Maybe Text
normalizeLangTag ([Text]
languageList [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [Text
loc])
  where
    get :: FilePath -> Maybe Text
get FilePath
k = case FilePath -> [(FilePath, FilePath)] -> Maybe FilePath
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup FilePath
k [(FilePath, FilePath)]
env of
      Just FilePath
v | Bool -> Bool
not (FilePath -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null FilePath
v) -> Text -> Maybe Text
forall a. a -> Maybe a
Just (FilePath -> Text
T.pack FilePath
v)
      Maybe FilePath
_ -> Maybe Text
forall a. Maybe a
Nothing
    effective :: Maybe Text
effective = FilePath -> Maybe Text
get FilePath
"LC_ALL" Maybe Text -> Maybe Text -> Maybe Text
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> FilePath -> Maybe Text
get FilePath
"LC_MESSAGES" Maybe Text -> Maybe Text -> Maybe Text
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> FilePath -> Maybe Text
get FilePath
"LANG"
    languageList :: [Text]
languageList = [Text] -> (Text -> [Text]) -> Maybe Text -> [Text]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] (HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
":") (FilePath -> Maybe Text
get FilePath
"LANGUAGE")

-- * Tests

-- i18n-extract: off

tests_I18n :: TestTree
tests_I18n :: TestTree
tests_I18n = FilePath -> [TestTree] -> TestTree
testGroup FilePath
"I18n" [
   FilePath -> IO () -> TestTree
testCase FilePath
"substitutePlaceholders" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     [(Text, Text)] -> Text -> Text
substitutePlaceholders [(Text
"a", Text
"1")] Text
"x {a} y" Text -> Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text
"x 1 y"
     [(Text, Text)] -> Text -> Text
substitutePlaceholders [(Text
"a", Text
"{b}"), (Text
"b", Text
"2")] Text
"{a}{b}" Text -> Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text
"{b}2"
     [(Text, Text)] -> Text -> Text
substitutePlaceholders [] Text
"{unknown} { }" Text -> Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text
"{unknown} { }"
     [(Text, Text)] -> Text -> Text
substitutePlaceholders [(Text
"a", Text
"1")] Text
"{a}{a}" Text -> Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text
"11"

  ,FilePath -> IO () -> TestTree
testCase FilePath
"placeholders" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     Text -> Set Text
placeholders Text
"a {x} {y_1} {bad name} { {z}" Set Text -> Set Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Text] -> Set Text
forall a. Ord a => [a] -> Set a
S.fromList [Text
"x", Text
"y_1", Text
"z"]
     Text -> Set Text
placeholders Text
"" Set Text -> Set Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Set Text
forall a. Set a
S.empty

  ,FilePath -> IO () -> TestTree
testCase FilePath
"parsePo" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     t <- (FilePath -> IO Translations)
-> (Translations -> IO Translations)
-> Either FilePath Translations
-> IO Translations
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either FilePath -> IO Translations
forall a. HasCallStack => FilePath -> IO a
assertFailure Translations -> IO Translations
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either FilePath Translations -> IO Translations)
-> Either FilePath Translations -> IO Translations
forall a b. (a -> b) -> a -> b
$ FilePath -> Text -> Text -> Either FilePath Translations
parsePo FilePath
"sample" Text
"de" Text
samplePo
     trLang t @?= "de"
     tr t "Balance Sheet" @?= "Bilanz"
     tr t "Untranslated" @?= "Untranslated"
     tr t "Empty" @?= "Empty"
     tr t "Fuzzy" @?= "Fuzzy"
     tr t "Obsolete" @?= "Obsolete"
     trc t "column heading" "Total" @?= "Summe"
     tr t "Total" @?= "Total"
     tr t "Multi" @?= "line one\nline two \"quoted\" \\ \252 A"
     trn t 1 "{n} day" "{n} days" @?= "1 Tag"
     trn t 2 "{n} day" "{n} days" @?= "2 Tage"
     trn t 0 "{n} day" "{n} days" @?= "0 Tage"
     tr t "{n} day" @?= "{n} Tag"
     trf t "Balance changes in {period}:" [("period", "2024")] @?= "Saldo\228nderungen in 2024:"
     maybe (-1) pfCount (trPluralForms t) @?= 2

  ,FilePath -> IO () -> TestTree
testCase FilePath
"parsePo errors" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     let bad :: Text -> IO ()
bad = HasCallStack => FilePath -> Bool -> IO ()
FilePath -> Bool -> IO ()
assertBool FilePath
"expected a parse failure" (Bool -> IO ()) -> (Text -> Bool) -> Text -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Either FilePath Translations -> Bool
forall a b. Either a b -> Bool
isLeft (Either FilePath Translations -> Bool)
-> (Text -> Either FilePath Translations) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FilePath -> Text -> Text -> Either FilePath Translations
parsePo FilePath
"t" Text
"de"
     Text -> IO ()
bad Text
"msgid \"a\"\nmsgstr \"b\"\nmsgid \"a\"\nmsgstr \"c\"\n"
     Text -> IO ()
bad Text
"garbage\n"
     Text -> IO ()
bad Text
"msgid \"a\"\nmsgstr \"b\n"
     Text -> IO ()
bad Text
"msgid \"\"\nmsgstr \"Content-Type: text/plain; charset=ISO-8859-1\\n\"\n"
     Text -> IO ()
bad Text
"msgid \"\"\nmsgstr \"Plural-Forms: nplurals=2; plural=(n +);\\n\"\n"

  ,FilePath -> IO () -> TestTree
testCase FilePath
"parsePo tolerates" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     let ok :: Text -> IO ()
ok = HasCallStack => FilePath -> Bool -> IO ()
FilePath -> Bool -> IO ()
assertBool FilePath
"expected a successful parse" (Bool -> IO ()) -> (Text -> Bool) -> Text -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool -> Bool
not (Bool -> Bool) -> (Text -> Bool) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Either FilePath Translations -> Bool
forall a b. Either a b -> Bool
isLeft (Either FilePath Translations -> Bool)
-> (Text -> Either FilePath Translations) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FilePath -> Text -> Text -> Either FilePath Translations
parsePo FilePath
"t" Text
"de"
     Text -> IO ()
ok Text
""
     Text -> IO ()
ok Text
"# just a comment\n"
     Text -> IO ()
ok Text
"\xFEFFmsgid \"a\"\r\nmsgstr \"b\"\r\n"
     Text -> IO ()
ok Text
"#~ msgid \"old\"\n#~ msgstr \"alt\"\n"
     Text -> IO ()
ok Text
"msgid \"\"\nmsgstr \"Content-Type: text/plain; charset=CHARSET\\n\"\n"

  ,FilePath -> IO () -> TestTree
testCase FilePath
"plural rules" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     let rule :: Text -> Int -> Int
rule Text
s = (Int -> Int)
-> (PluralForms -> Int -> Int) -> Maybe PluralForms -> Int -> Int
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Int -> Int -> Int
forall a b. a -> b -> a
const (-Int
1)) PluralForms -> Int -> Int
pfRule (Text -> Maybe PluralForms
parsePluralForms Text
s)
         en :: Int -> Int
en = Text -> Int -> Int
rule Text
"nplurals=2; plural=(n != 1);"
         fr :: Int -> Int
fr = Text -> Int -> Int
rule Text
"nplurals=2; plural=(n > 1);"
         ru :: Int -> Int
ru = Text -> Int -> Int
rule Text
"nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"
         zh :: Int -> Int
zh = Text -> Int -> Int
rule Text
"nplurals=1; plural=0;"
         ar :: Int -> Int
ar = Text -> Int -> Int
rule Text
"nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);"
         pl :: Int -> Int
pl = Text -> Int -> Int
rule Text
"nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);"
     (Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Int -> Int
en [Int
0, Int
1, Int
2] [Int] -> [Int] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Int
1, Int
0, Int
1]
     (Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Int -> Int
fr [Int
0, Int
1, Int
2] [Int] -> [Int] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Int
0, Int
0, Int
1]
     (Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Int -> Int
ru [Int
1, Int
2, Int
5, Int
11, Int
21, Int
22, Int
25] [Int] -> [Int] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Int
0, Int
1, Int
2, Int
2, Int
0, Int
1, Int
2]
     (Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Int -> Int
zh [Int
0, Int
1, Int
5] [Int] -> [Int] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Int
0, Int
0, Int
0]
     (Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Int -> Int
ar [Int
0, Int
1, Int
2, Int
3, Int
11, Int
100] [Int] -> [Int] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Int
0, Int
1, Int
2, Int
3, Int
4, Int
5]
     (Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map Int -> Int
pl [Int
1, Int
2, Int
5, Int
12, Int
22] [Int] -> [Int] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Int
0, Int
1, Int
2, Int
2, Int
1]
     Int -> (PluralForms -> Int) -> Maybe PluralForms -> Int
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Int
0 PluralForms -> Int
pfCount (Text -> Maybe PluralForms
parsePluralForms Text
"nplurals=6; plural=0;") Int -> Int -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Int
6

  ,FilePath -> IO () -> TestTree
testCase FilePath
"normalizeLangTag" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     Text -> Maybe Text
normalizeLangTag Text
"de_DE.UTF-8@euro" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"de-DE"
     Text -> Maybe Text
normalizeLangTag Text
"de" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"de"
     Text -> Maybe Text
normalizeLangTag Text
"C" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Maybe Text
forall a. Maybe a
Nothing
     Text -> Maybe Text
normalizeLangTag Text
"POSIX" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Maybe Text
forall a. Maybe a
Nothing
     Text -> Maybe Text
normalizeLangTag Text
"C.UTF-8" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Maybe Text
forall a. Maybe a
Nothing
     Text -> Maybe Text
normalizeLangTag Text
"" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Maybe Text
forall a. Maybe a
Nothing
     Text -> Maybe Text
normalizeLangTag Text
"zh_CN" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"zh-Hans"
     Text -> Maybe Text
normalizeLangTag Text
"zh-TW" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"zh-Hant"
     Text -> Maybe Text
normalizeLangTag Text
"zh-hant-tw" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"zh-Hant-TW"
     Text -> Maybe Text
normalizeLangTag Text
"sr_RS@latin" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"sr-Latn-RS"
     Text -> Maybe Text
normalizeLangTag Text
"pt-br" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"pt-BR"
     Text -> Maybe Text
normalizeLangTag Text
"no_NO" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"nb"
     Text -> Maybe Text
normalizeLangTag Text
"en-US;q=0.8" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"en-US"
     Text -> Maybe Text
normalizeLangTag Text
"ast" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"ast"
     Text -> Maybe Text
normalizeLangTag Text
"../x" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Maybe Text
forall a. Maybe a
Nothing
     Text -> Maybe Text
normalizeLangTag Text
"de/../x" Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Maybe Text
forall a. Maybe a
Nothing

  ,FilePath -> IO () -> TestTree
testCase FilePath
"isValidLangTag" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     Text -> Bool
isValidLangTag Text
"de" Bool -> Bool -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Bool
True
     Text -> Bool
isValidLangTag Text
"zh-Hant-TW" Bool -> Bool -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Bool
True
     Text -> Bool
isValidLangTag Text
"d" Bool -> Bool -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Bool
False
     Text -> Bool
isValidLangTag Text
"de-" Bool -> Bool -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Bool
False
     Text -> Bool
isValidLangTag Text
"../de" Bool -> Bool -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Bool
False
     Text -> Bool
isValidLangTag Text
"de.po" Bool -> Bool -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Bool
False

  ,FilePath -> IO () -> TestTree
testCase FilePath
"langTagCandidates" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$
     Text -> [Text]
langTagCandidates Text
"zh-Hant-TW" [Text] -> [Text] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Text
"zh-Hant-TW", Text
"zh-Hant", Text
"zh"]

  ,FilePath -> IO () -> TestTree
testCase FilePath
"shortLangTag" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$
     (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Text
shortLangTag [Text
"de", Text
"zh-Hans", Text
"zh-Hant", Text
"pt-BR", Text
"nb", Text
"sr-Latn-RS"]
       [Text] -> [Text] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Text
"de", Text
"zh", Text
"zh-Hant", Text
"pt-BR", Text
"nb", Text
"sr-Latn-RS"]

  ,FilePath -> IO () -> TestTree
testCase FilePath
"resolveLang" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     [Text] -> [Text] -> Maybe Text
resolveLang [Text
"en", Text
"de"] [Text
"de-CH", Text
"en", Text
"de"] Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"de"
     [Text] -> [Text] -> Maybe Text
resolveLang [Text
"en", Text
"de"] [Text
"fr", Text
"en-GB"] Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"en"
     [Text] -> [Text] -> Maybe Text
resolveLang [Text
"en", Text
"de"] [Text
"fr"] Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Maybe Text
forall a. Maybe a
Nothing
     [Text] -> [Text] -> Maybe Text
resolveLang [Text
"en", Text
"de"] [Text
"../etc"] Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Maybe Text
forall a. Maybe a
Nothing
     [Text] -> [Text] -> Maybe Text
resolveLang [Text
"en", Text
"de"] [Text
"DE"] Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"de"
     [Text] -> [Text] -> Maybe Text
resolveLang [Text
"en", Text
"zh-Hans"] [Text
"zh_CN"] Maybe Text -> Maybe Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"zh-Hans"

  ,FilePath -> IO () -> TestTree
testCase FilePath
"langPrefsFromEnv" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     [(FilePath, FilePath)] -> [Text]
langPrefsFromEnv [(FilePath
"LANG", FilePath
"de_DE.UTF-8")] [Text] -> [Text] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Text
"de-DE"]
     [(FilePath, FilePath)] -> [Text]
langPrefsFromEnv [(FilePath
"LC_ALL", FilePath
"C"), (FilePath
"LANGUAGE", FilePath
"de"), (FilePath
"LANG", FilePath
"de_DE.UTF-8")] [Text] -> [Text] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= []
     [(FilePath, FilePath)] -> [Text]
langPrefsFromEnv [(FilePath
"LANGUAGE", FilePath
"fr:de"), (FilePath
"LANG", FilePath
"en_US.UTF-8")] [Text] -> [Text] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Text
"fr", Text
"de", Text
"en-US"]
     [(FilePath, FilePath)] -> [Text]
langPrefsFromEnv [(FilePath
"LC_MESSAGES", FilePath
"de_AT"), (FilePath
"LANG", FilePath
"C")] [Text] -> [Text] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Text
"de-AT"]
     [(FilePath, FilePath)] -> [Text]
langPrefsFromEnv [(FilePath
"LC_ALL", FilePath
""), (FilePath
"LANG", FilePath
"de")] [Text] -> [Text] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= [Text
"de"]
     [(FilePath, FilePath)] -> [Text]
langPrefsFromEnv [] [Text] -> [Text] -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= []

  ,FilePath -> IO () -> TestTree
testCase FilePath
"withoutPlaceholderMismatches" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     t <- (FilePath -> IO Translations)
-> (Translations -> IO Translations)
-> Either FilePath Translations
-> IO Translations
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either FilePath -> IO Translations
forall a. HasCallStack => FilePath -> IO a
assertFailure Translations -> IO Translations
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either FilePath Translations -> IO Translations)
-> Either FilePath Translations -> IO Translations
forall a b. (a -> b) -> a -> b
$ FilePath -> Text -> Text -> Either FilePath Translations
parsePo FilePath
"t" Text
"de" (Text -> Either FilePath Translations)
-> Text -> Either FilePath Translations
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.unlines
       [ Text
"msgid \"In {account}\"",        Text
"msgstr \"In {account}\""
       , Text
"msgid \"{report} {dates}\"",    Text
"msgstr \"{bogus} {report}\""
       , Text
"msgid \"Totals\"",              Text
"msgstr \"Summen {x}\""
       , Text
"msgid \"{n} day\"", Text
"msgid_plural \"{n} days\"", Text
"msgstr[0] \"{n} Tag\"", Text
"msgstr[1] \"{n} Tage\""
       , Text
"msgid \"one {x}\"", Text
"msgid_plural \"{n} {x}s\"", Text
"msgstr[0] \"ein {y}\"", Text
"msgstr[1] \"{n} {x}\""
       ]
     let (t', problems) = withoutPlaceholderMismatches t
     tr t' "In {account}" @?= "In {account}"
     tr t' "{report} {dates}" @?= "{report} {dates}"
     tr t' "Totals" @?= "Totals"
     trn t' 2 "{n} day" "{n} days" @?= "2 Tage"
     trn t' 2 "one {x}" "{n} {x}s" @?= "2 {x}s"
     tr t' "one {x}" @?= "one {x}"
     problems @?=
       [ "\"Totals\": the translation has {x}, but the English text has none"
       , "\"{report} {dates}\": the translation has {bogus} {report}, but the English text has {dates} {report}"
       , "\"one {x}\": a plural form has {y}, but only these are allowed: {n} {x}"
       ]

  ,FilePath -> IO () -> TestTree
testCase FilePath
"built-in catalogs" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$
     ((Text, ByteString) -> IO ()) -> [(Text, ByteString)] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Text, ByteString) -> IO ()
checkBuiltin [(Text, ByteString)]
builtinCatalogSources

  ,FilePath -> IO () -> TestTree
testCase FilePath
"startingCatalog" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     let tagOf :: Text -> Either FilePath (Text, Bool)
tagOf = ((Text, Bool, ByteString) -> (Text, Bool))
-> Either FilePath (Text, Bool, ByteString)
-> Either FilePath (Text, Bool)
forall a b. (a -> b) -> Either FilePath a -> Either FilePath b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\(Text
t, Bool
b, ByteString
_) -> (Text
t, Bool
b)) (Either FilePath (Text, Bool, ByteString)
 -> Either FilePath (Text, Bool))
-> (Text -> Either FilePath (Text, Bool, ByteString))
-> Text
-> Either FilePath (Text, Bool)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Either FilePath (Text, Bool, ByteString)
startingCatalog
     Text -> Either FilePath (Text, Bool)
tagOf Text
"de-AT" Either FilePath (Text, Bool)
-> Either FilePath (Text, Bool) -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= (Text, Bool) -> Either FilePath (Text, Bool)
forall a b. b -> Either a b
Right (Text
"de", Bool
True)
     Text -> Either FilePath (Text, Bool)
tagOf Text
"eo_XX" Either FilePath (Text, Bool)
-> Either FilePath (Text, Bool) -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= (Text, Bool) -> Either FilePath (Text, Bool)
forall a b. b -> Either a b
Right (Text
"eo-XX", Bool
False)
     HasCallStack => FilePath -> Bool -> IO ()
FilePath -> Bool -> IO ()
assertBool FilePath
"en" (Bool -> IO ()) -> Bool -> IO ()
forall a b. (a -> b) -> a -> b
$ Either FilePath (Text, Bool, ByteString) -> Bool
forall a b. Either a b -> Bool
isLeft (Either FilePath (Text, Bool, ByteString) -> Bool)
-> Either FilePath (Text, Bool, ByteString) -> Bool
forall a b. (a -> b) -> a -> b
$ Text -> Either FilePath (Text, Bool, ByteString)
startingCatalog Text
"en"
     HasCallStack => FilePath -> Bool -> IO ()
FilePath -> Bool -> IO ()
assertBool FilePath
"not a tag" (Bool -> IO ()) -> Bool -> IO ()
forall a b. (a -> b) -> a -> b
$ Either FilePath (Text, Bool, ByteString) -> Bool
forall a b. Either a b -> Bool
isLeft (Either FilePath (Text, Bool, ByteString) -> Bool)
-> Either FilePath (Text, Bool, ByteString) -> Bool
forall a b. (a -> b) -> a -> b
$ Text -> Either FilePath (Text, Bool, ByteString)
startingCatalog Text
"x"
     -- a new language's catalog, made from the template, is usable as it is
     case Text -> Either FilePath (Text, Bool, ByteString)
startingCatalog Text
"eo" of
       Right (Text
_, Bool
_, ByteString
bs) -> do
         t <- (FilePath -> IO Translations)
-> (Translations -> IO Translations)
-> Either FilePath Translations
-> IO Translations
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either FilePath -> IO Translations
forall a. HasCallStack => FilePath -> IO a
assertFailure Translations -> IO Translations
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either FilePath Translations -> IO Translations)
-> Either FilePath Translations -> IO Translations
forall a b. (a -> b) -> a -> b
$ FilePath -> Text -> Text -> Either FilePath Translations
parsePo FilePath
"eo" Text
"eo" (Text -> Either FilePath Translations)
-> Text -> Either FilePath Translations
forall a b. (a -> b) -> a -> b
$ OnDecodeError -> ByteString -> Text
TE.decodeUtf8With OnDecodeError
lenientDecode ByteString
bs
         assertBool "plural rule" $ isJust $ trPluralForms t
       Left FilePath
e -> FilePath -> IO ()
forall a. HasCallStack => FilePath -> IO a
assertFailure FilePath
e
     -- with the language's plural rule, if known
     case Text -> Either FilePath (Text, Bool, ByteString)
startingCatalog Text
"uk-UA" of
       Right (Text
_, Bool
_, ByteString
bs) -> (Translations -> Maybe Int)
-> Either FilePath Translations -> Either FilePath (Maybe Int)
forall a b. (a -> b) -> Either FilePath a -> Either FilePath b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((PluralForms -> Int) -> Maybe PluralForms -> Maybe Int
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap PluralForms -> Int
pfCount (Maybe PluralForms -> Maybe Int)
-> (Translations -> Maybe PluralForms) -> Translations -> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Translations -> Maybe PluralForms
trPluralForms) (FilePath -> Text -> Text -> Either FilePath Translations
parsePo FilePath
"t" Text
"uk-UA" (Text -> Either FilePath Translations)
-> Text -> Either FilePath Translations
forall a b. (a -> b) -> a -> b
$ OnDecodeError -> ByteString -> Text
TE.decodeUtf8With OnDecodeError
lenientDecode ByteString
bs) Either FilePath (Maybe Int) -> Either FilePath (Maybe Int) -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Maybe Int -> Either FilePath (Maybe Int)
forall a b. b -> Either a b
Right (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
3)
       Left FilePath
e -> FilePath -> IO ()
forall a. HasCallStack => FilePath -> IO a
assertFailure FilePath
e
     Text -> Text
pluralFormsFor Text
"zh-Hant" Text -> Text -> IO ()
forall a. (Eq a, Show a, HasCallStack) => a -> a -> IO ()
@?= Text -> Text
pluralFormsFor Text
"ja"
     HasCallStack => FilePath -> Bool -> IO ()
FilePath -> Bool -> IO ()
assertBool FilePath
"pt-BR differs from pt" (Bool -> IO ()) -> Bool -> IO ()
forall a b. (a -> b) -> a -> b
$ Text -> Text
pluralFormsFor Text
"pt-BR" Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Text -> Text
pluralFormsFor Text
"pt"
  ,FilePath -> IO () -> TestTree
testCase FilePath
"commonPluralForms" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$
     ((Text, Text) -> IO ()) -> [(Text, Text)] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (\(Text
l, Text
r) -> case Text -> Maybe PluralForms
parsePluralForms Text
r of
       Maybe PluralForms
Nothing -> FilePath -> IO ()
forall a. HasCallStack => FilePath -> IO a
assertFailure (FilePath -> IO ()) -> FilePath -> IO ()
forall a b. (a -> b) -> a -> b
$ Text -> FilePath
T.unpack Text
l FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
": could not parse " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ Text -> FilePath
T.unpack Text
r
       Just PluralForms
pf -> HasCallStack => FilePath -> Bool -> IO ()
FilePath -> Bool -> IO ()
assertBool (Text -> FilePath
T.unpack Text
l FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
": a form number out of range") (Bool -> IO ()) -> Bool -> IO ()
forall a b. (a -> b) -> a -> b
$
         (Int -> Bool) -> [Int] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (\Int
n -> let i :: Int
i = PluralForms -> Int -> Int
pfRule PluralForms
pf Int
n in Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
0 Bool -> Bool -> Bool
&& Int
i Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< PluralForms -> Int
pfCount PluralForms
pf) [Int
0..Int
1000])
       [(Text, Text)]
commonPluralForms
  ]
  where
    checkBuiltin :: (Text, ByteString) -> IO ()
checkBuiltin (Text
lang, ByteString
bs) = do
      -- --lang values are normalized before lookup, so a tag that is not can never be selected
      FilePath -> Maybe Text -> Maybe Text -> IO ()
forall a.
(Eq a, Show a, HasCallStack) =>
FilePath -> a -> a -> IO ()
assertEqual (FilePath
"built-in catalog tag " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ Text -> FilePath
forall a. Show a => a -> FilePath
show Text
lang FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
" is not normalized") (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
lang) (Text -> Maybe Text
normalizeLangTag Text
lang)
      s <- (UnicodeException -> IO Text)
-> (Text -> IO Text) -> Either UnicodeException Text -> IO Text
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (\UnicodeException
e -> FilePath -> IO Text
forall a. HasCallStack => FilePath -> IO a
assertFailure (FilePath -> IO Text) -> FilePath -> IO Text
forall a b. (a -> b) -> a -> b
$ Text -> FilePath
T.unpack Text
lang FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ FilePath
": not UTF-8: " FilePath -> ShowS
forall a. [a] -> [a] -> [a]
++ UnicodeException -> FilePath
forall a. Show a => a -> FilePath
show UnicodeException
e) Text -> IO Text
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either UnicodeException Text -> IO Text)
-> Either UnicodeException Text -> IO Text
forall a b. (a -> b) -> a -> b
$ ByteString -> Either UnicodeException Text
TE.decodeUtf8' ByteString
bs
      t <- either assertFailure return $ parsePo (T.unpack lang) lang s
      assertEqual (T.unpack lang ++ " translations with wrong placeholders") [] (snd $ withoutPlaceholderMismatches t)

samplePo :: Text
samplePo :: Text
samplePo = [Text] -> Text
T.unlines
  [ Text
"# German translations for the tests."
  , Text
"#, fuzzy"
  , Text
"msgid \"\""
  , Text
"msgstr \"\""
  , Text
"\"Project-Id-Version: hledger\\n\""
  , Text
"\"Language: de\\n\""
  , Text
"\"Content-Type: text/plain; charset=UTF-8\\n\""
  , Text
"\"Plural-Forms: nplurals=2; plural=(n != 1);\\n\""
  , Text
""
  , Text
"#. Report title."
  , Text
"#: hledger/Hledger/Cli/Commands/Balancesheet.hs:23"
  , Text
"#, python-brace-format"
  , Text
"msgid \"Balance Sheet\""
  , Text
"msgstr \"Bilanz\""
  , Text
""
  , Text
"msgid \"Untranslated\""
  , Text
"msgstr \"\""
  , Text
""
  , Text
"msgid \"Empty\""
  , Text
"msgstr \"\""
  , Text
""
  , Text
"#, fuzzy, python-brace-format"
  , Text
"#| msgid \"Fuzy\""
  , Text
"msgid \"Fuzzy\""
  , Text
"msgstr \"Unscharf\""
  , Text
""
  , Text
"msgctxt \"column heading\""
  , Text
"msgid \"Total\""
  , Text
"msgstr \"Summe\""
  , Text
""
  , Text
"msgid \"Multi\""
  , Text
"msgstr \"\""
  , Text
"  \"line one\\n\""
  , Text
"  \"line two \\\"quoted\\\" \\\\ \\374 \\x41\""
  , Text
""
  , Text
"msgid \"{n} day\""
  , Text
"msgid_plural \"{n} days\""
  , Text
"msgstr[0] \"{n} Tag\""
  , Text
"msgstr[1] \"{n} Tage\""
  , Text
""
  , Text
"msgid \"Balance changes in {period}:\""
  , Text
"msgstr \"Saldo\228nderungen in {period}:\""
  , Text
""
  , Text
"#~ msgid \"Obsolete\""
  , Text
"#~ msgstr \"Veraltet\""
  ]