{-# OPTIONS_HADDOCK hide #-}
module BuildBox.Build.Base where
import BuildBox.Pretty
import BuildBox.Build.BuildError
import BuildBox.Build.BuildState
import Control.Monad.Catch
import Control.Monad.State
import System.IO
import System.Directory
import qualified Data.Text as T
type Build a = StateT BuildState IO a
runBuild :: FilePath -> Build a -> IO (Either BuildError a)
runBuild scratchDir build
= do let s = buildStateDefault scratchDir
try $ evalStateT build s
runBuildPrint :: FilePath -> Build a -> IO (Maybe a)
runBuildPrint scratchDir build
= do let s = buildStateDefault scratchDir
runBuildPrintWithState s build
runBuildWithState :: BuildState -> Build a -> IO (Maybe a)
runBuildWithState s build
= do result <- try $ evalStateT build s
case result of
Left (err :: BuildError)
-> do putStrLn $ T.unpack $ ppr err
return $ Nothing
Right x
-> do return $ Just x
runBuildPrintWithState :: BuildState -> Build a -> IO (Maybe a)
runBuildPrintWithState s build
= do result <- try $ evalStateT build s
case result of
Left (err :: BuildError)
-> do putStrLn "\nBuild failed"
putStr " due to "
putStrLn $ T.unpack $ ppr err
return $ Nothing
Right x
-> do putStrLn "Build succeeded."
return $ Just x
successfully :: IO a -> IO ()
successfully f = f >> return ()
needs :: FilePath -> Build ()
needs filePath
= do isFile <- io $ doesFileExist filePath
isDir <- io $ doesDirectoryExist filePath
if isFile || isDir
then return ()
else throwM $ ErrorNeeds filePath
io :: IO a -> Build a
io x
= do
result <- liftIO $ try x
case result of
Left err -> throwM $ ErrorIOError err
Right res -> return res
whenM :: Monad m => m Bool -> m () -> m ()
whenM cb cx
= do b <- cb
if b then cx else return ()
out :: Text -> Build ()
out tx
= io
$ do putStr $ T.unpack tx
hFlush stdout
outLn :: Text -> Build ()
outLn tx = io $ putStrLn $ T.unpack tx
outBlank :: Build ()
outBlank = out $ string "\n"
outLine :: Build ()
outLine = io $ putStr (replicate 80 '-' ++ "\n")
outLINE :: Build ()
outLINE = io $ putStr (replicate 80 '=' ++ "\n")