module DisTract.Utils
(readFileStrict,
writeFileStrict,
bugIdTimeFormatter,
monotoneDateFormat,
monotoneDateFormatLength,
bugIdDateFormat,
bugIdDateFormatLength,
humanTimeFormat,
intersperseEvery,
formatTimeHuman
)
where
import System.IO
import Data.Time
import Data.Fixed
import System.Locale
readFileStrict :: FilePath -> IO String
readFileStrict file = do { h <- openFile file ReadMode
; str <- hGetContents h
; length str `seq` return ()
; hClose h
; return str
}
writeFileStrict :: FilePath -> String -> IO ()
writeFileStrict file txt = do { h <- openFile file WriteMode
; hPutStr h txt
; hClose h
}
bugIdTimeFormatter :: UTCTime -> String
bugIdTimeFormatter t@(UTCTime { utctDayTime = fromMidnight })
= time ++ "S" ++ millis
where
time = formatTime defaultTimeLocale bugIdDateFormat
t
millis' = (fromMidnight (fromMidnight `mod'` 0.001)) `mod'` 1
millis'' = show ((floor . toRational . (*1000) $ millis') :: Integer)
padding = replicate (3 (length millis'')) '0'
millis = padding ++ millis''
bugIdDateFormat :: String
bugIdDateFormat = "%Y%m%dT%H%M%S"
bugIdDateFormatLength :: Int
bugIdDateFormatLength = 4 + 2 + 2 + 1 + 2 + 2 + 2
monotoneDateFormat :: String
monotoneDateFormat = "%Y-%m-%dT%H:%M:%S"
monotoneDateFormatLength :: Int
monotoneDateFormatLength = 4 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 2
humanTimeFormat :: String
humanTimeFormat = "%c"
intersperseEvery :: Int -> a -> [a] -> [a]
intersperseEvery n sep list
= intersperseEvery' n 1 sep list
where
intersperseEvery' _ _ _ [] = []
intersperseEvery' _ _ _ [x] = [x]
intersperseEvery' n t sep (x:xs)
| n == t = x : sep : intersperseEvery n sep xs
| otherwise = x : intersperseEvery' n (t+1) sep xs
formatTimeHuman :: (FormatTime t) => t -> IO String
formatTimeHuman t
= do { return $ formatTime defaultTimeLocale humanTimeFormat t}