|
| 1 | +{-# LANGUAGE FlexibleInstances #-} |
| 2 | + |
| 3 | +module Import.Utils where |
| 4 | + |
| 5 | +import ClassyPrelude.Yesod (isInfixOf) |
| 6 | +import Data.Text (Text, pack) |
| 7 | +import Data.Time.Clock (UTCTime, diffUTCTime) |
| 8 | +import System.FilePath.Posix (joinPath, normalise, splitPath) |
| 9 | + |
| 10 | +diffInMilliseconds :: UTCTime -> UTCTime -> Int |
| 11 | +diffInMilliseconds t1 t2 = |
| 12 | + let diffSeconds = diffUTCTime t1 t2 |
| 13 | + diffMillis = diffSeconds * 1000 |
| 14 | + in round diffMillis |
| 15 | + |
| 16 | +formatDuration :: Int -> Text |
| 17 | +formatDuration ms = |
| 18 | + let totalSeconds = ms `div` 1000 |
| 19 | + (minutes, seconds) = totalSeconds `divMod` 60 |
| 20 | + pad2 n = if n < 10 then "0" <> show n else show n |
| 21 | + in pack $ pad2 minutes <> ":" <> pad2 seconds |
| 22 | + |
| 23 | +class PathSanitizer a where |
| 24 | + takeBaseName :: a -> FilePath |
| 25 | + |
| 26 | +instance PathSanitizer FilePath where |
| 27 | + takeBaseName = sanitizePath |
| 28 | + |
| 29 | +sanitizePath :: FilePath -> FilePath |
| 30 | +sanitizePath p = |
| 31 | + let (s, suffix) = case span (== '/') p of |
| 32 | + (sl@('/' : '/' : _), rest) -> (sl, rest) |
| 33 | + _ -> ("", dropWhile (== '/') p) |
| 34 | + parts = |
| 35 | + filter |
| 36 | + ( \x -> |
| 37 | + x `notElem` ["./", "../"] |
| 38 | + && not (".." `isInfixOf` x) |
| 39 | + ) |
| 40 | + . splitPath |
| 41 | + . normalise |
| 42 | + $ suffix |
| 43 | + in s ++ joinPath parts |
| 44 | + |
| 45 | +showT :: (Show a) => a -> Text |
| 46 | +showT = pack . show |
0 commit comments