{-# LANGUAGE CPP, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module System.Process.Text.Lazy where

#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
import Control.DeepSeq (force)
import qualified Control.Exception as C (evaluate)
import Data.ListLike.IO (hGetContents)
import Data.Text.Lazy (Text, fromStrict, toChunks)
import Prelude hiding (null)
import System.Process
import System.Process.Common
import System.Exit (ExitCode)

instance ProcessText Text Char

-- | Like 'System.Process.readProcessWithExitCode', but using 'Text'
instance ListLikeProcessIO Text Char where
    forceOutput :: Text -> IO Text
forceOutput = Text -> IO Text
forall a. a -> IO a
C.evaluate (Text -> IO Text) -> (Text -> Text) -> Text -> IO Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
forall a. NFData a => a -> a
force
    readChunks :: Handle -> IO [Text]
readChunks Handle
h = ((StrictText -> Text) -> [StrictText] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map StrictText -> Text
fromStrict ([StrictText] -> [Text])
-> (Text -> [StrictText]) -> Text -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [StrictText]
toChunks) (Text -> [Text]) -> IO Text -> IO [Text]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Handle -> IO Text
forall full item. ListLikeIO full item => Handle -> IO full
hGetContents Handle
h

-- | Specialized version for backwards compatibility.
readProcessWithExitCode
    :: FilePath                  -- ^ command to run
    -> [String]                  -- ^ any arguments
    -> Text                      -- ^ standard input
    -> IO (ExitCode, Text, Text) -- ^ exitcode, stdout, stderr
readProcessWithExitCode :: FilePath -> [FilePath] -> Text -> IO (ExitCode, Text, Text)
readProcessWithExitCode = FilePath -> [FilePath] -> Text -> IO (ExitCode, Text, Text)
forall text char.
ListLikeProcessIO text char =>
FilePath -> [FilePath] -> text -> IO (ExitCode, text, text)
System.Process.Common.readProcessWithExitCode

readCreateProcessWithExitCode
    :: CreateProcess             -- ^ command and arguments to run
    -> Text                      -- ^ standard input
    -> IO (ExitCode, Text, Text) -- ^ exitcode, stdout, stderr
readCreateProcessWithExitCode :: CreateProcess -> Text -> IO (ExitCode, Text, Text)
readCreateProcessWithExitCode = CreateProcess -> Text -> IO (ExitCode, Text, Text)
forall maker text char.
(ProcessMaker maker, ListLikeProcessIO text char) =>
maker -> text -> IO (ExitCode, text, text)
System.Process.Common.readCreateProcessWithExitCode