module Test.Hspec.Util (
quantify
, safeEvaluate
, Path
, filterPredicate
, formatRequirement
, readMaybe
, getEnv
) where
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
quantify :: Int -> String -> String
quantify 1 s = "1 " ++ s
quantify n s = show n ++ " " ++ s ++ "s"
safeEvaluate :: IO a -> IO (Either E.SomeException a)
safeEvaluate action = (Right <$> action) `E.catches` [
E.Handler $ \e -> E.throw (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 <$> safeEvaluate (Environment.getEnv key)