module Test.Hspec.Util (
pluralize
, lineBreaksAt
, safeTry
, Path
, filterPredicate
, formatRequirement
, readMaybe
, getEnv
, strip
, stdGenToInteger
, stdGenFromInteger
) where
import Data.Int (Int32)
import Data.List
import Data.Maybe
import Data.Char (isSpace)
import Control.Applicative
import qualified Control.Exception as E
import qualified System.Environment as Environment
import System.Random (StdGen)
pluralize :: Int -> String -> String
pluralize 1 s = "1 " ++ s
pluralize n s = show n ++ " " ++ s ++ "s"
safeTry :: IO a -> IO (Either E.SomeException a)
safeTry action = (Right <$> (action >>= E.evaluate)) `E.catches` [
E.Handler $ \e -> E.throwIO (e :: E.AsyncException)
, E.Handler $ \e -> (return . Left) (e :: E.SomeException)
]
type Path = ([String], String)
filterPredicate :: String -> Path -> Bool
filterPredicate pattern path@(groups, requirement) =
pattern `isInfixOf` plain
|| pattern `isInfixOf` formatted
where
plain = intercalate "/" (groups ++ [requirement])
formatted = formatRequirement path
formatRequirement :: Path -> String
formatRequirement (groups, requirement) = groups_ ++ requirement
where
groups_ = case break (any isSpace) groups of
([], ys) -> join ys
(xs, ys) -> join (intercalate "." xs : ys)
join xs = case xs of
[x] -> x ++ " "
ys -> concatMap (++ ", ") ys
readMaybe :: Read a => String -> Maybe a
readMaybe = fmap fst . listToMaybe . reads
getEnv :: String -> IO (Maybe String)
getEnv key = either (const Nothing) Just <$> safeTry (Environment.getEnv key)
lineBreaksAt :: Int -> String -> [String]
lineBreaksAt n input = case words input of
[] -> []
x:xs -> go (x, xs)
where
go :: (String, [String]) -> [String]
go c = case c of
(s, []) -> [s]
(s, y:ys) -> let r = s ++ " " ++ y in
if length r <= n
then go (r, ys)
else s : go (y, ys)
strip :: String -> String
strip = dropWhile isSpace . reverse . dropWhile isSpace . reverse
stdGenToInteger :: StdGen -> Integer
stdGenToInteger stdGen =
let [a, b] = map read . words $ show stdGen
in b * fromIntegral (maxBound :: Int32) + a
stdGenFromInteger :: Integer -> StdGen
stdGenFromInteger n =
let (a, b) = quotRem n (fromIntegral (maxBound :: Int32))
in read (show b ++ " " ++ show a)