module System.Handsy where
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as C
import System.Exit
import Control.Monad.Trans.Free
import System.Process.ByteString.Lazy
import System.Handsy.Internal (HandsyF (..))
import qualified System.Handsy.Internal as T
type Handsy = FreeT T.HandsyF IO
command :: FilePath
-> [String]
-> B.ByteString
-> Handsy (ExitCode, B.ByteString, B.ByteString)
command = T.command
readFile :: FilePath -> Handsy B.ByteString
readFile = T.readFile
writeFile :: FilePath -> B.ByteString -> Handsy ()
writeFile = T.writeFile
appendFile :: FilePath -> B.ByteString -> Handsy ()
appendFile = T.appendFile
shell :: String
-> B.ByteString
-> Handsy (ExitCode, B.ByteString, B.ByteString)
shell cmd stdin = command "/usr/bin/env" ["sh", "-c", cmd] stdin
shell_ :: String -> B.ByteString -> Handsy (B.ByteString, B.ByteString)
shell_ cmd stdin = shell cmd stdin >>= \case
(ExitFailure code, _, stderr) -> error ('`':cmd ++ "` returned " ++ show code
++ "\nStderr was: " ++ (C.unpack stderr))
(ExitSuccess, stdout, stderr) -> return (stdout, stderr)
command_ :: FilePath -> [String] -> B.ByteString -> Handsy (B.ByteString, B.ByteString)
command_ path args stdin = command path args stdin >>= \case
(ExitFailure code, _, stderr) -> error ('`':path ++ ' ' :(show args) ++ "` returned " ++ show code
++ "\nStderr was: " ++ (C.unpack stderr))
(ExitSuccess, stdout, stderr) -> return (stdout, stderr)
run :: Handsy a -> IO a
run h = do
x <- runFreeT h
case x of
Pure r -> return r
Free (ReadFile fp next)
-> B.readFile fp >>= run . next
Free (WriteFile fp str next)
-> B.writeFile fp str >>= run . next
Free (AppendFile fp str next)
-> B.appendFile fp str >>= run . next
Free (Command prg args stdin next)
-> readProcessWithExitCode prg args stdin >>= run . next