module Simulation.Aivika.Experiment.ExperimentWriter
(ExperimentWriter,
runExperimentWriter,
ExperimentFilePath(..),
resolveFilePath,
expandFilePath,
mapFilePath) where
import Control.Applicative
import Control.Monad
import Control.Monad.Trans
import Control.Monad.State
import qualified Data.Map as M
import qualified Data.Set as S
import System.Directory
import System.FilePath
import Simulation.Aivika.Experiment.MRef
import Simulation.Aivika.Experiment.Utils (replace)
data ExperimentFilePath = WritableFilePath FilePath
| UniqueFilePath FilePath
resolveFilePath :: FilePath -> ExperimentFilePath -> ExperimentWriter FilePath
resolveFilePath dir (WritableFilePath path) =
return $ dir </> path
resolveFilePath dir (UniqueFilePath path) =
ExperimentWriter $ \r ->
let (name, ext) = splitExtension path
loop y i =
do let n = dir </> addExtension y ext
y' = name ++ "(" ++ show i ++ ")"
f1 <- doesFileExist n
f2 <- doesDirectoryExist n
if f1 || f2
then loop y' (i + 1)
else do n' <- liftIO $
modifyMRef r $ \s ->
if S.member n s
then return (s, Nothing)
else return (S.insert n s, Just n)
case n' of
Nothing -> loop y' (i + 1)
Just n' -> return n'
in loop name 2
expandFilePath :: ExperimentFilePath -> M.Map String String -> ExperimentFilePath
expandFilePath (WritableFilePath path) map = WritableFilePath (expandTemplates path map)
expandFilePath (UniqueFilePath path) map = UniqueFilePath (expandTemplates path map)
expandTemplates :: String -> M.Map String String -> String
expandTemplates name map = name' where
((), name') = flip runState name $
forM_ (M.assocs map) $ \(k, v) ->
do a <- get
put $ replace k v a
mapFilePath :: (FilePath -> FilePath) -> ExperimentFilePath -> ExperimentFilePath
mapFilePath f (WritableFilePath path) = WritableFilePath (f path)
mapFilePath f (UniqueFilePath path) = UniqueFilePath (f path)
newtype ExperimentWriter a = ExperimentWriter (MRef (S.Set String) -> IO a)
instance Functor ExperimentWriter where
fmap f (ExperimentWriter m) =
ExperimentWriter $ \r -> fmap f (m r)
instance Applicative ExperimentWriter where
pure a =
ExperimentWriter $ \r -> return a
(ExperimentWriter f) <*> (ExperimentWriter m) =
ExperimentWriter $ \r -> f r <*> m r
instance Monad ExperimentWriter where
return a =
ExperimentWriter $ \r -> return a
(ExperimentWriter m) >>= k =
ExperimentWriter $ \r ->
do a <- m r
let ExperimentWriter b = k a
b r
instance MonadIO ExperimentWriter where
liftIO m = ExperimentWriter $ \r -> liftIO m
runExperimentWriter :: ExperimentWriter a -> IO a
runExperimentWriter (ExperimentWriter m) =
do r <- newMRef S.empty
m r