module Hakyll.Core.Store
( Store
, makeStore
, storeSet
, storeGet
) where
import Control.Concurrent.MVar (MVar, newMVar, readMVar, modifyMVar_)
import System.FilePath ((</>))
import System.Directory (doesFileExist)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Binary (Binary, encodeFile, decodeFile)
import Data.Typeable (Typeable)
import Hakyll.Core.CompiledItem
import Hakyll.Core.Writable
import Hakyll.Core.Identifier
import Hakyll.Core.Util.File
data Store = Store
{
storeDirectory :: FilePath
,
storeMap :: MVar (Map FilePath CompiledItem)
}
makeStore :: FilePath -> IO Store
makeStore directory = do
mvar <- newMVar M.empty
return Store
{ storeDirectory = directory
, storeMap = mvar
}
addToMap :: (Binary a, Typeable a, Writable a)
=> Store -> FilePath -> a -> IO ()
addToMap store path value =
modifyMVar_ (storeMap store) $ return . M.insert path (compiledItem value)
makePath :: Store -> String -> Identifier -> FilePath
makePath store name identifier =
storeDirectory store </> name </> toFilePath identifier </> ".hakyllstore"
storeSet :: (Binary a, Typeable a, Writable a)
=> Store -> String -> Identifier -> a -> IO ()
storeSet store name identifier value = do
makeDirectories path
encodeFile path value
addToMap store path value
where
path = makePath store name identifier
storeGet :: (Binary a, Typeable a, Writable a)
=> Store -> String -> Identifier -> IO (Maybe a)
storeGet store name identifier = do
map' <- readMVar $ storeMap store
case M.lookup path map' of
Just c -> return $ Just $ unCompiledItem c
Nothing -> do
exists <- doesFileExist path
if not exists
then return Nothing
else do v <- decodeFile path
addToMap store path v
return $ Just v
where
path = makePath store name identifier