{-# LANGUAGE LambdaCase #-}
module MBug.Cache (cachedIO, cachedIO_) where
import qualified Data.ByteString.Lazy as BL
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock (diffUTCTime, getCurrentTime)
import System.Directory
( createDirectoryIfMissing
, doesFileExist
, getModificationTime
)
import System.Environment.XDG.BaseDir
( getUserCacheDir
, getUserCacheFile
)
isCacheFileStale :: FilePath -> IO Bool
isCacheFileStale path =
doesFileExist path >>= \case
False -> pure False
True -> do
now <- getCurrentTime
mtime <- getModificationTime path
pure $ diffUTCTime now mtime < 900
cachedIO :: Text -> IO BL.ByteString -> IO (FilePath, BL.ByteString)
cachedIO label action = do
getUserCacheDir "mbug" >>= createDirectoryIfMissing True
cache <- getUserCacheFile "mbug" (T.unpack label)
isCacheFileStale cache >>= \case
True -> (,) <$> pure cache <*> BL.readFile cache
False -> action >>= \output -> do BL.writeFile cache output
pure (cache, output)
cachedIO_ :: Text -> IO BL.ByteString -> IO BL.ByteString
cachedIO_ label action = fmap snd $ cachedIO label action