-- SPDX-FileCopyrightText: 2020 Tocqueville Group -- -- SPDX-License-Identifier: LicenseRef-MIT-TQ module Util.IO ( readFileUtf8 , writeFileUtf8 , appendFileUtf8 , withEncoding , hSetTranslit ) where import Data.Text.IO (hGetContents) import System.IO (TextEncoding, hGetEncoding, hSetBinaryMode, hSetEncoding, utf8) import Util.IO.GHC (hSetTranslit) readFileUtf8 :: FilePath -> IO Text readFileUtf8 name = openFile name ReadMode >>= \h -> hSetEncoding h utf8 >> hGetContents h writeFileUtf8 :: Print text => FilePath -> text -> IO () writeFileUtf8 name txt = withFile name WriteMode $ \h -> hSetEncoding h utf8 >> hPutStr h txt appendFileUtf8 :: Print text => FilePath -> text -> IO () appendFileUtf8 name txt = withFile name AppendMode $ \h -> hSetEncoding h utf8 >> hPutStr h txt withEncoding :: Handle -> TextEncoding -> IO () -> IO () withEncoding handle encoding action = do mbInitialEncoding <- hGetEncoding handle bracket (hSetEncoding handle encoding) (\_ -> maybe (hSetBinaryMode handle True) (hSetEncoding handle) mbInitialEncoding) (\_ -> action)