aboutsummaryrefslogtreecommitdiffstats
path: root/app/Cache.hs
blob: 4540fa4dce51a6a700ace44ea95b04ee07fd4d77 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
module Cache
  ( cached,
    cachedMaybe,
  )
where

-- TODO Reduce cached data size
--
-- Right now we are caching complete `Issue` instances, which
-- contain the full issue title and description.  For a fast
-- lookup it may already be enough to only store the issue's
--
-- \* filename
-- \* start position
-- \* end position
--
-- With this information we can use git to quickly look up the
-- complete issue text and parse it.
--
-- @topic caching
-- @backlog

import Data.Binary (Binary, decodeFileOrFail, encodeFile)
import Data.Text qualified as T
import Git qualified
import System.Directory (createDirectoryIfMissing, doesFileExist)
import System.FilePath ((</>))

cached :: Binary a => T.Text -> IO a -> IO a
cached key func = do
  root <- Git.getRootDir
  createDirectoryIfMissing True (root </> ".anissue")
  let file = (root </> ".anissue" </> T.unpack key)
  doesFileExist file >>= \case
    True ->
      decodeFileOrFail file >>= \case
        Left _ -> generate file
        Right blob -> pure blob
    False -> generate file
  where
    generate file = do
      blob <- func
      encodeFile file blob
      pure blob

cachedMaybe :: Binary a => Maybe T.Text -> IO a -> IO a
cachedMaybe Nothing func = func
cachedMaybe (Just key) func = cached key func