module System.Handsy
( Handsy
, run
, command
, readFile
, writeFile
, appendFile
, shell
, command_
, shell_
, Options (..)
, options
, ExitCode (..)
) where
import Prelude hiding (appendFile, readFile,
writeFile)
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as C
import System.Exit
import System.Process.ByteString.Lazy
import System.Handsy.Core hiding (command)
import qualified System.Handsy.Core as I
command :: FilePath
-> [String]
-> B.ByteString
-> Handsy (ExitCode, B.ByteString, B.ByteString)
command = I.command
readFile :: FilePath -> Handsy B.ByteString
readFile fp = command "cat" [fp] "" >>= \case
(ExitSuccess, stdin, _) -> return stdin
_ -> error $ "Error reading " ++ fp
writeFile :: FilePath -> B.ByteString -> Handsy ()
writeFile fp s = command "dd" ["of=" ++ fp] s >>= \case
(ExitSuccess, _, _) -> return ()
_ -> error $ "Error writing to " ++ fp
appendFile :: FilePath -> B.ByteString -> Handsy ()
appendFile fp s = command "dd" ["of=" ++ fp, "conv=notrunc", "oflag=append"] s >>= \case
(ExitSuccess, _, _) -> return ()
_ -> error $ "Error appending to " ++ fp
shell :: String
-> B.ByteString
-> Handsy (ExitCode, B.ByteString, B.ByteString)
shell cmd = command "sh" ["-c", cmd]
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)
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)
run :: Options -> Handsy a -> IO a
run = interpretSimple readProcessWithExitCode