module Hix.Data.ProjectFile where

import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Reader (ask)
import qualified Data.Text.IO as Text
import Path (File, Path, Rel, parent, toFilePath, (</>))
import Path.IO (createDirIfMissing)

import Hix.Data.Error (tryIO)
import qualified Hix.Monad
import Hix.Monad (Env (Env), M)

data ProjectFile =
  ProjectFile {
    ProjectFile -> Path Rel File
path :: Path Rel File,
    ProjectFile -> Text
content :: Text
  }
  deriving stock (ProjectFile -> ProjectFile -> Bool
(ProjectFile -> ProjectFile -> Bool)
-> (ProjectFile -> ProjectFile -> Bool) -> Eq ProjectFile
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ProjectFile -> ProjectFile -> Bool
== :: ProjectFile -> ProjectFile -> Bool
$c/= :: ProjectFile -> ProjectFile -> Bool
/= :: ProjectFile -> ProjectFile -> Bool
Eq, Int -> ProjectFile -> ShowS
[ProjectFile] -> ShowS
ProjectFile -> String
(Int -> ProjectFile -> ShowS)
-> (ProjectFile -> String)
-> ([ProjectFile] -> ShowS)
-> Show ProjectFile
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ProjectFile -> ShowS
showsPrec :: Int -> ProjectFile -> ShowS
$cshow :: ProjectFile -> String
show :: ProjectFile -> String
$cshowList :: [ProjectFile] -> ShowS
showList :: [ProjectFile] -> ShowS
Show, (forall x. ProjectFile -> Rep ProjectFile x)
-> (forall x. Rep ProjectFile x -> ProjectFile)
-> Generic ProjectFile
forall x. Rep ProjectFile x -> ProjectFile
forall x. ProjectFile -> Rep ProjectFile x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. ProjectFile -> Rep ProjectFile x
from :: forall x. ProjectFile -> Rep ProjectFile x
$cto :: forall x. Rep ProjectFile x -> ProjectFile
to :: forall x. Rep ProjectFile x -> ProjectFile
Generic)

createFile :: ProjectFile -> M ()
createFile :: ProjectFile -> M ()
createFile ProjectFile
f = do
  Env {Path Abs Dir
cwd :: Path Abs Dir
$sel:cwd:Env :: Env -> Path Abs Dir
cwd} <- ReaderT Env (ExceptT Error IO) Env
forall (m :: * -> *) r. Monad m => ReaderT r m r
ask
  let
    file :: Path Abs File
file = Path Abs Dir
cwd Path Abs Dir -> Path Rel File -> Path Abs File
forall b t. Path b Dir -> Path Rel t -> Path b t
</> ProjectFile
f.path
  ExceptT Error IO () -> M ()
forall (m :: * -> *) a. Monad m => m a -> ReaderT Env m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ExceptT Error IO () -> M ()) -> ExceptT Error IO () -> M ()
forall a b. (a -> b) -> a -> b
$ IO () -> ExceptT Error IO ()
forall a. IO a -> ExceptT Error IO a
tryIO do
    Bool -> Path Abs Dir -> IO ()
forall (m :: * -> *) b. MonadIO m => Bool -> Path b Dir -> m ()
createDirIfMissing Bool
True (Path Abs File -> Path Abs Dir
forall b t. Path b t -> Path b Dir
parent Path Abs File
file)
    String -> Text -> IO ()
Text.writeFile (Path Abs File -> String
forall b t. Path b t -> String
toFilePath Path Abs File
file) ProjectFile
f.content