blob: 7a4637f3a630c7fff08366e2ccb4da0a1b4d785d (
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
49
50
51
52
53
54
55
56
57
58
59
60
|
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE OverloadedRecordDot #-}
module Store
( commitDocument,
replaceDocument,
)
where
import Control.Exception (Exception, throwIO)
import Data.Aeson qualified as J
import Data.ByteString.Lazy qualified as LB
import Data.Default (Default (def))
import Data.List (intercalate)
import Data.String (IsString (fromString))
import Document qualified as D
import ProbabilityMap qualified as C
import System.Directory (copyFile)
import System.Exit (ExitCode (ExitFailure, ExitSuccess))
import System.IO.LockFile (withLockFile)
import System.Process.Typed (readProcessStderr)
import Text.Printf (printf)
replaceDocument :: String -> D.Document -> IO ()
replaceDocument message doc = do
withGit do
J.encodeFile doc.iFilePath doc.index
oldDoc <- D.readDocument doc.iFileName
_ <- C.modifyProbabilityCache (C.replaceDocument oldDoc doc)
commitAll [doc.iFilePath, C.fileName] message
commitDocument :: String -> FilePath -> D.Document -> IO ()
commitDocument message original doc = do
withGit do
copyFile original doc.oFilePath
J.encodeFile doc.iFilePath doc.index
_ <- C.modifyProbabilityCache (C.addDocument doc)
commitAll [doc.iFilePath, doc.oFilePath, C.fileName] message
withGit :: IO a -> IO a
withGit = withLockFile def ".gitlock"
commitAll :: [FilePath] -> String -> IO ()
commitAll fps m = do
sh_ (">/dev/null git add -- " ++ intercalate " " (map (printf "'%s'") fps))
sh_ (printf ">/dev/null git commit -m '%s' || :" m)
-- TODO Refacotor library `sh`
sh_ :: String -> IO ()
sh_ cmd = do
-- printf "+ %s\n" cmd
(exitCode, err) <- readProcessStderr (fromString cmd)
case exitCode of
ExitSuccess -> return ()
ExitFailure exitCode' -> throwIO $ ProcessException exitCode' err
data ProcessException = ProcessException Int LB.ByteString
deriving (Show)
instance Exception ProcessException
|