git-annex/Utility/HumanTime.hs

102 lines
2.2 KiB
Haskell
Raw Normal View History

{- Time for humans.
-
- Copyright 2012-2013 Joey Hess <joey@kitenet.net>
-
- License: BSD-2-clause
-}
module Utility.HumanTime (
Duration(..),
2014-01-23 19:09:43 +00:00
durationSince,
durationToPOSIXTime,
2014-01-23 19:09:43 +00:00
durationToDays,
daysToDuration,
parseDuration,
fromDuration,
2013-10-08 21:35:25 +00:00
prop_duration_roundtrips
) where
import Utility.PartialPrelude
import Utility.Applicative
2013-10-08 21:35:25 +00:00
import Utility.QuickCheck
2014-01-23 19:09:43 +00:00
import Data.Time.Clock
import Data.Time.Clock.POSIX (POSIXTime)
import Data.Char
2013-10-08 21:35:25 +00:00
import Control.Applicative
import qualified Data.Map as M
newtype Duration = Duration { durationSeconds :: Integer }
deriving (Eq, Ord, Read, Show)
2014-01-23 19:09:43 +00:00
durationSince :: UTCTime -> IO Duration
durationSince pasttime = do
now <- getCurrentTime
return $ Duration $ round $ diffUTCTime now pasttime
durationToPOSIXTime :: Duration -> POSIXTime
durationToPOSIXTime = fromIntegral . durationSeconds
2014-01-23 19:09:43 +00:00
durationToDays :: Duration -> Integer
durationToDays d = durationSeconds d `div` dsecs
daysToDuration :: Integer -> Duration
daysToDuration i = Duration $ i * dsecs
{- Parses a human-input time duration, of the form "5h", "1m", "5h1m", etc -}
parseDuration :: String -> Maybe Duration
parseDuration = Duration <$$> go 0
2012-12-13 04:24:19 +00:00
where
go n [] = return n
go n s = do
num <- readish s :: Maybe Integer
2013-10-26 16:07:00 +00:00
case dropWhile isDigit s of
(c:rest) -> do
u <- M.lookup c unitmap
go (n + num * u) rest
_ -> return $ n + num
fromDuration :: Duration -> String
2013-10-08 21:35:25 +00:00
fromDuration Duration { durationSeconds = d }
| d == 0 = "0s"
2014-04-26 23:25:05 +00:00
| otherwise = concatMap showunit $ go [] units d
where
showunit (u, n)
| n > 0 = show n ++ [u]
| otherwise = ""
go c [] _ = reverse c
2013-10-08 21:35:25 +00:00
go c ((u, n):us) v =
let (q,r) = v `quotRem` n
in go ((u, q):c) us r
units :: [(Char, Integer)]
units =
[ ('y', ysecs)
, ('d', dsecs)
, ('h', hsecs)
, ('m', msecs)
, ('s', 1)
]
unitmap :: M.Map Char Integer
unitmap = M.fromList units
ysecs :: Integer
ysecs = dsecs * 365
dsecs :: Integer
dsecs = hsecs * 24
hsecs :: Integer
hsecs = msecs * 60
msecs :: Integer
msecs = 60
2013-10-08 21:35:25 +00:00
-- Durations cannot be negative.
instance Arbitrary Duration where
arbitrary = Duration <$> nonNegative arbitrary
prop_duration_roundtrips :: Duration -> Bool
prop_duration_roundtrips d = parseDuration (fromDuration d) == Just d