2014-01-20 20:47:56 +00:00
|
|
|
{- git-annex single-value log
|
|
|
|
-
|
|
|
|
- This is used to store a value in a way that can be union merged.
|
|
|
|
-
|
|
|
|
- A line of the log will look like: "timestamp value"
|
|
|
|
-
|
|
|
|
- The line with the newest timestamp wins.
|
|
|
|
-
|
2015-01-21 16:50:09 +00:00
|
|
|
- Copyright 2014 Joey Hess <id@joeyh.name>
|
2014-01-20 20:47:56 +00:00
|
|
|
-
|
|
|
|
- Licensed under the GNU GPL version 3 or higher.
|
|
|
|
-}
|
|
|
|
|
|
|
|
module Logs.SingleValue where
|
|
|
|
|
2016-01-20 20:36:33 +00:00
|
|
|
import Annex.Common
|
2014-01-20 20:47:56 +00:00
|
|
|
import qualified Annex.Branch
|
2015-05-10 18:45:55 +00:00
|
|
|
import Logs.TimeStamp
|
2014-01-20 20:47:56 +00:00
|
|
|
|
|
|
|
import qualified Data.Set as S
|
|
|
|
import Data.Time.Clock.POSIX
|
|
|
|
|
2014-01-21 20:08:19 +00:00
|
|
|
class SingleValueSerializable v where
|
2014-01-20 20:47:56 +00:00
|
|
|
serialize :: v -> String
|
|
|
|
deserialize :: String -> Maybe v
|
|
|
|
|
|
|
|
data LogEntry v = LogEntry
|
|
|
|
{ changed :: POSIXTime
|
|
|
|
, value :: v
|
|
|
|
} deriving (Eq, Show, Ord)
|
|
|
|
|
|
|
|
type Log v = S.Set (LogEntry v)
|
|
|
|
|
2014-01-21 20:08:19 +00:00
|
|
|
showLog :: (SingleValueSerializable v) => Log v -> String
|
2014-01-20 20:47:56 +00:00
|
|
|
showLog = unlines . map showline . S.toList
|
|
|
|
where
|
|
|
|
showline (LogEntry t v) = unwords [show t, serialize v]
|
|
|
|
|
2014-01-21 20:08:19 +00:00
|
|
|
parseLog :: (Ord v, SingleValueSerializable v) => String -> Log v
|
2014-01-20 20:47:56 +00:00
|
|
|
parseLog = S.fromList . mapMaybe parse . lines
|
|
|
|
where
|
|
|
|
parse line = do
|
|
|
|
let (ts, s) = splitword line
|
2015-05-10 18:45:55 +00:00
|
|
|
date <- parsePOSIXTime ts
|
2014-01-20 20:47:56 +00:00
|
|
|
v <- deserialize s
|
|
|
|
Just (LogEntry date v)
|
|
|
|
splitword = separate (== ' ')
|
|
|
|
|
|
|
|
newestValue :: Log v -> Maybe v
|
|
|
|
newestValue s
|
|
|
|
| S.null s = Nothing
|
|
|
|
| otherwise = Just (value $ S.findMax s)
|
|
|
|
|
2014-01-21 20:08:19 +00:00
|
|
|
readLog :: (Ord v, SingleValueSerializable v) => FilePath -> Annex (Log v)
|
2014-01-20 20:47:56 +00:00
|
|
|
readLog = parseLog <$$> Annex.Branch.get
|
|
|
|
|
2014-01-21 20:08:19 +00:00
|
|
|
getLog :: (Ord v, SingleValueSerializable v) => FilePath -> Annex (Maybe v)
|
2014-01-20 20:47:56 +00:00
|
|
|
getLog = newestValue <$$> readLog
|
|
|
|
|
2014-01-21 20:08:19 +00:00
|
|
|
setLog :: (SingleValueSerializable v) => FilePath -> v -> Annex ()
|
2014-01-20 20:47:56 +00:00
|
|
|
setLog f v = do
|
2014-10-09 19:09:26 +00:00
|
|
|
now <- liftIO getPOSIXTime
|
|
|
|
let ent = LogEntry now v
|
2014-01-20 20:47:56 +00:00
|
|
|
Annex.Branch.change f $ \_old -> showLog (S.singleton ent)
|