{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
module System.IO.Utf8.Internal
( EncodingAction (..)
, chooseBestEncPure
, chooseBestEnc
) where
import Data.List (isSuffixOf)
import GHC.IO.Encoding (TextEncoding, textEncodingName, utf8)
import qualified System.IO as IO
data EncodingAction
= Keep
| ChangeFromTo TextEncoding String
chooseBestEncPure
:: Bool
-> Maybe String
-> Maybe String
chooseBestEncPure :: Bool -> Maybe String -> Maybe String
chooseBestEncPure _ Nothing = Maybe String
forall a. Maybe a
Nothing
chooseBestEncPure _ (Just "UTF-8") = Maybe String
forall a. Maybe a
Nothing
chooseBestEncPure False _ = String -> Maybe String
forall a. a -> Maybe a
Just "UTF-8"
chooseBestEncPure True (Just name :: String
name)
| "//TRANSLIT" String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isSuffixOf` String
name = Maybe String
forall a. Maybe a
Nothing
| Bool
otherwise = String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$ String
name String -> String -> String
forall a. [a] -> [a] -> [a]
++ "//TRANSLIT"
chooseBestEnc
:: IO.Handle
-> (IO.Handle -> IO Bool)
-> Maybe TextEncoding
-> IO EncodingAction
chooseBestEnc :: Handle
-> (Handle -> IO Bool) -> Maybe TextEncoding -> IO EncodingAction
chooseBestEnc _ _ Nothing = EncodingAction -> IO EncodingAction
forall (f :: * -> *) a. Applicative f => a -> f a
pure EncodingAction
Keep
chooseBestEnc h :: Handle
h hIsTerm :: Handle -> IO Bool
hIsTerm (Just enc :: TextEncoding
enc) = case TextEncoding -> String
textEncodingName TextEncoding
enc of
"UTF-8" -> EncodingAction -> IO EncodingAction
forall (f :: * -> *) a. Applicative f => a -> f a
pure EncodingAction
Keep
name :: String
name
| "//TRANSLIT" String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isSuffixOf` String
name -> EncodingAction -> IO EncodingAction
forall (f :: * -> *) a. Applicative f => a -> f a
pure EncodingAction
Keep
| Bool
otherwise -> Handle -> IO Bool
hIsTerm Handle
h IO Bool -> (Bool -> IO EncodingAction) -> IO EncodingAction
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
False -> EncodingAction -> IO EncodingAction
forall (f :: * -> *) a. Applicative f => a -> f a
pure (EncodingAction -> IO EncodingAction)
-> EncodingAction -> IO EncodingAction
forall a b. (a -> b) -> a -> b
$ TextEncoding -> String -> EncodingAction
ChangeFromTo TextEncoding
enc (TextEncoding -> String
textEncodingName TextEncoding
utf8)
True -> EncodingAction -> IO EncodingAction
forall (f :: * -> *) a. Applicative f => a -> f a
pure (EncodingAction -> IO EncodingAction)
-> EncodingAction -> IO EncodingAction
forall a b. (a -> b) -> a -> b
$ TextEncoding -> String -> EncodingAction
ChangeFromTo TextEncoding
enc (String
name String -> String -> String
forall a. [a] -> [a] -> [a]
++ "//TRANSLIT")