-- | See GHC #10762 and #15021.
module GHC.HandleEncoding (configureHandleEncoding) where

import Prelude -- See note [Why do we import Prelude here?]
import GHC.IO.Encoding (textEncodingName)
import System.Environment
import System.IO

-- | Handle GHC-specific character encoding flags, allowing us to control how
-- GHC produces output regardless of OS.
configureHandleEncoding :: IO ()
configureHandleEncoding :: IO ()
configureHandleEncoding = do
   mb_val <- String -> IO (Maybe String)
lookupEnv String
"GHC_CHARENC"
   case mb_val of
    Just String
"UTF-8" -> do
     Handle -> TextEncoding -> IO ()
hSetEncoding Handle
stdout TextEncoding
utf8
     Handle -> TextEncoding -> IO ()
hSetEncoding Handle
stderr TextEncoding
utf8
    Maybe String
_ -> do
     -- Avoid GHC erroring out when trying to display unhandled characters
     Handle -> IO ()
hSetTranslit Handle
stdout
     Handle -> IO ()
hSetTranslit Handle
stderr

-- | Change the character encoding of the given Handle to transliterate
-- on unsupported characters instead of throwing an exception
hSetTranslit :: Handle -> IO ()
hSetTranslit :: Handle -> IO ()
hSetTranslit Handle
h = do
    menc <- Handle -> IO (Maybe TextEncoding)
hGetEncoding Handle
h
    case fmap textEncodingName menc of
        Just String
name | Char
'/' Char -> String -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` String
name -> do
            enc' <- String -> IO TextEncoding
mkTextEncoding (String -> IO TextEncoding) -> String -> IO TextEncoding
forall a b. (a -> b) -> a -> b
$ String
name String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"//TRANSLIT"
            hSetEncoding h enc'
        Maybe String
_ -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()